Skip to content

Instantly share code, notes, and snippets.

@roppa
Forked from miguelmota/crypto.go
Created March 28, 2022 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roppa/b2ab8d2d41bbf507a8195f1b0007aa14 to your computer and use it in GitHub Desktop.
Save roppa/b2ab8d2d41bbf507a8195f1b0007aa14 to your computer and use it in GitHub Desktop.
Golang SHA256 hash example
package crypto
import (
"crypto/sha256"
)
// NewSHA256 ...
func NewSHA256(data []byte) []byte {
hash := sha256.Sum256(data)
return hash[:]
}
package crypto
import (
"encoding/hex"
"fmt"
"testing"
)
func TestNewSHA256(t *testing.T) {
for i, tt := range []struct {
in []byte
out string
}{
{[]byte(""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"},
{[]byte("abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"},
{[]byte("hello"), "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"},
} {
t.Run(fmt.Sprintf("%v", i), func(t *testing.T) {
result := NewSHA256(tt.in)
if hex.EncodeToString(result) != tt.out {
t.Errorf("want %v; got %v", tt.out, hex.EncodeToString(result))
}
})
}
}
package main
import (
"crypto/sha256"
"fmt"
)
func main() {
data := []byte("hello")
hash := sha256.Sum256(data)
fmt.Printf("%x", hash[:]) // 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment