Golang 的加密库都放在 crypto 目录下,其中 MD5 库在 crypto/md5 包中,该包主要提供了 New() 和 Sum() 函数。
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
)
func main() {
data := \[\]byte("Mdroid.cn")
md5Ctx := md5.New()
md5Ctx.Write(data)
cipherStr := md5Ctx.Sum(nil)
fmt.Println(cipherStr)
fmt.Printf("%x\\n", md5.Sum(data))
fmt.Printf("%x\\n", cipherStr)
fmt.Println(hex.EncodeToString(cipherStr))
}
结果:
[24 55 47 68 190 11 229 212 65 82 130 95 125 93 53 9]
18372f44be0be5d44152825f7d5d3509
18372f44be0be5d44152825f7d5d3509
18372f44be0be5d44152825f7d5d3509
分析:
md5.New() 初始化一个 MD5 对象,返回 hash.Hash 对象。函数原型为 func New() hash.Hash。其实该对象实现了 hash.Hash 的 Sum 接口。Sum() 计算出 MD5 校验和。Sum() 函数原型 func Sum(data []byte) [Size]byte。
通过翻阅源码可以看到他并不是对 data 进行校验计算,而是对 hash.Hash 对象内部存储的内容进行校验和计算然后将其追加到 data 的后面形成一个新的 byte 切片。因此通常的使用方法就是将 data 置为 nil。
该方法返回一个 Size 大小为 16 的 byte 数组,对于 MD5 来说就是一个 128bit 的 16 字节 byte 数组。
参考文档:
官方文档:https://golang.org/pkg/crypto/md5/#New