先看实现代码:数组
package main app
import (
"crypto/md5"
"encoding/hex"
"fmt"
) 函数
func main() {
h := md5.New()
h.Write([]byte("123456")) // 须要加密的字符串为 123456
cipherStr := h.Sum(nil)
fmt.Println(cipherStr)
fmt.Printf("%s\n", hex.EncodeToString(cipherStr)) // 输出加密结果
}加密
代码输入效果:code
说明:对象
Golang的加密库都放在crypto目录下,其中MD5库在crypto/md5包中,该包主要提供了New和Sum函数。 blog
这里直接对一串字符串计算MD5。其中经过md5.New()初始化一个MD5对象,其实它是一个hash.Hash对象。 函数原型为:
接口
// New returns a new hash.Hash computing the MD5 checksum.ip
func New() hash.Hash {
d := new(digest)
d.Reset()
return d
}
该对象实现了hash.Hash的Sum接口:计算出校验和。其函数原型 为:
// Hash is the common interface implemented by all hash functions.md5
type Hash interface {
// Sum appends the current hash to b and returns the resulting slice.
// It does not change the underlying hash state.
Sum(b []byte) []byte
…
}
Sum 函数是对hash.Hash对象内部存储的内容进行校验和 计算而后将其追加到data的后面造成一个新的byte切片。所以一般的使用方法就是将data置为nil。
该方法返回一个Size大小的byte数组,对于MD5来讲就是一个128bit的16字节byte数组。
参考资料:
Golang计算MD5
http://gotaly.blog.51cto.com/8861157/1403942