golang中MD5值計算問題

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

朋友發來一個一段用golang寫的計算MD5值的codes:

[cpp] view plaincopy在CODE上查看代碼片派生到My Code片
package main

import (

"crypto/md5"  "fmt"

)

func main() {

hash := md5.New()  b := []byte("test")  hash.Write(b)  fmt.Printf("%x %x\n", hash.Sum(nil), md5.Sum(b))

}

從上面的計算效果看,md5.Sum(b) = hash.Write(b) + hash.Sum(nil)。  至於其原因,從stackoverflow上看到如下評論:

[cpp] view plaincopy在CODE上查看代碼片派生到My Code片
The definition of Sum :

func (d0 *digest) Sum(in []byte) []byte {

// Make a copy of d0 so that caller can keep writing and summing.  d := *d0  hash := d.checkSum()  return append(in, hash[:]...)

}
When you call Sum(nil) it returns d.checkSum() directly as a byte slice, however if you call Sum([]byte) it appends d.checkSum() to your input.

從上面一段文字可以看出,Write函數會把MD5對象內部的字串clear掉,然後把其參數作為新的內部字串。而Sum函數則是先計算出內部字串的MD5值,而後把輸入參數附加到內部字串後面。   即可以為認為:hash.Write(b) + hash.Sum(nil) = hash.Write(nil) + hash.Sum(b) + hash.Sum(nil) = md5.Sum(b)。   如下代碼即可驗證上面的等式:

[cpp] view plaincopy在CODE上查看代碼片派生到My Code片
package main

import (

"crypto/md5"  "fmt"

)

func main() {

hash := md5.New()  b := []byte("test")  hash.Write(b)  fmt.Printf("%x %x\n", hash.Sum(nil), md5.Sum(b))  hash.Write(nil)  fmt.Printf("%x %x\n", hash.Sum(b), hash.Sum(nil))

}

此記。謝絕轉載。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.