37

Possible Duplicate:
Generate MD5 hash in Java

Hi,

I want to compute the MD5 hash of a string in my scala code. Is there any scala or java library i can use to do this quickly, apart from the regular java.security.MessageDigest way ?

Please Help Thanks

Community
  • 1
  • 1
james
  • 507
  • 1
  • 5
  • 5

1 Answers1

77

You may be reinventing a very tiny wheel here, but just write a function to do what you want: take a string, use MessageDigest, and return whatever (hex string, byte array) you need.

import java.security.MessageDigest

def md5(s: String) = {
    MessageDigest.getInstance("MD5").digest(s.getBytes)
}

md5("Hello")

P.S. I don't write Scala, but this works and it's left as an exercise to the reader to turn it into anything other than an Array[Byte]

Debilski
  • 66,976
  • 12
  • 110
  • 133
John Cromartie
  • 4,184
  • 27
  • 32
  • @John: `.getInstance("SHA")`? – Nick May 13 '11 at 14:00
  • 3
    @Debilski the bytes in the digest are nonsense as characters themselves when used to create a string. Someone usually wants to format them as hex digits... I know in Clojure this would be like `(apply str (map #(format "%02x" %) bytes))` – John Cromartie May 13 '11 at 14:09
  • 1
    @John Cromartie You’re correct. I remember I had to do that once… Was something like `map(0xFF & _).map { "%02x".format(_) }.mkString` – Debilski May 13 '11 at 14:12
  • Btw. You need a `=` after the argument list. – Debilski May 13 '11 at 14:14
  • 26
    @Debilksi I don't think the first `map(0xFF & _)` is necessary, simply `.map("%02X".format(_)).mkString` – Alois Cochard May 13 '11 at 14:30
  • Is `.map("%02X".format(_)).mkString` hex md5 format reversible? There is a way to do this `BigInt(hexMd5,16).toByteArray` but I'm not sure if it is 100% – lisak Apr 21 '15 at 12:57
  • 3
    Here's some gists to create md5 strings in all languages: https://gist.github.com/amscotti/2467512 – Guy Sopher Jun 16 '15 at 07:44
  • 12
    I came here looking for this: `def md5Hash(text: String) : String = java.security.MessageDigest.getInstance("MD5").digest(text.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft(""){_ + _}` – Priyank Desai Jan 29 '16 at 00:02
  • I used the same instance, but did messageDigest.reset() before messageDigest.update(str.getBytes()) – beloblotskiy Dec 22 '16 at 22:01
  • 2
    Here is complete extension method, can be used as "testString".hash `import java.security.MessageDigest object StringExtensions { implicit class RichString(val str: String) extends AnyVal { def hash: String = MessageDigest.getInstance("MD5").digest(str.getBytes).map("%02X".format(_)).mkString + "-" + str } }` – AjitChahal Jan 31 '17 at 16:25
  • @AjitChahal why do you need to extend `AnyVal`? – DanGordon Aug 25 '17 at 13:51
  • 1
    I found it cleaner to go to hex via a BigInt: `def hex(bytes: Array[Byte]): String = BigInt(1, bytes).toString(16).toUpperCase` – Kevin Wright Jan 27 '19 at 09:57