Created
June 7, 2011 23:39
MD5 in scala
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
| 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) | |
| } | |
| } |
Yes, @goofyz is right. This does not work for hashes with leading zeros, they are skipped. For example if you caluclate hash("iwrupvqb346386") you'll get 45c5e2b3911eb937d9d8c574f09 instead of 0000045c5e2b3911eb937d9d8c574f09 .
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If
0is the first character, this function will omit it and give an incorrect result.