Nick Rucci
Nick Rucci

Reputation: 1058

Encoding UTF-8 with Go

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

Upvotes: 1

Views: 4784

Answers (1)

Tinwor
Tinwor

Reputation: 7983

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.

Upvotes: 3

Related Questions