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

chilloutman commented Aug 31, 2015

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

This comment has been minimized.

Show comment
Hide comment
@AbuCarlo

AbuCarlo 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

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