-
-
Save stonegao/1044641 to your computer and use it in GitHub Desktop.
MD5 in scala
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 MD5 { | |
def hash(s: String) = { | |
val m = java.security.MessageDigest.getInstance("MD5") | |
val b = s.getBytes("UTF-8") | |
m.update(b, 0, b.length) | |
new java.math.BigInteger(1, m.digest()).toString(16) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This does not work for hashes with leading zeros, they are skipped. For example if you caluclate
hash("iwrupvqb346386")
you'll get45c5e2b3911eb937d9d8c574f09
instead of0000045c5e2b3911eb937d9d8c574f09
.As a remedy, you could do
new java.math.BigInteger(1, m.digest()).toString(16).reverse.padTo(32, "0").reverse.mkString
in the last line.On StackOverflow you find code like
m.digest().map("%02x".format(_)).mkString
which also works but is slower.