MD5 Digests in Java

| 1 Comment | No TrackBacks

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());

// 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

No TrackBacks

TrackBack URL: http://dinomite.net/cgi-bin/mt/mt-tb.cgi/107

1 Comment

Thanks for the help. I was having trouble figuring how to clear the dashes in the byte array. I didnt think of ANDing it with 0xFF until I saw the code.

Saved me a few hours of debugging.

Leave a comment

Pages

About this Entry

This page contains a single entry by Drew Stephens published on March 22, 2007 1:59 PM.

Perl Just Like sed was the previous entry in this blog.

Windows Server 2003 Updates is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.