java.security.MessageDigest#digest
返回一个字节数组。
scala> import java.security.MessageDigest
scala> import java.math.BigInteger
scala> MessageDigest.getInstance("SHA-256").digest("some string".getBytes("UTF-8"))
res1: Array[Byte] = Array(97, -48, 52, 71, 49, 2, -41, -38, -61, 5, -112, 39, 112, 71, 31, -43, 15, 76, 91, 38, -10, -125, 26, 86, -35, -112, -75, 24, 75, 60, 48, -4)
使用String.format
创建十六进制数:
scala> val hash = String.format("%032x", new BigInteger(1, MessageDigest.getInstance("SHA-256").digest("some string".getBytes("UTF-8"))))
hash: String = 61d034473102d7dac305902770471fd50f4c5b26f6831a56dd90b5184b3c30fc
您可以使用命令行工具在Linux和Unix中验证哈希值。
$ echo -n "some string" | openssl dgst -sha256
61d034473102d7dac305902770471fd50f4c5b26f6831a56dd90b5184b3c30fc
注意:
如果Java返回的哈希长度小于64个字符,您可以使用0
进行左填充。(例如:39
)
def hash64(data: String) = {
val hash = String.format(
"%032x",
new BigInteger(1, MessageDigest.getInstance("SHA-256").digest(data.getBytes("UTF-8")))
)
val hash64 = hash.reverse.padTo(64, "0").reverse.mkString
hash64
}