Skip to content

Instantly share code, notes, and snippets.

@ybiquitous
Last active December 26, 2015 20:29
Show Gist options
  • Save ybiquitous/7209497 to your computer and use it in GitHub Desktop.
Save ybiquitous/7209497 to your computer and use it in GitHub Desktop.
compiled by scala 2.10.3
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