How to get hex-encoded md5 hash in Go

2019-07-02 21:15发布

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?

标签: hash md5 go
2条回答
老娘就宠你
2楼-- · 2019-07-02 21:49

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.

查看更多
三岁会撩人
3楼-- · 2019-07-02 21:53

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

查看更多
登录 后发表回答