Arena Red » 10 Oct 2003 » SHA and MD5 in Java
« Dynoweb | Now Playing in iTunes »
SHA and MD5 in Java

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:

Note: Since originally posting this, I have seen it mentioned that SHA is preferable to MD5 because it is harder to crack. If you want to use SHA instead of MD5 in this example, it's simply a matter of passing "SHA" in place of "MD5" in the call to MessageDigest.getInstance().
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.

You will notice that I am calling a function 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.