golang 的md5加密


先看實現代碼:

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)) // 輸出加密結果
}

代碼輸入效果:

image

說明:

Golang的加密庫都放在crypto目錄下,其中MD5庫在crypto/md5包中,該包主要提供了New和Sum函數。

這里直接對一串字符串計算MD5。其中通過md5.New()初始化一個MD5對象,其實它是一個hash.Hash對象。 函數原型為:

// New returns a new hash.Hash computing the MD5 checksum.

func New() hash.Hash {
    d := new(digest)
    d.Reset()
    return d
}
該對象實現了hash.Hash的Sum接口:計算出校驗和。其函數原型 為:

// 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 函數是對hash.Hash對象內部存儲的內容進行校驗和 計算然后將其追加到data的后面形成一個新的byte切片。因此通常的使用方法就是將data置為nil。

該方法返回一個Size大小的byte數組,對於MD5來說就是一個128bit的16字節byte數組。

 

參考資料:

Golang計算MD5
http://gotaly.blog.51cto.com/8861157/1403942


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM