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
", h.Sum(nil))
fmt.Println()
h2 := md5.New()
fmt.Printf("%x
", 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
?
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)
.