I am a Go beginner and stuck with a problem. I want to encode a string with UTF16 little endian and then hash it with MD5 (hexadecimal). I have found a piece of Python code, which does exactly what I want. But I am not able to transfer it to Google Go.
md5 = hashlib.md5()
md5.update(challenge.encode('utf-16le'))
response = md5.hexdigest()
The challenge is a variable containing a string.
You can do it with less work (or at least more understandability, IMO) by using golang.org/x/text/encoding and golang.org/x/text/transform to create a Writer chain that will do the encoding and hashing without so much manual byte slice handling. The equivalent function:
You can use the
unicode/utf16
package for UTF-16 encoding.utf16.Encode()
returns the UTF-16 encoding of the Unicode code point sequence (slice of runes:[]rune
). You can simply convert astring
to a slice of runes, e.g.[]rune("some string")
, and you can easily produce the byte sequence of the little-endian encoding by ranging over theuint16
codes and sending/appending first the low byte then the high byte to the output (this is what Little Endian means).For Little Endian encoding, alternatively you can use the
encoding/binary
package: it has an exportedLittleEndian
variable and it has aPutUint16()
method.As for the MD5 checksum, the
crypto/md5
package has what you want,md5.Sum()
simply returns the MD5 checksum of the byte slice passed to it.Here's a little function that captures what you want to do:
Using it:
Output:
Try it on the Go Playground.
The variant that uses
encoding/binary
would look like this:(Although this is slower as it creates lots of new slice headers.)
So, for reference, I used this complete python program:
It prints
8f4a54c6ac7b88936e990256cc9d335b
Here is the Go equivalent: https://play.golang.org/p/Nbzz1dCSGI