dongquepao8653 2014-06-15 21:33
浏览 993
已采纳

Golang md5 Sum()函数

package main

import (
    "crypto/md5"
    "fmt"
)

func main() {
    hash := md5.New()
    b := []byte("test")
    fmt.Printf("%x
", hash.Sum(b))
    hash.Write(b)
    fmt.Printf("%x
", hash.Sum(nil))
}

Output:

*md5.digest74657374d41d8cd98f00b204e9800998ecf8427e
098f6bcd4621d373cade4e832627b4f6

Could someone please explain to me why/how do I get different result for the two print ?

  • 写回答

4条回答 默认 最新

  • donglun7151 2014-06-15 23:57
    关注

    I'm building up on the already good answers. I'm not sure if Sum is actually the function you want. From the hash.Hash documentation:

    // Sum appends the current hash to b and returns the resulting slice.
    // It does not change the underlying hash state.
    Sum(b []byte) []byte
    

    This function has a dual use-case, which you seem to mix in an unfortunate way. The use-cases are:

    1. Computing the hash of a single run
    2. Chaining the output of several runs

    In case you simply want to compute the hash of something, either use md5.Sum(data) or

    digest := md5.New()
    digest.Write(data)
    hash := digest.Sum(nil)
    

    This code will, according to the excerpt of the documentation above, append the checksum of data to nil, resulting in the checksum of data.

    If you want to chain several blocks of hashes, the second use-case of hash.Sum, you can do it like this:

    hashed := make([]byte, 0)
    for hasData {
        digest.Write(data)
        hashed = digest.Sum(hashed)
    }
    

    This will append each iteration's hash to the already computed hashes. Probably not what you want.

    So, now you should be able to see why your code is failing. If not, take this commented version of your code (On play):

    hash := md5.New()
    b := []byte("test")
    fmt.Printf("%x
    ", hash.Sum(b))             // gives 74657374<hash> (74657374 = "test")
    fmt.Printf("%x
    ", hash.Sum([]byte("AAA"))) // gives 414141<hash> (41 = 'A')
    fmt.Printf("%x
    ", hash.Sum(nil))           // gives <hash> as append(nil, hash) == hash
    
    fmt.Printf("%x
    ", hash.Sum(b))             // gives 74657374<hash> (74657374 = "test")
    fmt.Printf("%x
    ", hash.Sum([]byte("AAA"))) // gives 414141<hash> (41 = 'A')
    hash.Write(b)
    fmt.Printf("%x
    ", hash.Sum(nil))           // gives a completely different hash since internal bytes changed due to Write()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog