Go SHA-256 Hash Code Example (Online Runner)
Go SHA-256 hashing code example with runnable snippets to calculate SHA-256 for text and files.
Online calculator: use the site SHA-256 text tool.
Calculation method
Use crypto/sha256, hash UTF-8 bytes, and encode the 32-byte digest as hex.
Implementation notes
- Package: built-in
crypto/sha256. - Implementation: file hashing streams bytes to avoid loading large files into memory.
- Notes: SHA-256 is not keyed; use HMAC for authentication or Argon2/scrypt for passwords.
Text hashing example
go
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
)
func sha256Text(text string) string {
sum := sha256.Sum256([]byte(text))
return hex.EncodeToString(sum[:])
}
func main() {
fmt.Println(sha256Text("hello world"))
}File hashing example
go
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
)
func sha256File(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
func main() {
file, err := os.CreateTemp("", "sha256-example-*.bin")
if err != nil {
panic(err)
}
defer os.Remove(file.Name())
if _, err := file.Write([]byte("example payload\n")); err != nil {
panic(err)
}
if err := file.Close(); err != nil {
panic(err)
}
value, err := sha256File(file.Name())
if err != nil {
panic(err)
}
fmt.Println(value)
}Complete script (implementation + tests)
go
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
)
func sha256Hex(data []byte) string {
sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:])
}
func sha256Text(text string) string {
return sha256Hex([]byte(text))
}
func sha256File(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
func main() {
vectors := map[string]string{
"": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"abc": "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
"message digest": "f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650",
"abcdefghijklmnopqrstuvwxyz": "71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73",
}
for input, expected := range vectors {
if got := sha256Text(input); got != expected {
panic(fmt.Sprintf("SHA-256 mismatch for %q: %s != %s", input, got, expected))
}
}
file, err := os.CreateTemp("", "sha256-example-*.bin")
if err != nil {
panic(err)
}
defer os.Remove(file.Name())
if _, err := file.Write([]byte("example payload\n")); err != nil {
panic(err)
}
if err := file.Close(); err != nil {
panic(err)
}
fileHash, err := sha256File(file.Name())
if err != nil {
panic(err)
}
fmt.Println("sha256(file)=", fileHash)
fmt.Println("All SHA-256 test vectors passed.")
}