Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate MD5 hash of a file while being as Groovy as possible.
def generateMD5( File file ) {
def digest = java.security.MessageDigest.getInstance("MD5")
file.eachByte( 4096 ) { buffer, length ->
digest.update( buffer, 0, length )
}
new BigInteger(1, digest.digest()).toString(16).padLeft(32, '0')
}
@chilloutman

This comment has been minimized.

Show comment
Hide comment
@chilloutman

chilloutman Aug 31, 2015

The hex encoding can also be done like this:

digest.digest().encodeHex() as String

The hex encoding can also be done like this:

digest.digest().encodeHex() as String
@Vampire

This comment has been minimized.

Show comment
Hide comment
@Vampire

Vampire Dec 11, 2015

I'd say

def generateMD5(File file) {
   file.withInputStream {
      new DigestInputStream(it, MessageDigest.getInstance('MD5')).withStream {
         it.eachByte {}
         it.messageDigest.digest().encodeHex() as String
      }
   }
}

Vampire commented Dec 11, 2015

I'd say

def generateMD5(File file) {
   file.withInputStream {
      new DigestInputStream(it, MessageDigest.getInstance('MD5')).withStream {
         it.eachByte {}
         it.messageDigest.digest().encodeHex() as String
      }
   }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment