The Bad Programmer

Java MD5 Hash



How do you get a MD5 hash in Java? Well I am glad you asked! I have somehow managed to create some Java code that does exactly that. Here it is for your cut and pasting pleasure! I have seen some code out there that won’t work correctly if the hashed value starts with zeros (generally because they are using a BigInteger). This version will properly display leading zeroes.

public class Hasher {
    /**
     * Gets the md5 hash of the passed in bytes
     *
     * @param bytes The bytes to determine the md5 hash of
     * @return a String containing the md5 hash string
     */
    public String getMd5Hash(byte[] bytes) {
        Formatter fm = new Formatter();
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("MD5");
            digest.update(bytes);
            bytes = digest.digest();
            for (byte b : bytes) {
                fm.format("%02x", b);
            }
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Exception: " + e);
        }
        return fm.out().toString();
    }
    public static void main(String[] args) {
        Hasher hasher = new Hasher();
        String hash = hasher.getMd5Hash("what is the md5 hash of this?".getBytes());
        System.out.println("hash = " + hash);
    }
}

If you run this code the output will be:

hash = 49a9884c3121800a49d64a5389691d1a

Comparing this to obtaining the md5 hash from the command-line shows that I actually managed to put together some code that works. This is on Mac OS, although every unix flavor probably has a md5 command-line utility:

bad:~:7> md5 -s "what is the md5 hash of this?"
MD5 ("what is the md5 hash of this?") = 49a9884c3121800a49d64a5389691d1a

This code actually demonstrates another issue I sometimes have with Java. That being that the JDK itself doesn’t always get the checked vs. unchecked exception nonsense correct. Being a bad programmer might mean that I don’t have a clue what I am talking about, but NoSuchAlgorithmException should not be a checked exception! I can’t reasonably be expected to recover from that exception so it should be unchecked. If a unknown algorithm is being passed to getInstance() then that is a programming error, so again, that should be an unchecked exception.