Produce MD5 or SHA1 hash code to long (64 bits)
I need to compute a hash code of a string and store it into a 'long' variable.
MD5 and SHA1 produce hash codes which are longer than 64 bits (MD开发者_JAVA百科5 - 128 bits, SHA1 - 160 bit).
Ideas any one?
Cheers,
Doron
You can truncate the hash and use just the first 64 bits. The hash will be somewhat less strong, but the first 64 bits are still extremely likely to be unique.
For most uses of a hash this is both a common and perfectly acceptable practice.
You can also store the complete hash in two 64-bit integers.
The FNV Hash is pretty easy to implement. We extended it to 64 bits and it works very well. Using it is much faster than computing MD5 or SHA1 and then truncating the result. However, we don't depend on it for cryptographic functions--just for hash tables and such.
More information on FNV, with source code and detailed explanations: http://isthe.com/chongo/tech/comp/fnv/
I'm using this (Java):
public class SimpleLongHash {
final MessageDigest md;
//
public SimpleLongHash() throws NoSuchAlgorithmException {
md = MessageDigest.getInstance("MD5");
}
//
public long hash(final String str) {
return hash(str.getBytes());
}
public long hash(final byte[] buf) {
md.reset();
final byte[] digest = md.digest(buf);
return (getLong(digest, 0) ^ getLong(digest, 8));
}
//
private static final long getLong(final byte[] array, final int offset) {
long value = 0;
for (int i = 0; i < 8; i++) {
value = ((value << 8) | (array[offset+i] & 0xFF));
}
return value;
}
}
What would be the probability for a collision as a result of a XOR between the first 64 bits and the last 64 bits?
XOR the bits together? E.g. for MD5, bits 0-63 XOR bits 64-127, voila, 64 bits. This will give you a weaker hash, check if that's acceptable for you.
(also, unless your environment is extremely constrained - e.g. embedded devices - there's a question of "why do you need to shorten it?")
You can also play with various hash algorithms with FooBabel Hasher
精彩评论