Last active
December 26, 2015 20:29
-
-
Save ybiquitous/7209497 to your computer and use it in GitHub Desktop.
compiled by scala 2.10.3
This file contains 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
object md5sum { | |
def main(args: Array[String]) { | |
if (args.isEmpty) { | |
println("Usage: scala md5sum FILE1, FILE2, ...") | |
return | |
} | |
args.foreach{ file => | |
// calculate hash | |
val hash = calcHash(file, "MD5") | |
// print as hex string | |
println(bytesToHexString(hash) + " " + file) | |
} | |
} | |
def calcHash(file: String, algo: String) = { | |
val md = java.security.MessageDigest.getInstance(algo) | |
val stream = try { | |
new java.security.DigestInputStream(new java.io.FileInputStream(file), md) | |
} catch { | |
case e: java.io.FileNotFoundException => { println(e.getMessage); sys.exit(-1) } | |
} | |
var bytes = 0 | |
while (bytes != -1) bytes = stream.read() | |
stream.close | |
md.digest | |
} | |
def bytesToHexString(bytes: Array[Byte]) = { | |
val sb = new java.lang.StringBuilder(bytes.size) | |
val fmt = new java.util.Formatter(sb, java.util.Locale.ENGLISH) | |
bytes.foreach{ b => fmt.format("%02x", byte2Byte(b)) } | |
sb.toString | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment