Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java calculate MD5 hash

Tags:

java

md5

md5sum

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

like image 622
AndyAndroid Avatar asked Oct 15 '11 05:10

AndyAndroid


People also ask

What is MD5 in Java?

MD5 is a widely used cryptographic hash function, which produces a hash of 128 bit. In this article, we will see different approaches to create MD5 hashes using various Java libraries.

What is MD5 hash code?

The MD5 (message-digest algorithm) hashing algorithm is a one-way cryptographic function that accepts a message of any length as input and returns as output a fixed-length digest value to be used for authenticating the original message.


1 Answers

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

DigestUtils.md5Hex(str);

this will give you 32 char string as a result

like image 135
tsds Avatar answered Oct 16 '22 08:10

tsds