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

情到浓时终转凉″ 提交于 2020-01-01 05:26:06

问题


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


回答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.




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



回答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/




回答4:


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




回答5:


You can also play with various hash algorithms with FooBabel Hasher




回答6:


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



来源:https://stackoverflow.com/questions/5018717/produce-md5-or-sha1-hash-code-to-long-64-bits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!