使用Go编码UTF-8

使用Go编码UTF-8

问题描述:

I am trying to find the equivalent of the following C# code in Go.

pwd = "abc123";
encoding = Encoding.UTF8;
SHA1 sha1 = SHA1.Create();
byte[] hash = sha1.ComputeHash(encoding.GetBytes(text));

I know that there is a crypto/sha1 package within Go. I know I can run:

pwd := "abc123"
hasher := sha1.New() // SHA1.Create();
hasher.Write([]byte(pwd)) // sha1.ComputeHash but without encoding in UTF8 ?

I am not sure how I can get the correct encoding when hashing. I was wondering if I could get some help converting this

我试图在Go中找到以下C#代码的等效项。 p> pwd =“ abc123”; encoding = Encoding.UTF8; SHA1 sha1 = SHA1.Create(); byte []哈希= sha1.ComputeHash(encoding.GetBytes(text)); 代码> pre>

我知道有一个 crypto / sha1 中的包。 我知道我可以运行: p>

  pwd:=“ abc123” 
hasher:= sha1.New()// SHA1.Create(); 
hasher.Write([]  byte(pwd))// sha1.ComputeHash但没有UTF8编码吗?
  code>  pre> 
 
 

我不确定哈希时如何获得正确的编码。 我想知道是否可以得到一些转换 p> div>的帮助

According to the documentation:

A string literal, absent byte-level escapes, always holds valid UTF-8 sequences.

So you don't need to encode into utf8 the string if is inside the Golang source code. However, if the string comes from an input, the utf8 package is your friend.