doumao6212 2015-01-28 16:48
浏览 728
已采纳

哈希中调用Write(val)然后调用Sum(nil)与Sum(val)之间的区别?

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?

  • 写回答

1条回答 默认 最新

  • douzhu1188 2015-01-28 17:10
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计