Unique hex for unique string in java

1k views Asked by At

I want to get a unique hex per unique string. As of now I am using Message Digest class but there are possibilities (very less but still) that for two unique strings, computed hex can be same. So is there any other way to do such thing so that I have unique hex for unique strings.

Thanks in advance.

2

There are 2 answers

11
tobias_k On

(Assuming that you meant hash, not hex, since you mentioned MessageDigest).

You can't have a unique hash code for each unique string. Think of it this way: A hash function maps a string (or any other object) to an integer number. Since each integer number can be represented as a string, e.g. "123", there are at least as many strings as there are different integer numbers -- and then some more, like, everything that is not a number, e.g. "Hello". Thus, as there are more strings than integer numbers, it is not possible to generate unique hash codes for unique strings in all cases.

Having said that, for "everyday hashing" (for hash-tables etc.), the hash function provided by String.hashCode is about as good as it gets. For cryptographic hashing, MessageDigest seems to be the way to go. Depending on what you currently use, you might be able to upgrade to a stronger algorithm, though, e.g. sha-512 instead of sha-256.

2
Bohemian On

Convert each character to a hex value:

String hex = Arrays.stream(str.split(""))
  .map(s -> s.charAt(0) + 0)
  .map(c -> String.format("%4x", c))
  .collect(Collectors.joining(""));