MD5 Digests in Java

Mar 22, 2007

File hashes have a multitude of uses and MD5 is, despite the fact that weaknesses have been found in the algorithm, still very useful and widely employed. Creating MD5 digests in Java is quite easy, but the documentation for MessageDigest is a little bit tricky. Here is a simple method that takes in a string of input and returns the hash of the string.

public static String md5(String input) {
    // Compute the MD5 digest of the passed String
    MessageDigest algorithm = null;
    try {
        algorithm = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
    algorithm.reset();
    byte[] hash = algorithm.digest(input.getBytes());

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Convert it to a String
StringBuffer ret = new StringBuffer();
for (int x = 0; x < hash.length; x++) {
    String hexString = Integer.toHexString(0xFF & hash[x]);
    if (hexString.length() == 1)
        hexString = "0" + hexString;

    ret.append(hexString);

    // Add the dashes
    if (x == 3 || x == 5 || x == 7 || x == 9)
        ret.append("-");
} //for

return ret.toString().toUpperCase();

} //md5