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 (MD5 - 128 bits, SHA1 - 160 bit).
Ideas any one?
Cheers,
Doron
Whereas SHA1 can have 160 bits length of message digest. 3. The speed of MD5 is fast in comparison of SHA1's speed. While the speed of SHA1 is slow in comparison of MD5's speed.
The MD5 and SHA1 are the hashing algorithms where MD5 is better than SHA in terms of speed. However, SHA1 is more secure as compared to MD5. The concept behind these hashing algorithms is that these are used to generate a unique digital fingerprint of data or message which is known as a hash or digest.
The hash size for the MD5 algorithm is 128 bits. The ComputeHash methods of the MD5 class return the hash as an array of 16 bytes. Note that some MD5 implementations produce a 32-character, hexadecimal-formatted hash.
SHA stands for Secure Hash Algorithm. MD5 can have 128 bits length of digest message. SHA can have 160 bits length of digest message. MD5 is faster than SHA.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With