Produce MD5 or SHA1 hash code to long (64 bits)

12,511

Solution 1

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.

Solution 2

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;
    }
}

Solution 3

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/

Solution 4

What would be the probability for a collision as a result of a XOR between the first 64 bits and the last 64 bits?

Share:
12,511
DoronBM
Author by

DoronBM

Updated on June 25, 2022

Comments

  • DoronBM
    DoronBM almost 2 years

    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