MD5 Inconsistent between C# and golang

五迷三道 提交于 2019-12-11 11:22:57

问题


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:


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:


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



来源:https://stackoverflow.com/questions/22765185/md5-inconsistent-between-c-sharp-and-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!