Adam Short
Adam Short

Reputation: 498

MD5 Hashing returning different output than expected

I'm connecting lamp using JDBC and I have the word LondonWeight as a password hashed using MD5 on a MySQL database. I then need to check an inputted password against the collection, i.e LondonWeight to check to see if they match. However the hashing in my Java code returns a different output for the word.

MySQL hash: 1274d1c52d7a5a9125bd64f1f9a26dce

Java hash: 132310771724320562704545645352563257040366

Here's my hash code:

private String hashPass(String pass) throws NoSuchAlgorithmException {
    MessageDigest mdEnc = MessageDigest.getInstance("MD5"); 
    mdEnc.update(pass.getBytes(), 0, pass.length());
    String md5 = new BigInteger(1, mdEnc.digest()).toString(8); // Encrypted 
    return md5;
}

It definitely hashes the String entered in the text box as I have it printed to the terminal so I can check. Any idea why it gives a different output? I understand there a different ways to hash the bytes or something?

Upvotes: 0

Views: 807

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503130

You're currently converting the hash into octal in Java, whereas the MySQL version is in hex.

That's the first problem, but also:

  • Your MySQL hash appears to be 33 characters, which is too much data for an MD5 hash in hex. There's something odd going on there.
  • I wouldn't use BigInteger to convert a byte array into hex anyway; that's not what it's there for. Use Apache Commons Codec or something designed for hex conversion. For example, that way you'll get appropriate leading zeroes which BigInteger may suppress
  • Your current code assumes a single byte per character
  • Your current code assumes that the default character encoding is appropriate; I would suggest always specifying an encoding in String.getBytes
  • Using MD5 for password hashing is weak; update to a more appropriate hash if you possibly can

Upvotes: 7

Related Questions