对于Ruby中的BigNum,似乎pack方法将只打包最后32位(4字节)。因此,对于这个散列f1af822290cfcac4ce476a69
1a50305c
[Digest::MD5.hexdigest("Data to pack").to_i(16)]
.pack("N")
.each_byte.map { |b| sprintf("0x%02X ",b) }.join
显示
0x1A 0x50 0x30 0x5C
,是最后4个字节
具有相同行为的Scala实现:
import java.security.MessageDigest
import java.nio._
import java.io._
import scala.annotation.tailrec
object MD5 {
def main(args: Array[String]) = {
val str = "Data to pack"
val md5Bytes = calcMd5(str)
val md5Str = md5Bytes.map(b => "%02x".format(b)).mkString
println(s"$str => $md5Str")
// Get last 4-bytes
val byteArr = md5Bytes.slice(12, 16)
// Print it
print(s"Last 4-bytes => ")
byteArr.foreach { r =>
print("%02X ".format(r))
}
println
}
def calcMd5(str: String): Array[Byte] = {
MessageDigest.getInstance("MD5")
.digest(str.getBytes)
}
}