8
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

golangで文字列からsha256でハッシュ化する方法

Posted at

ハッシュ化

特定の文字列の不可逆変換をする処理ですが、golangではどう書くでしょうか。
結論。以下のようにしてできます。


package main

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
)

func main() {
	s := "Hello, World"
	b := getSHA256Binary(s)
	h := hex.EncodeToString(b)
	fmt.Println(b) // [3 103 90 197 63 249 205 21 53 204 199 223 205 250 44 69 140 82 24 55 31 65 141 193 54 242 209 154 193 251 232 165]
	fmt.Println(h) // 03675ac53ff9cd1535ccc7dfcdfa2c458c5218371f418dc136f2d19ac1fbe8a5
}

func getSHA256Binary(s string) []byte {
	r := sha256.Sum256([]byte(s))
	return r[:]
}

せっかくなので、一緒に使われることの多いhexへの変換も載せておきます

8
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?