DoronBM
DoronBM

Reputation: 515

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

Upvotes: 7

Views: 14996

Answers (6)

user975383
user975383

Reputation: 51

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

Upvotes: 1

ggrandes
ggrandes

Reputation: 2133

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

Upvotes: 2

Bobby Whitman
Bobby Whitman

Reputation: 41

You can also play with various hash algorithms with FooBabel Hasher

Upvotes: 0

Jim Mischel
Jim Mischel

Reputation: 134085

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/

Upvotes: 2

Piskvor left the building
Piskvor left the building

Reputation: 92792

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?")

Upvotes: 0

Charles Burns
Charles Burns

Reputation: 10602

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.

Upvotes: 6

Related Questions