本文介绍了Golang编码字符串UTF16小端和散列与MD5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名Go初学者,并且遇到问题。
我想用UTF16小端编码一个字符串,然后用MD5(十六进制)对它进行哈希处理。我找到了一段Python代码,它完全符合我的要求。但我无法将其转移到Google Go。

  md5 = hashlib.md5()
md5.update (challenge.encode('utf-16le'))
response = md5.hexdigest()



<挑战是一个包含字符串的变量。

解决方案
 func utf16leMd5(s string)[] byte { enc:= unicode.UTF16(unicode .LittleEndian,unicode.IgnoreBOM).NewEncoder() hasher:= md5.New()t:= transform.NewWriter(hasher,enc) t.Write([] byte(s )) return hasher.Sum(nil)}  


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:

func utf16leMd5(s string) []byte {
    enc := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder()
    hasher := md5.New()
    t := transform.NewWriter(hasher, enc)
    t.Write([]byte(s))
    return hasher.Sum(nil)
}

这篇关于Golang编码字符串UTF16小端和散列与MD5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!