AndyAndroid AndyAndroid - 3 years ago 211
Java Question

Java calculate MD5 hash

In an example is given how to calculate an MD5 hash of String. This results in a 20 digit hex string. According to I would expect a 32 digit hex string. I get the same result for example using dac2009 response in How can I generate an MD5 hash?.

Why do I get something which looks like a MD5 hash but isn't? I cannot imagine that all the strings I get I have to pad with 12 leading zeros.

Edit: one code example

public static String MungPass(String pass) throws NoSuchAlgorithmException {
MessageDigest m = MessageDigest.getInstance("MD5");
byte[] data = pass.getBytes();
BigInteger i = new BigInteger(1,m.digest());
return String.format("%1$032X", i);

Taken from

Answer Source

The code example you linked, is in my opinion bad code. It looks like the autor doesn't know how a computer works. However, there are much better examples.

The last example is the one you are searching for. Chech this Ideone:

Update 0: I've never seen before this way of formatting a String ("%1$032X"), so I don't know what it does. You need 128 bits to represent the MD5 hash and I would suggest to use the toString(16) method of BigInteger itself to create a String representation of the BigInteger instead of using that format.

String hashtext = bigInt.toString(16);

Update 1: I really don't know anymore what's wrong with the provided code. Try this:


And if that still produces still 20 digits, try to reinstall Java. I'm out of inspiration.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download