Golang md5 Write vs Sum – 为什么输出结果不同?

huangapple go评论86阅读模式
英文:

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

huangapple
  • 本文由 发表于 2015年11月11日 06:58:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/33641282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定