Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marcelmaatkamp/347630 to your computer and use it in GitHub Desktop.
Save marcelmaatkamp/347630 to your computer and use it in GitHub Desktop.
import java.security.MessageDigest
import java.io.*
/**
* Determine the MD5 or SHA1Sum of a file:
*
* println Checksum.getMD5Sum(new File("file.bin"))
* println Checksum.getSHA1Sum(new File("file.bin"))
*
* @author: Marcel Maatkamp (m.maatkamp avec gmail dot com)
*/
public class Checksum {
static getSha1sum(file) {
return getChecksum(file, "SHA1")
}
static getMD5sum(file) {
return getChecksum(file, "MD5")
}
static getChecksum(file, type) {
def digest = MessageDigest.getInstance(type)
def inputstream = file.newInputStream()
def buffer = new byte[16384]
def len
while((len=inputstream.read(buffer)) > 0) {
digest.update(buffer, 0, len)
}
def sha1sum = digest.digest()
def result = ""
for(byte b : sha1sum) {
result += toHex(b)
}
return result
}
private static hexChr(int b) {
return Integer.toHexString(b & 0xF)
}
private static toHex(int b) {
return hexChr((b & 0xF0) >> 4) + hexChr(b & 0x0F)
}
static def main(args) {
def sha1sum = Checksum.getSha1sum(new File(args[0]))
println "file($args[0]): sha1sum($sha1sum)"
}
}
@marcelmaatkamp
Copy link
Author

Note: the outcome of these checksums are the same as the ones called from unix, like

% sha1sum file.bin

@matteomazza91
Copy link

matteomazza91 commented Apr 13, 2018

I've fixed an unclosed resource and the examples in the comment.

You can merge it from here: https://gist.github.com/matteomazza91/fb2cfc4a4cd20f1a0d6cd6c511b48ca7

@ivarmu
Copy link

ivarmu commented Mar 10, 2021

Hi @marcelmaatkamp,

I've expanded the functionality to accept a String as input as well.

You can look the complete implementation from here: https://gist.github.com/ivarmu/5d412feea8dd2edd923b174435e7c643

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