英文:
Golang md5 Write vs Sum - why different outputs?
问题
有人能解释一下为什么这两种方法会产生不同的输出值吗?从md5文档中并不清楚。
import (
"crypto/md5"
"encoding/hex"
"fmt"
)
func GetMD5HashWithWrite(text string) string {
hasher := md5.New()
hasher.Write([]byte(text))
return hex.EncodeToString(hasher.Sum(nil))
}
func GetMD5HashWithSum(text string) string {
hasher := md5.New()
return hex.EncodeToString(hasher.Sum([]byte(text)))
}
参考示例:https://play.golang.org/p/Fy7KgfCvXc
英文:
Can anyone explain why these methods produce two different output values? It isn't clear from the md5 docs.
import (
"crypto/md5"
"encoding/hex"
"fmt"
)
func GetMD5HashWithWrite(text string) string {
hasher := md5.New()
hasher.Write([]byte(text))
return hex.EncodeToString(hasher.Sum(nil))
}
func GetMD5HashWithSum(text string) string {
hasher := md5.New()
return hex.EncodeToString(hasher.Sum([]byte(text)))
}
See example: https://play.golang.org/p/Fy7KgfCvXc
答案1
得分: 5
我混淆了hasher.Sum()
和md5.Sum()
。它们确实会产生相同的输出。
func GetMD5HashWithWrite(text string) []byte {
hasher := md5.New()
hasher.Write([]byte(text))
return hasher.Sum(nil)
}
func GetMD5HashWithSum(text string) [16]byte {
return md5.Sum([]byte(text))
}
Playground: https://play.golang.org/p/fpE5ztnh5U
英文:
I was mixing up hasher.Sum() with md5.Sum(). These do produce equivalent outputs.
func GetMD5HashWithWrite(text string) []byte {
hasher := md5.New()
hasher.Write([]byte(text))
return hasher.Sum(nil)
}
func GetMD5HashWithSum(text string) [16]byte {
return md5.Sum([]byte(text))
}
Playground: https://play.golang.org/p/fpE5ztnh5U
答案2
得分: 4
Sum函数的参数不是输入,而是一个用于存储输出的位置。在不需要分配内存的情况下,可以将Sum函数的结果直接存储到一个固定大小的字节数组中。你必须使用Write
方法向哈希函数提供输入。
或者直接使用md5.Sum()
函数:
func GetMD5HashWithSum(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}
英文:
The argument to the Sum function is not input, but a location to store the output. It is technically possible to Sum into a fixed byte array without needing to allocate. You must use Write
to provide input to the hash function.
Or use md5.Sum()
directly:
func GetMD5HashWithSum(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论