How to get hex-encoded md5 hash in Go

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 20:23:29

问题


I'm trying to get the md5 hash of a file in Go, like thus:

running_hash := md5.New(); // type hash.Hash
running_hash.Write(data);  // data is []byte
sum := running_hash.Sum(); // []uint8 according to the compiler

But when I try to get the string of the hash's 'sum' (http://golang.org/pkg/hash/), via

sumstring := string(sum);  // returns 'Ӿ��]앿��N��' or similar

when the hash is supposed to be d3be9e835dec95bfbef34ebe1fbf03da. I get the same sort of nonsense, only with different characters, when I try to convert on a byte-by-byte basis.

How am I meant to get the hash's string?


回答1:


Basically, you've got the binary data but it looks like you're expecting hex. Have a look at the hex package for conversion routines, especially EncodeToString. I'm not a Go programmer, but I think if you just pass sum into hex.EncodeToString, you'll get the answer you expected.




回答2:


alternately, you can get the hex representation of a string or byte slice easily using fmt.Sprintf("%x", sum)



来源:https://stackoverflow.com/questions/7988543/how-to-get-hex-encoded-md5-hash-in-go

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