A Scala method to create an MD5 hash of a string

If you happen to need Scala method to perform an MD5 hash on a string, here you go:

def md5HashString(s: String): String = {
    import java.security.MessageDigest
    import java.math.BigInteger
    val md = MessageDigest.getInstance("MD5")
    val digest = md.digest(s.getBytes)
    val bigInt = new BigInteger(1,digest)
    val hashedString = bigInt.toString(16)

I’m currently writing a Play Framework (Scala) web application that sits on top of an old Drupal 6 database, and that version of Drupal stored the user passwords in the database using MD5 without any sort of salt, and I can confirm that this Scala method converts a given string to the same MD5 string that Drupal 6 put into that database.

Please note that this Scala code is a pretty direct translation of the Java code at this SO URL; I didn’t look into trying to translate anything into a more Scala-like approach.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.