Saturday, June 08, 2013

How to calculate MD5 as zero-padded hex string in Groovy?

import java.security.MessageDigest
 
def digest = MessageDigest.getInstance("MD5")
 
def bytes = data.getBytes()
def md5 = digest.digest(bytes)
 
// Convert to hex, left-padded with 0 to 32 chars
def hex = new BigInteger(1, md5).toString(16).padLeft(32, "0")

Gist: https://gist.github.com/sjtai/5733901