39

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

7
  • 6
    Why cant you use java.security.MessageDigest? Just wrap it in a public static function to make less clutter in Scala? Commented May 13, 2011 at 13:43
  • 2
    What is the reason you don't want to use MessageDigest? Commented May 13, 2011 at 13:45
  • 1
    net.liftweb.util.Helpers.md5(str) – of course it only makes sense when you’re already using liftweb somewhere… Commented May 13, 2011 at 14:03
  • @Debilski: that function just calls MessageDigest again Commented May 13, 2011 at 14:10
  • 2
    @Goran Jovic Of course it does. Why should it implement that function again? Commented May 13, 2011 at 14:16

1 Answer 1

80

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]

Sign up to request clarification or add additional context in comments.

12 Comments

@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))
@Debilksi I don't think the first map(0xFF & _) is necessary, simply .map("%02X".format(_)).mkString
Here's some gists to create md5 strings in all languages: gist.github.com/amscotti/2467512
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(""){_ + _}
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 } }
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.