Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (MD5 - 128 bits, SHA1 - 160 bit).

Ideas any one?

Cheers,

Doron

like image 866
DoronBM Avatar asked Feb 16 '11 15:02

DoronBM


People also ask

Which is faster MD5 or SHA1?

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.

What are MD5 and SHA1 hash values?

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.

How long is hash MD5?

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.

What is the correct comparison of SHA 1 and MD5?

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.


2 Answers

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.

like image 71
Charles Burns Avatar answered Sep 16 '22 21:09

Charles Burns


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;
    }
}
like image 29
ggrandes Avatar answered Sep 17 '22 21:09

ggrandes