Java calculate MD5 hash

AndyAndroid picture AndyAndroid · Oct 15, 2011 · Viewed 65.6k times · Source

In http://www.anyexample.com/programming/java/java_simple_class_to_compute_md5_hash.xml an example is given how to calculate an MD5 hash of String. This results in a 20 digit hex string. According to http://en.wikipedia.org/wiki/MD5 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(); 
    m.update(data,0,data.length);
    BigInteger i = new BigInteger(1,m.digest());
    return String.format("%1$032X", i);
}

Taken from http://snippets.dzone.com/posts/show/3686

Answer

tsds picture tsds · Oct 15, 2011

use org.apache.commons.codec.digest.DigestUtils instead:

DigestUtils.md5Hex(str);

this will give you 32 char string as a result