Tuesday, 15 September 2009

Creating MD5 Digest in Groovy (or Java)

There is a quick-and-dirty way to generate MD5 digests in Groovy (or Java):

import java.security.MessageDigest

MessageDigest digest = MessageDigest.getInstance("MD5")

digest.update("encodeMe".bytes)

BigInteger big = new BigInteger(1,digest.digest())
String md5 = big.toString(16).padLeft(32,"0")

The above encodes the candidate string "encodeMe" to an MD5 digest.

If there are any Grails users reading, please note that you can simply use one of the built-in codecs:

String md5 = "encodeMe".encodeAsMD5()

Hopefully this will be if use to someone.

2 comments:

  1. Hi Duncan,

    I was just looking on with envy at the PHP version of this:

    $md5Hash = md5('encodeMe');

    when I came across your little post.

    I'll be using Grails for this little project anyway so everything's sweet.

    How's life treating you?

    Ed.

    ReplyDelete