Skip to content

Instantly share code, notes, and snippets.

@stonegao
Forked from leifwickland/gist:1013460
Created June 24, 2011 11:59
Show Gist options
  • Save stonegao/1044641 to your computer and use it in GitHub Desktop.
Save stonegao/1044641 to your computer and use it in GitHub Desktop.
MD5 in scala
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)
}
}
@bxt
Copy link

bxt commented Nov 12, 2017

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