使用Go进行UTF-8编码

huangapple go评论82阅读模式
英文:

Encoding UTF-8 with Go

问题

我正在尝试找到在Go语言中等效的以下C#代码:

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

我知道Go语言中有一个crypto/sha1包。我知道可以运行以下代码:

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

我不确定如何在哈希时获取正确的编码。我想知道是否可以得到一些帮助来转换这段代码。

英文:

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

答案1

得分: 4

根据文档:

一个字符串字面量,没有字节级转义,总是包含有效的UTF-8序列。

所以,如果字符串在Golang源代码中,你不需要将其编码为utf8。然而,如果字符串来自输入,utf8包是你的朋友。

英文:

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.

huangapple
  • 本文由 发表于 2016年11月2日 23:12:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/40383431.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定