How to generate a unique hash code for string input in android...? How to generate a unique hash code for string input in android...? java java

How to generate a unique hash code for string input in android...?


It depends on what you mean:

  • As mentioned String.hashCode() gives you a 32 bit hash code.

  • If you want (say) a 64-bit hashcode you can easily implement it yourself.

  • If you want a cryptographic hash of a String, the Java crypto libraries include implementations of MD5, SHA-1 and so on. You'll typically need to turn the String into a byte array, and then feed that to the hash generator / digest generator. For example, see @Bryan Kemp's answer.

  • If you want a guaranteed unique hash code, you are out of luck. Hashes and hash codes are non-unique.

A Java String of length N has 65536 ^ N possible states, and requires an integer with 16 * N bits to represent all possible values. If you write a hash function that produces integer with a smaller range (e.g. less than 16 * N bits), you will eventually find cases where more than one String hashes to the same integer; i.e. the hash codes cannot be unique. This is called the Pigeonhole Principle, and there is a straight forward mathematical proof. (You can't fight math and win!)

But if "probably unique" with a very small chance of non-uniqueness is acceptable, then crypto hashes are a good answer. The math will tell you how big (i.e. how many bits) the hash has to be to achieve a given (low enough) probability of non-uniqueness.


This is a class I use to create Message Digest hashes

import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class Sha1Hex {    public String makeSHA1Hash(String input)            throws NoSuchAlgorithmException, UnsupportedEncodingException        {            MessageDigest md = MessageDigest.getInstance("SHA1");            md.reset();            byte[] buffer = input.getBytes("UTF-8");            md.update(buffer);            byte[] digest = md.digest();            String hexStr = "";            for (int i = 0; i < digest.length; i++) {                hexStr +=  Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 );            }            return hexStr;        }}


String input = "some input string";int hashCode = input.hashCode();System.out.println("input hash code = " + hashCode);