Golang两种MD5加密方式
代码
package main import ( "crypto/md5" "encoding/hex" "fmt" ) func main() { // md5 加密的第一种方法 srcData := []byte("iyannik0215") cipherText1 := md5.Sum(srcData) fmt.Printf("md5 encrypto is \"iyannik0215\": %x \n", cipherText1) // md5 加密的第二种方法 hash := md5.New() hash.Write(srcData) cipherText2 := hash.Sum(nil) hexText := make([]byte, 32) hex.Encode(hexText, cipherText2) fmt.Println("md5 encrypto is \"iyannik0215\":", string(hexText)) }
# 执行结果 md5 encrypto is "iyannik0215": b6b20c73e6bc53bc691a6bb559cf9ca9 md5 encrypto is "iyannik0215": b6b20c73e6bc53bc691a6bb559cf9ca9
解释一下两种加密方式的不一样之处. 第一种加密方法: 第一种加密方法所调用的函数不同
//Source file src/crypto/md5/md5.go 19 // The size of an MD5 checksum in bytes. 20 const Size = 16 130 // Sum returns the MD5 checksum of the data. 131 func Sum(data []byte) [Size]byte { 132 var d digest 133 d.Reset() 134 d.Write(data) 135 return d.checkSum() 136 }func Sum(data []byte) [Size]byte 其 [Size]byte 是固定死的.所以说第一种方法返回的是 16长度的数组. 第二种加密方法:
//Source file src/crypto/md5/md5.go 50 // New returns a new hash.Hash computing the MD5 checksum. 51 func New() hash.Hash { 52 d := new(digest) 53 d.Reset() 54 return d 55 } // 这里只放了函数签名部分, 关于函数具体内容这里就不详细复制了. 51 func New() hash.Hash {} 61 func (d *digest) Write(p []byte) (nn int, err error) {} 90 func (d0 *digest) Sum(in []byte) []byte {}这里使用 func New() hash.Hash {} 函数进行生成对象. 使用 func (d *digest) Write(p []byte) (nn int, err error) {} 方法进行写入要加密的数据. 使用 func (d0 *digest) Sum(in []byte) []byte {} 方法进行数据的加密 看其返回值. []byte 可见使用第二种方式加密返回的是 []byte 类型的切片.