先看實(shí)現(xiàn)代碼:
package main
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)) // 輸出加密結(jié)果
}
代碼輸入效果:
說明:
Golang的加密庫都放在crypto目錄下,其中MD5庫在crypto/md5包中,該包主要提供了New和Sum函數(shù)。
這里直接對(duì)一串字符串計(jì)算MD5。其中通過md5.New()初始化一個(gè)MD5對(duì)象,其實(shí)它是一個(gè)hash.Hash對(duì)象。 函數(shù)原型為:
// New returns a new hash.Hash computing the MD5 checksum.
func New() hash.Hash {d := new(digest)
d.Reset()
return d
}該對(duì)象實(shí)現(xiàn)了hash.Hash的Sum接口:計(jì)算出校驗(yàn)和。其函數(shù)原型 為:
// Hash is the common interface implemented by all hash functions.
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 函數(shù)是對(duì)hash.Hash對(duì)象內(nèi)部存儲(chǔ)的內(nèi)容進(jìn)行校驗(yàn)和 計(jì)算然后將其追加到data的后面形成一個(gè)新的byte切片。因此通常的使用方法就是將data置為nil。
該方法返回一個(gè)Size大小的byte數(shù)組,對(duì)于MD5來說就是一個(gè)128bit的16字節(jié)byte數(shù)組。
參考資料:
Golang計(jì)算MD5
http://gotaly.blog.51cto.com/8861157/1403942
新聞熱點(diǎn)
疑難解答
圖片精選