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长度的数组**(无法转string类型,需使用第二种加密方法)** 第二种加密方法:
By admin
read more