Forked from marcelmaatkamp/Checksum.groovy - Determine the MD5 or SHA1Sum of a file
Last active
March 10, 2021 13:17
-
-
Save ivarmu/5d412feea8dd2edd923b174435e7c643 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.* | |
/** | |
* Inspired in the original https://gist.github.com/marcelmaatkamp/347630/0d2b8a3b4e78c0be1cabf5a70c4784276d628d41 | |
* Determine the MD5 or SHA1Sum of a file: | |
* | |
* println Checksum.getMD5Sum(new File("file.bin")) | |
* println Checksum.getSHA1Sum(new File("file.bin")) | |
* println Checksum.getMD5Sum("Hello world") | |
* println Checksum.getSHA1Sum("Hello world") | |
* | |
*/ | |
public class Checksum { | |
static getSha1sum(File file) { | |
return getChecksum(file, "SHA1") | |
} | |
static getSha1sum(String string) { | |
return getChecksum(string, "SHA1") | |
} | |
static getMD5sum(File file) { | |
return getChecksum(file, "MD5") | |
} | |
static getMD5sum(String string) { | |
return getChecksum(string, "MD5") | |
} | |
static getChecksum(File 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 | |
} | |
static getChecksum(String string, type) { | |
def digest = MessageDigest.getInstance(type) | |
def inputstream = new ByteArrayInputStream( string.getBytes( 'UTF-8' ) ) | |
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)" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment