golang中MD5值计算问题
alexstocks · · 2848 次点击 · · 开始浏览朋友发来一个一段用golang写的计算MD5值的codes:
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
package main
import (
"crypto/md5" "fmt"
)
func main() {
hash := md5.New()
b := []byte("test")
hash.Write(b)
fmt.Printf("%x %x\n", hash.Sum(nil), md5.Sum(b))
}
从上面的计算效果看,md5.Sum(b) = hash.Write(b) + hash.Sum(nil)。 至于其原因,从stackoverflow上看到如下评论:
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
The definition of Sum :
func (d0 *digest) Sum(in []byte) []byte {
// Make a copy of d0 so that caller can keep writing and summing. d := *d0 hash := d.checkSum() return append(in, hash[:]...)
}
When you call Sum(nil) it returns d.checkSum() directly as a byte slice, however if you call Sum([]byte) it appends d.checkSum() to your input.
从上面一段文字可以看出,Write函数会把MD5对象内部的字符串clear掉,然后把其参数作为新的内部字符串。而Sum函数则是先计算出内部字符串的MD5值,而后把输入参数附加到内部字符串后面。 即可以为认为:hash.Write(b) + hash.Sum(nil) = hash.Write(nil) + hash.Sum(b) + hash.Sum(nil) = md5.Sum(b)。 如下代码即可验证上面的等式:
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
package main
import (
"crypto/md5" "fmt"
)
func main() {
hash := md5.New()
b := []byte("test")
hash.Write(b)
fmt.Printf("%x %x\n", hash.Sum(nil), md5.Sum(b))
hash.Write(nil)
fmt.Printf("%x %x\n", hash.Sum(b), hash.Sum(nil))
}
此记。谢绝转载。
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
朋友发来一个一段用golang写的计算MD5值的codes:
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
package main
import (
"crypto/md5" "fmt"
)
func main() {
hash := md5.New()
b := []byte("test")
hash.Write(b)
fmt.Printf("%x %x\n", hash.Sum(nil), md5.Sum(b))
}
从上面的计算效果看,md5.Sum(b) = hash.Write(b) + hash.Sum(nil)。 至于其原因,从stackoverflow上看到如下评论:
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
The definition of Sum :
func (d0 *digest) Sum(in []byte) []byte {
// Make a copy of d0 so that caller can keep writing and summing. d := *d0 hash := d.checkSum() return append(in, hash[:]...)
}
When you call Sum(nil) it returns d.checkSum() directly as a byte slice, however if you call Sum([]byte) it appends d.checkSum() to your input.
从上面一段文字可以看出,Write函数会把MD5对象内部的字符串clear掉,然后把其参数作为新的内部字符串。而Sum函数则是先计算出内部字符串的MD5值,而后把输入参数附加到内部字符串后面。 即可以为认为:hash.Write(b) + hash.Sum(nil) = hash.Write(nil) + hash.Sum(b) + hash.Sum(nil) = md5.Sum(b)。 如下代码即可验证上面的等式:
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
package main
import (
"crypto/md5" "fmt"
)
func main() {
hash := md5.New()
b := []byte("test")
hash.Write(b)
fmt.Printf("%x %x\n", hash.Sum(nil), md5.Sum(b))
hash.Write(nil)
fmt.Printf("%x %x\n", hash.Sum(b), hash.Sum(nil))
}
此记。谢绝转载。