golang 的md5加密

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

先看實現代碼:

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

代碼輸入效果:

說明:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.