英文:
Difference between calling Write(val) then Sum(nil) compared to Sum(val) in hash?
问题
我正在研究使用Go的crypto包,并且我有一个简单的示例,我正在尝试弄清楚其中的问题。我知道可以使用io.WriteString
与哈希一起使用,但我想在将其与另一个库进行交互之前直接了解哈希对象。
package main
import (
"crypto/md5"
"fmt"
)
func main() {
val := []byte("Hello World")
h := md5.New()
h.Write(val)
fmt.Printf("%x\n", h.Sum(nil))
fmt.Println()
h2 := md5.New()
fmt.Printf("%x\n", h2.Sum(val))
}
运行上述代码会产生以下输出:
b10a8db164e0754105b7a99be72e3fe5
48656c6c6f20576f726c64d41d8cd98f00b204e9800998ecf8427e
在伪代码中,我期望以下操作:
h.Write(part1)
h.Write(part2)
result := h.Sum(part3)
会产生与以下操作相同的结果:
result := h.Sum(part1 + part2 + part3)
但在上面的简单示例中,我甚至无法使单个部分在两种情况下产生相同的输出。在GoLang pkg站点上列出的md5文档中,Write
方法神秘地消失了,这让我相信我可能使用错误了。我对只使用Sum
方法时得到比通常更长的哈希值感到特别困惑。
这里发生了什么?
编辑:我决定打印val
的十六进制,并注意到它与h2.Sum(val)
的输出的开头完全匹配。作为对比:
val: 48656c6c6f20576f726c64
h2: 48656c6c6f20576f726c64d41d8cd98f00b204e9800998ecf8427e
我肯定做错了什么。我应该完全避免使用Write
函数,而坚持使用io
吗?
英文:
I'm looking into using Go's crypto package and I have a simple example that I'm trying to figure out. I know I can use io.WriteString
with the hash, but I want to understand the hash object directly before interfacing it with another library.
package main
import (
"crypto/md5"
"fmt"
)
func main() {
val := []byte("Hello World")
h := md5.New()
h.Write(val)
fmt.Printf("%x\n", h.Sum(nil))
fmt.Println()
h2 := md5.New()
fmt.Printf("%x\n", h2.Sum(val))
}
Running it produces this output:
b10a8db164e0754105b7a99be72e3fe5
48656c6c6f20576f726c64d41d8cd98f00b204e9800998ecf8427e
In pseudo code, I would expect that:
h.Write(part1)
h.Write(part2)
result := h.Sum(part3)
Would produce the same results as
result := h.Sum(part1 + part2 + part3)
but in my simple example above I can't even get a single part to produce the same output in both scenarios. Write
is mysteriously missing from the GoLang pkg site listing for md5 which leads me to believe I might be using it wrong. I'm especially confused by the fact that if I only use the Sum
method, I get a longer than usual hash.
What's going on here?
EDIT: I decided to print the hex for val
and noticed that it exactly matched the beginning of h2.Sum(val)
's output. For comparison:
val: 48656c6c6f20576f726c64
h2: 48656c6c6f20576f726c64d41d8cd98f00b204e9800998ecf8427e
I'm definitely doing something wrong. Should I avoid the Write
function entirely and stick with io
?
答案1
得分: 3
Sum 方法将当前哈希值追加到参数中,并返回结果。参数不会被添加到哈希值中。
提供参数是为了让应用程序在获取哈希值时避免分配内存。许多应用程序不需要这种优化,可以直接调用 h.Sum(nil)
。
英文:
Sum appends the current hash to the argument and returns the result. The argument is not added to the hash.
The argument is provided so that applications can avoid an allocation when getting the hash. Many applications do not need this optimization and can simply call h.Sum(nil)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论