Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get hex-encoded md5 hash in Go

Tags:

hash

go

md5

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?

like image 257
jeffbr13 Avatar asked Nov 29 '22 10:11

jeffbr13


1 Answers

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.

like image 53
Jon Skeet Avatar answered Dec 05 '22 23:12

Jon Skeet