package main
import (
"crypto/md5"
"fmt"
)
func main() {
hash := md5.New()
b := []byte("test")
fmt.Printf("%x\n", hash.Sum(b))
hash.Write(b)
fmt.Printf("%x\n", hash.Sum(nil))
}
输出:
*md5.digest74657374d41d8cd98f00b204e9800998ecf8427e
098f6bcd4621d373cade4e832627b4f6
有人可以向我解释为什么/如何为两次打印得到不同的结果吗?
最佳答案
我正在建立已经很好的答案。我不确定 Sum
是否真的是您想要的函数。来自hash.Hash
文档:
// Sum appends the current hash to b and returns the resulting slice.
// It does not change the underlying hash state.
Sum(b []byte) []byte
这个函数有一个双重用例,你似乎以一种不幸的方式混合使用。用例是:
- 计算单次运行的哈希值
- 链接多个运行的输出
如果您只想计算某些东西的哈希值,请使用 md5.Sum(data)
或
digest := md5.New()
digest.Write(data)
hash := digest.Sum(nil)
根据上面文档的摘录,这段代码会将 data
的校验和附加到 nil
,从而得到 data
的校验和>.
如果你想链接几个散列 block ,hash.Sum
的第二个用例,你可以这样做:
hashed := make([]byte, 0)
for hasData {
digest.Write(data)
hashed = digest.Sum(hashed)
}
这会将每次迭代的散列附加到已计算的散列中。可能不是您想要的。
因此,现在您应该能够了解您的代码失败的原因。如果没有,请使用您的代码的注释版本 ( On play ):
hash := md5.New()
b := []byte("test")
fmt.Printf("%x\n", hash.Sum(b)) // gives 74657374<hash> (74657374 = "test")
fmt.Printf("%x\n", hash.Sum([]byte("AAA"))) // gives 414141<hash> (41 = 'A')
fmt.Printf("%x\n", hash.Sum(nil)) // gives <hash> as append(nil, hash) == hash
fmt.Printf("%x\n", hash.Sum(b)) // gives 74657374<hash> (74657374 = "test")
fmt.Printf("%x\n", hash.Sum([]byte("AAA"))) // gives 414141<hash> (41 = 'A')
hash.Write(b)
fmt.Printf("%x\n", hash.Sum(nil)) // gives a completely different hash since internal bytes changed due to Write()
关于hash - Golang md5 Sum() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24234322/