朋友發來一個一段用golang寫的計算MD5值的codes:golang
[cpp] view plaincopy在CODE上查看代碼片派生到個人代碼片 package mainapp
import (
"crypto/md5"
"fmt"
)函數
func main() {code
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上查看代碼片派生到個人代碼片 The definition of Sum :md5
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上查看代碼片派生到個人代碼片 package maininput
import (
"crypto/md5"
"fmt"
)hash
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))
}it
此記。謝絕轉載。