Alan Jurgensen
Alan Jurgensen

Reputation: 863

Convert MD5 to Long

I have a 16byte array from MD5 JAVA method. I want to convert it to a long to use as a hashkey. Am reading a bitwise XOR the bits to 64 is a good idea... then howto get a long from that? full code example of XOR and cvt to long please.

Upvotes: 3

Views: 10062

Answers (3)

Eric J.
Eric J.

Reputation: 150148

The very best solution I found (based on my needs... mix of speed and good hash function) is Google's CityHash. The input can be any byte array including an MD5 result and the output is an unsigned 64-bit long.

CityHash has a very good but not perfect hash distribution, and is very fast.

I ported CityHash from C++ to C# in half an hour. A Java port should be straightforward too.

Just XORing the bits doesn't give as good a distribution (though admittedly that will be very fast).

I'm not familiar enough with Java to tell you exactly how to populate a long from a byte array (there could be a good helper I'm not familiar with, or I could get some details of arithmetic in Java wrong). Essentially, though, you'll want to do something like this:

long a = md5[0] + 
         256 * md5[1] + 
         256 * 256 * md5[2] + 
         256 * 256 * 256 * md5[3] + 
         256 * 256 * 256 * 256 * md5[4] + 
         256 * 256 * 256 * 256 * 256 * md5[5] +
         256 * 256 * 256 * 256 * 256 * 256 * md5[6] +
         256 * 256 * 256 * 256 * 256 * 256 * 256 * md5[7];

long b = md5[8] + 
         256 * md5[9] + 
         256 * 256 * md5[10] + 
         256 * 256 * 256 * md5[11] + 
         256 * 256 * 256 * 256 * md5[12] + 
         256 * 256 * 256 * 256 * 256 * md5[13] +
         256 * 256 * 256 * 256 * 256 * 256 * md5[14] +
         256 * 256 * 256 * 256 * 256 * 256 * 256 * md5[15];

long result = a ^ b;

Note I have made no attempt to deal with endianness. If you just care about a consistent hash value on a given platform, though, endianness should not matter.

Upvotes: 5

Adam Gent
Adam Gent

Reputation: 49095

Guava has some very nice Hashing capabilities:

Hashing.md5().hashString(s).asLong();

I believe the above is actually CityHash but regardless it will generate hash longs that you can use for whatever your hashing needs. (I tried @Eric J. Java code and it looks like CityHash 32).

Upvotes: 4

SecurityMatt
SecurityMatt

Reputation: 6743

Just to be clear, any subsection of a cryptographic digest no longer has many of the cryptographic properties of the digest, specifically these properties no longer hold:

  • Inversion resistance (finding an X that satisfies H(X))
  • Collision resistance (finding an X, Y such that H(X) = H(Y))
  • Random distribution over the range of possible outputs

Upvotes: 1

Related Questions