Skip to main content
SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature.

Computing a SHA256 Hash

Go implements several hash functions in various crypto/* packages:
import (
    "crypto/sha256"
    "fmt"
)

s := "sha256 this string"

Creating the Hash

Start with a new hash:
h := sha256.New()

Writing Data

Write expects bytes. If you have a string, use []byte(s) to convert it:
h.Write([]byte(s))

Getting the Result

Get the finalized hash result as a byte slice:
bs := h.Sum(nil)

fmt.Println(s)
fmt.Printf("%x\n", bs)
Output:
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a0d3db739d77aacb
The argument to Sum can be used to append to an existing byte slice, but it usually isn’t needed.

Hash Functions

sha256.New
func() hash.Hash
Creates a new SHA256 hash
Write
func(p []byte) (n int, err error)
Adds more data to the hash
Sum
func(b []byte) []byte
Returns the current hash, appending to b if provided

Other Hash Functions

Go provides several other hash functions in the crypto package:

MD5

crypto/md5 - 128-bit hash (not recommended for security)

SHA1

crypto/sha1 - 160-bit hash (deprecated for security)

SHA512

crypto/sha512 - 512-bit hash (more secure)

Blake2

golang.org/x/crypto/blake2b - Fast cryptographic hash

Example: File Hashing

Compute the SHA256 hash of a file:
import (
    "crypto/sha256"
    "fmt"
    "io"
    "os"
)

f, err := os.Open("file.txt")
if err != nil {
    panic(err)
}
defer f.Close()

h := sha256.New()
io.Copy(h, f)

fmt.Printf("%x\n", h.Sum(nil))

Computing Hash in One Step

For convenience, compute a hash directly from a byte slice:
data := []byte("sha256 this string")
hash := sha256.Sum256(data)

fmt.Printf("%x\n", hash)
// Output: 1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a0d3db739d77aacb
Use Sum256 when you have all the data at once. Use New() when you need to hash data incrementally.

Package Reference

Build docs developers (and LLMs) love