(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
.