Generate MD5 or SHA1 hash in length (64 bits)

I need to calculate the hash code of a string and store it in a "long" variable.

MD5 and SHA1 produce hash codes that are longer than 64 bits (MD5 128 bits, SHA1 160 bits).

Any ideas?

Greetings

Doron

+4
source share
6 answers

You can trim the hash and use only the first 64 bits. The hash will be somewhat less powerful, but the first 64 bits are still extremely unique.

For most hash applications, this is a common and perfectly acceptable practice.

You can also store the full hash in two 64-bit integers.

+3
source

FNV Hash is pretty easy to implement. We have expanded it to 64 bits and it works very well. Using it is much faster than calculating MD5 or SHA1 and then truncating the result. However, we are not dependent on it for cryptographic functions - just for hash tables, etc.

Further information on FNV with source code and detailed explanations: http://isthe.com/chongo/tech/comp/fnv/

+1
source

I am 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; } } 
+1
source

XOR bits together? For instance. for MD5, bit 0-63 bit XOR 64-127, voila, 64 bit. This will give you a weaker hash, check if this is acceptable to you.

(in addition, if your environment is unlimited - for example, embedded devices - the question arises, "why do you need to reduce it?")

0
source

You can also play with various hashing algorithms using FooBabel Hasher

0
source

What is the probability of an XOR collision between the first 64 bits and the last 64 bits?

0
source

Source: https://habr.com/ru/post/1340029/


All Articles