Programmer's Cookbook

Recipes for the practical programmer

Friday, June 13, 2008

 

Creating an MD5 dogest of a Java String

You can generate MD5's using Java's own MessageDigest class. This class will generate the MD5 value as a set of bytes. Typically this isn't what you want. In most cases you will want to create a hex string from the bytes, so it looks something like this, "007868b95b02a639bed49adea41f266e". You can rectify this by downloading the commons-codec library, and running the bytes through the Hex class.

The code below does just this.


import java.security.MessageDigest;
import import org.apache.commons.codec.binary.Hex;

...

String myString = "The string to create a digest from";
String md5String = null;

try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(myString.getBytes());
md5String = new String(Hex.encodeHex(digest.digest()));
}
catch (Exception e) {}

Comments:
Nice post, there are some rather lengthy ones out there that try to do it all manually. However, since you are already using commons-codec, you can reduce this to one line:

return DigestUtils.md5Hex(s);
 
Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?