How do I generate an MD5 digest for a String?
Author: Deron Eriksson
Description: This tutorial shows how to digest a String using MD5.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


Digesting a String with MD5W can be done with the MessageDigest class. We can get a MessageDigest object that can be used to do an MD5 digest via MessageDigest.getInstance("MD5"). We can pass the MessageDigest a byte array representation of the String that we'd like to digest. Calling the digest() method on the MessageDigest object will return a byte array representation of the MD5 digest. It's very common to convert this to its Hex representation.

The MD5Digest class demonstrates this. It takes a String as an argument and displays the original String and the MD5 digest converted to hex.

MD5Digest.java

package digest;

import java.security.MessageDigest;

public class MD5Digest {

	public static void main(String[] args) throws Exception {

		if (args.length != 1) {
			System.err.println("String to MD5 digest should be first and only parameter");
			return;
		}
		String original = args[0];
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(original.getBytes());
		byte[] digest = md.digest();
		StringBuffer sb = new StringBuffer();
		for (byte b : digest) {
			sb.append(String.format("%02x", b & 0xff));
		}

		System.out.println("original:" + original);
		System.out.println("digested(hex):" + sb.toString());
	}

}

If I execute the MD5Digest with an argument of "secret", I receive the following output in my console:

Console Output

original:secret
digested(hex):5ebe2294ecd0e0f08eab7690d2a6ee69

MD5 digests have many uses. One such use is to take passwords and run MD5 to generate a digest version of the password. This is a one-way hash, meaning that it's easy to generate a digest, but we can't go backwards and find out the original String based on the digest. Thus, passwords are often stored in MD5 digest form so that the original password can't be figured out from the MD5 value.