C#和golang之间的MD5计算结果不一致。

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

MD5 Inconsistent between C# and golang

问题

我正在尝试将一个算法从C#移植到Go。我需要的一步是对字节数组进行MD5哈希。但是我似乎无法在C#和Go的实现之间得到一致的哈希值。

在C#中,我可以这样做:new MD5CryptoServiceProvider().ComputeHash(new byte[] { 5 }))

我得到的结果是:[139 182 193 120 56 100 63 150 145 204 106 77 230 197 23 9]

在Go中,我使用:md5.New().Sum([]byte{5})

得到的结果是:[5 212 29 140 217 143 0 178 4 233 128 9 152 236 248 66 126]

我是不是做错了什么,还是这两个实现确实不同?我需要在Go中复制C#的行为。

如果你想检查我整个实现,我有一些可用的示例代码:goc#

英文:

I am attempting to port an algorithm from C# to go. One step I need is to take the md5 of an array of bytes. I cannot seem to get a consistent hash between C# and go implementations.

In C# I can do: new MD5CryptoServiceProvider().ComputeHash(new byte[] { 5 }))

and I get [139 182 193 120 56 100 63 150 145 204 106 77 230 197 23 9]

In go: md5.New().Sum([]byte{5})

yields: [5 212 29 140 217 143 0 178 4 233 128 9 152 236 248 66 126]

Am I doing something wrond, or are the implementations actually different. I need to be able to replicate the C# behavior on the go side.

I have some fiddles available for go and c# if you want to check my entire implementation.

答案1

得分: 4

你错误地使用了Sum函数的输入。Sum函数的输入参数用于存储输出结果,而不是作为hash的输入。可以直接使用md5.Sum(它的行为符合你的需求),或者按照示例中所示,将数据写入返回的Hash对象中:http://golang.org/pkg/crypto/md5/#example_New

英文:

You are misusing the input to the Sum function. The input parameter to sum is used to store the output, not as input to hash. Use md5.Sum directly (which behaves as you want) or write to the returned Hash object as demonstrated in the example: http://golang.org/pkg/crypto/md5/#example_New

答案2

得分: 2

这是要翻译的内容:

应该是这样的:

fmt.Println(md5.Sum([]byte{5}))

对于你在评论中提到的第二个问题:

hash.Hash 实现了 io.Writer 接口。所以你可以这样做:

h := md5.New()
h.Write([]byte{5})

可以查看 hash.Hash 接口

英文:

It should be

fmt.Println(md5.Sum([]byte{5}))

For your second question in your comment to Evan:

hash.Hash implements the io.Writer. So you can always do:

h := md5.New()
h.Write([]byte{5})

Have a look at the hash.Hash interface

huangapple
  • 本文由 发表于 2014年3月31日 23:06:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/22765185.html
匿名

发表评论

匿名网友

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

确定