I noticed on Rogers Cadenhead's blog that he was looking for, and found, how to get an MD5 hash for a password
in Java. Of course, like so many things it's "right there" in the Java libraries, but you have to know where to look!
MessageDigest, in this case. I have a trivially small class that I use to wrap the ugliness. Typically, you just
want to either check that a clear text password you've been given hashes to match a stored
value, or you want to hash that string to get a value you can store. So that's just two
very simple function APIs, and here's how I wrap them into a little class:
import java.security.*;
public class MD5Password
{
public static String getEncodedPassword(String clearTextPassword)
throws NoSuchAlgorithmException
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(clearTextPassword.getBytes());
return HexString.bufferToHex(md.digest());
}
public static boolean testPassword(String clearTextTestPassword,
String encodedActualPassword)
throws NoSuchAlgorithmException
{
String encodedTestPassword = MD5Password.getEncodedPassword(
clearTextTestPassword);
return (encodedTestPassword.equals(encodedActualPassword));
}
}
If you really wanted to assume that NoSuchAlgorithmException would never be thrown, you
could have these functions catch it and eat it, or catch it and rethrow as an unchecked
exception.
bufferToHex, also from my Java code
vault package, to convert the MD5 hash to a
hexadecimal string that is suitable for storing as text in a database or properties file
or whatever. I have subsequently posted the HexString class in this entry.
[340] Google: "java md5"
[230] Google: "java md5"
[177] http://forum.counter-strike.de/bb/thread.php?TID=37469&SID=H...
[150] Google: "java md5"
[147] Google: "java md5"
[134] Google: "java md5"
[121] Google: "java md5"
[101] Google: "java md5"
[97] Google: "java md5"
[96] Google: "Java MD5"