Skip to content

Instantly share code, notes, and snippets.

@mcquinne
Forked from ikarius/md5.groovy
Created May 10, 2012 20:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcquinne/2655782 to your computer and use it in GitHub Desktop.
Save mcquinne/2655782 to your computer and use it in GitHub Desktop.
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
Copy link

The hex encoding can also be done like this:

digest.digest().encodeHex() as String

@Vampire
Copy link

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

@AbuCarlo
Copy link

AbuCarlo commented Aug 14, 2018

import java.nio.file.Path

Path.metaClass.getMd5 << { ->
   def digest = java.security.MessageDigest.getInstance("MD5")
   delegate.withInputStream { stream ->
       stream.eachByte 4096, { buffer, length ->
       digest.update( buffer, 0, length )
     }
  }
  digest.digest().encodeHex() as String
}

File.metaClass.getMd5 << { -> delegate.toPath().md5 }

def f = new File('/Users/pwg947/incoming_transactions.tsv')

f.md5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment