Posted By

narkisr on 09/11/08


Tagged

groovy md5


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

sfhynx
laurenceosx


Groovy File and URL MD5


 / Published in: Groovy
 

Generating MD5 HEX string from either URL or File instance in Groovy (more elegant than the Java version).

  1. import java.security.MessageDigest
  2.  
  3. def generateMD5(final file) {
  4. MessageDigest digest = MessageDigest.getInstance("MD5")
  5. file.withInputStream(){is->
  6. byte[] buffer = new byte[8192]
  7. int read = 0
  8. while( (read = is.read(buffer)) > 0) {
  9. digest.update(buffer, 0, read);
  10. }
  11. }
  12. byte[] md5sum = digest.digest()
  13. BigInteger bigInt = new BigInteger(1, md5sum)
  14. return bigInt.toString(16)
  15. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: ahornbeck on January 14, 2009

Thanks for the code sample! Found a small problem. To protect against leading zeros being dropped, change last line to.

return bigInt.toString(16).padLeft(32, '0')

Posted By: narkisr on January 14, 2009

Thanks for the comment, could you explain why 32 zero pad?

Posted By: daemonflower on January 26, 2009

This example would benefit from the line import java.security.MessageDigest to make it work on its own.

Posted By: narkisr on January 31, 2009

Iv added the import, thanx for the comment.

Posted By: seeekr on April 3, 2009

32 zero padding because the md5 digest string is expected to have 32 characters after left padding with zeros

You need to login to post a comment.