Scala MD5

参考:
* MD5 in Scala
* MD5 hashing
* Scala-MD5 Hash function for Scala console
* Scala - converting array to map
* Scala,importing class

1.MD5

//way 1
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)
    }
}
//way 2 md5.scala
import java.security.MessageDigest
val digest = MessageDigest.getInstance("MD5")
//Quick MD5 of text
val text = "MD5 this text!"
val md5hash1 = digest.digest(text.getBytes).map("%02x".format(_)).mkString

//MD5 of text with updates
digest.update("MD5 ".getBytes())
digest.update("this ".getBytes())
digest.update("text!".getBytes())
val md5hash2 = digest.digest().map(0xFF & _).map("%02x".format(_)).mkString
//output
println(md5hash1 + " should be the same as "+md5hash2)
// way 3
digest.digest(text.getBytes).map("%02x".format(_)).mkString
// way 4
def md5Hash(text:String):String = 
java.security.MessageDigest.getInstance("MD5").digest(text.getBytes()).map(0xFF & _).map{"%02x".format(_)}.foldLeft(""){_+_}

你可能感兴趣的:(scala)