Created
March 29, 2010 09:07
-
-
Save marcelmaatkamp/347630 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)" | |
} | |
} |
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
I've fixed an unclosed resource and the examples in the comment.
You can merge it from here: https://gist.github.com/matteomazza91/fb2cfc4a4cd20f1a0d6cd6c511b48ca7