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
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[:])
}
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