Go by Example

SHA256 Hashes

crypto/sha256 for one-shot and streaming SHA-256 hashing, hex encoding the digest, and when not to use SHA256 for passwords.

The crypto/sha256 package makes a fixed 32-byte digest, a short summary calculated from the input bytes. A change to the input changes the digest. Use sha256.Sum256 for small inputs, then hex encoding to print the bytes as text.

The returned digest is an array. Slice it when passing it to functions such as hex.EncodeToString.

package main
 
import (
    "crypto/sha256"
    "encoding/hex"
    "fmt"
)
 
func main() {
    digest := sha256.Sum256([]byte("hello"))
    fmt.Println(hex.EncodeToString(digest[:]))
}

In production

For a large input, use sha256.New with io.Copy to calculate the digest as the data is read. SHA-256 is useful for checking whether data changed, but it is too fast for storing passwords. Password storage needs a purpose-built function that makes each check slow and costly.

Enjoyed this? Get more software craft delivered to your inbox.