SHA-3, SHAKE, and HKDF
suggest changeGo 1.24 moved two commonly used packages from golang.org/x/crypto into the standard library:
crypto/sha3: the SHA-3 hash functions (SHA3-224, SHA3-256, SHA3-384, SHA3-512) and the SHAKE extendable output functions, all defined in FIPS 202crypto/hkdf: HKDF, the HMAC-based key derivation function from RFC 5869
Go 1.25 added two interfaces to the hash package that go with them:
hash.XOF, the interface for extendable output functions like SHAKEhash.Cloner, for copying the state of a hash in the middle of a computation
This article shows how to use all of them. Every hex output below was checked against published test vectors (FIPS 202 examples, NIST SP 800-185 samples and RFC 5869) where one exists.
For HMAC signatures and constant-time comparison see Application security. For passwords use a slow password hashing function, not SHA-3 or HKDF: see Password hashing, which also covers crypto/pbkdf2.
SHA-3
sha3.Sum256 hashes a byte slice in one call and returns a [32]byte array, just like sha256.Sum256:
package main
import (
"crypto/sha3"
"fmt"
)
func main() {
fmt.Printf("%x\n", sha3.Sum256([]byte("")))
fmt.Printf("%x\n", sha3.Sum256([]byte("abc")))
h := sha3.New256()
h.Write([]byte("a"))
h.Write([]byte("bc"))
fmt.Printf("%x\n", h.Sum(nil))
fmt.Println(h.Size(), h.BlockSize())
}
a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a
3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532
3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532
32 136
For data that arrives in pieces (a file, a network stream) use sha3.New256(), which returns a *sha3.SHA3. It implements hash.Hash, so you can Write to it, or io.Copy a file into it, and call Sum at the end. Sum appends the hash to its argument and doesn't change the state, so you can keep writing after it.
The functions for each size:
| one-shot | streaming | output size |
|---|---|---|
sha3.Sum224 |
sha3.New224() |
28 bytes |
sha3.Sum256 |
sha3.New256() |
32 bytes |
sha3.Sum384 |
sha3.New384() |
48 bytes |
sha3.Sum512 |
sha3.New512() |
64 bytes |
crypto.SHA3_256 and friends are registered by importing crypto/sha3, so APIs that take a crypto.Hash, like rsa.SignPSS, can use SHA-3 too.
SHA-3 or SHA-256?
SHA-2 (SHA-256, SHA-512) is not broken, is faster on most CPUs thanks to hardware instructions, and is what most protocols and file formats specify. Use SHA-256 unless:
- a protocol or standard requires SHA-3 (many post-quantum algorithms, like ML-KEM and ML-DSA, are built on SHA-3 and SHAKE)
- you want a hash with a completely different internal design as a hedge against a future attack on SHA-2
- you need variable-length output, which is what SHAKE is for
SHA-3 is not vulnerable to length-extension attacks, unlike SHA-256. That means sha3.Sum256(append(key, msg...)) is a valid MAC. Still, hmac.New works with any hash, and HMAC is what other systems expect, so prefer HMAC for interoperability.
golang.org/x/crypto/sha3
golang.org/x/crypto/sha3 is now a thin wrapper around crypto/sha3. New code should import the standard library package. The one thing that stays only in x/crypto is the legacy Keccak hash (sha3.NewLegacyKeccak256), which is the pre-standard variant used by Ethereum. It produces different output than SHA3-256.
SHAKE: hashes with any output length
SHAKE128 and SHAKE256 are extendable output functions (XOFs). They work like a hash, except that instead of a fixed 32 or 64 bytes you can read as many output bytes as you want. The number in the name is the security level in bits, not the output size.
sha3.SumSHAKE128 and sha3.SumSHAKE256 take the desired length:
package main
import (
"crypto/sha3"
"fmt"
)
func main() {
// one-shot: ask for exactly the number of bytes you need
fmt.Printf("%x\n", sha3.SumSHAKE128([]byte(""), 32))
fmt.Printf("%x\n", sha3.SumSHAKE256([]byte(""), 64))
// a shorter output is a prefix of a longer one
fmt.Printf("%x\n", sha3.SumSHAKE128([]byte(""), 8))
}
7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26
46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762fd75dc4ddd8c0f200cb05019d67b592f6fc821c49479ab48640292eacb3b7c4be
7f9c2ba4e88f827d
Note the last line: the 8-byte output is the first 8 bytes of the 32-byte output. The length is not an input to the function. If you derive two values of different lengths from the same input, they will be related, so don't truncate the same SHAKE output for different purposes. Give each purpose its own input, or use cSHAKE (below).
For security, the output should be at least twice the security level: 32 bytes from SHAKE128, 64 bytes from SHAKE256, to get full collision resistance.
Streaming with hash.XOF
sha3.NewSHAKE128() and sha3.NewSHAKE256() return a *sha3.SHAKE. It implements the hash.XOF interface added in Go 1.25:
type XOF interface {
io.Writer // absorb input; panics if called after Read
io.Reader // squeeze output
Reset()
BlockSize() int
}
You first Write all the input, then Read output in as many calls as you like:
package main
import (
"crypto/sha3"
"fmt"
"hash"
"io"
)
func main() {
var x hash.XOF = sha3.NewSHAKE256()
x.Write([]byte("seed for a stream"))
// Read as much as you want, in as many calls as you want.
a := make([]byte, 16)
b := make([]byte, 16)
io.ReadFull(x, a)
io.ReadFull(x, b)
fmt.Printf("%x\n%x\n", a, b)
// The same as reading 32 bytes at once.
fmt.Printf("%x\n", sha3.SumSHAKE256([]byte("seed for a stream"), 32))
defer func() { fmt.Println("panic:", recover()) }()
x.Write([]byte("more")) // Write after Read panics
}
d1381002c0d482ca890df9c6b94602ec
b117dbaf2ed6b9387cb0a26f30eadfba
d1381002c0d482ca890df9c6b94602ecb117dbaf2ed6b9387cb0a26f30eadfba
panic: sha3: Write after Read
Two reads of 16 bytes give the same bytes as one read of 32. Once you start reading, the input is final: calling Write panics. Call Reset to start over.
Because a *sha3.SHAKE is an io.Reader, you can pass it anywhere a stream of bytes is expected. Write functions that take hash.XOF rather than *sha3.SHAKE so callers can choose SHAKE128, SHAKE256 or cSHAKE, or plug in another XOF implementation.
A SHAKE stream is deterministic: anyone with the same input gets the same bytes. It's handy for expanding a seed into test data or into a public parameter (that's how ML-KEM generates its matrix), but it's not a replacement for crypto/rand when you need secrets.
cSHAKE: domain separation
sha3.NewCSHAKE128(N, S) and sha3.NewCSHAKE256(N, S) create customizable SHAKE (NIST SP 800-185). S is a customization string: the same input with different S values gives unrelated outputs. N is a function name reserved for algorithms defined by NIST (KMAC, TupleHash), so pass nil for your own uses. With both empty, cSHAKE is plain SHAKE.
package main
import (
"crypto/sha3"
"fmt"
)
func main() {
// NIST SP 800-185 cSHAKE128 sample #2
c := sha3.NewCSHAKE128(nil, []byte("Email Signature"))
c.Write([]byte{0x00, 0x01, 0x02, 0x03})
out := make([]byte, 32)
c.Read(out)
fmt.Printf("%x\n", out)
// Same input, different customization string: unrelated output.
for _, s := range []string{"encryption key", "mac key"} {
c := sha3.NewCSHAKE256(nil, []byte(s))
c.Write([]byte("shared secret"))
k := make([]byte, 16)
c.Read(k)
fmt.Printf("%-15s %x\n", s, k)
}
}
c1c36925b6409a04f1b504fcbca9d82b4017277cb5ed2b2065fc1d3814d5aaf5
encryption key eddd775207a1ab051712a8fa716cdd6a
mac key 03abafdff96d4bd0fc91816bab951639
The first line matches the NIST sample. To derive keys, the more common tool is HKDF.
HKDF: deriving keys
Often you have one secret and need several keys from it. A key exchange (ECDH with crypto/ecdh, or ML-KEM) gives you a shared secret, and you need an AES key and an HMAC key. Or you have one master key in configuration and want a separate key per tenant or per purpose.
Don't use the secret directly, and don't make up a scheme like sha256(secret + "enc"). Use a key derivation function. HKDF is the standard one: TLS 1.3, Signal, HPKE, WireGuard-style protocols and many others use it.
HKDF has two steps:
- Extract: mix the input secret and an optional salt into a fixed-size pseudorandom key (PRK)
- Expand: stretch the PRK into as many output bytes as needed, bound to an
infostring that describes what the key is for
hkdf.Key does both steps in one call. This is the RFC 5869 test case 1:
package main
import (
"bytes"
"crypto/hkdf"
"crypto/sha256"
"encoding/hex"
"fmt"
"log"
)
func main() {
// RFC 5869, Appendix A.1 (test case 1)
ikm := bytes.Repeat([]byte{0x0b}, 22)
salt, _ := hex.DecodeString("000102030405060708090a0b0c")
info, _ := hex.DecodeString("f0f1f2f3f4f5f6f7f8f9")
okm, err := hkdf.Key(sha256.New, ikm, salt, string(info), 42)
if err != nil {
log.Fatal(err)
}
fmt.Printf("OKM = %x\n", okm)
}
OKM = 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865
The signature is:
func Key[H hash.Hash](h func() H, secret, salt []byte, info string, keyLength int) ([]byte, error)
his a hash constructor such assha256.New. The function is generic, so constructors that return a concrete type, likesha3.New256(which returns*sha3.SHA3), work too.secretis the input keying material. It must already have enough entropy. HKDF doesn't slow down guessing, so a password is not a valid input (use Argon2id or PBKDF2 for that).saltis optional (nilis fine) and doesn't have to be secret. A random salt makes the derived keys stronger when the secret isn't uniformly random, as with a Diffie-Hellman output.infobinds the key to its purpose. Differentinfostrings give independent keys.keyLengthis the number of bytes you want, at most 255 times the hash size (8160 bytes for SHA-256).
Unlike the old golang.org/x/crypto/hkdf, which returned an io.Reader, the standard library version returns the key directly. The error is returned when keyLength is too large or the hash isn't allowed in FIPS 140-3 mode.
Several keys from one secret
Call hkdf.Key once per key, with a different info each time:
package main
import (
"crypto/hkdf"
"crypto/rand"
"crypto/sha256"
"fmt"
"log"
)
// sessionKeys derives independent keys from one shared secret.
// salt is public and may be stored or sent next to the ciphertext.
func sessionKeys(secret, salt []byte) (encKey, macKey []byte, err error) {
encKey, err = hkdf.Key(sha256.New, secret, salt, "myapp v1 encryption", 32)
if err != nil {
return nil, nil, err
}
macKey, err = hkdf.Key(sha256.New, secret, salt, "myapp v1 mac", 32)
if err != nil {
return nil, nil, err
}
return encKey, macKey, nil
}
func main() {
secret := []byte("a 32-byte secret from ECDH / KEM") // normally from a key exchange
salt := make([]byte, 16)
rand.Read(salt)
enc, mac, err := sessionKeys(secret, salt)
if err != nil {
log.Fatal(err)
}
fmt.Println(len(enc), len(mac))
fmt.Println("keys differ:", string(enc) != string(mac))
// Deterministic: the same inputs always give the same keys.
enc2, _, _ := sessionKeys(secret, salt)
fmt.Println("reproducible:", string(enc) == string(enc2))
}
32 32
keys differ: true
reproducible: true
Put the application name and a version in info. If you ever change how keys are used, bump the version and old and new keys can never collide. The 32-byte encKey is ready for AES-256-GCM as shown in Encryption and decryption with AES GCM.
Deriving one long output and slicing it (okm[:32], okm[32:]) also works, but separate info strings are clearer and let you add keys later without changing existing ones.
Extract and Expand separately
When you derive many keys from the same secret, you can run Extract once and Expand many times:
package main
import (
"bytes"
"crypto/hkdf"
"crypto/sha256"
"encoding/hex"
"fmt"
"log"
)
func main() {
ikm := bytes.Repeat([]byte{0x0b}, 22)
salt, _ := hex.DecodeString("000102030405060708090a0b0c")
info, _ := hex.DecodeString("f0f1f2f3f4f5f6f7f8f9")
prk, err := hkdf.Extract(sha256.New, ikm, salt)
if err != nil {
log.Fatal(err)
}
fmt.Printf("PRK = %x\n", prk)
okm, err := hkdf.Expand(sha256.New, prk, string(info), 42)
if err != nil {
log.Fatal(err)
}
fmt.Printf("OKM = %x\n", okm)
// The output is limited to 255 * hash size bytes.
_, err = hkdf.Expand(sha256.New, prk, "", 255*32+1)
fmt.Println(err)
}
PRK = 077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5
OKM = 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865
hkdf: requested key length too large
Both PRK and OKM match RFC 5869. The PRK is a secret: treat it like the input secret.
hkdf.Expand skips extraction, so only pass it a key that is already uniformly random: a PRK from Extract, or 32 bytes from crypto/rand. Protocols like TLS 1.3 call Expand directly on such keys. For everything else, hkdf.Key is the safe default.
HKDF with SHA-3
Any hash works. With SHA3-256:
package main
import (
"crypto/hkdf"
"crypto/sha3"
"fmt"
"log"
)
func main() {
secret := []byte("input keying material")
// sha3.New256 returns *sha3.SHA3; hkdf's generic signature accepts it as is.
key, err := hkdf.Key(sha3.New256, secret, nil, "example", 32)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%x\n", key)
}
569dbda6ab242d7de8833432d1e11cd103e7e6d9321c078adf983f17965567ef
There's no official test vector for HKDF-SHA3-256. This output was cross-checked with Python's hmac and hashlib.sha3_256. Use SHA-256 unless a protocol says otherwise; both sides must use the same hash.
Cloning hash state with hash.Cloner
Sometimes many messages share a long prefix: a fixed header, a domain separation string, a large common part of a file. Instead of hashing the prefix again for each message, hash it once and copy the state.
Go 1.25 added hash.Cloner:
type Cloner interface {
Hash
Clone() (Cloner, error)
}
*sha3.SHA3 has a Clone method. Functions like sha256.New return a plain hash.Hash, so you type-assert to hash.Cloner:
package main
import (
"crypto/sha256"
"crypto/sha3"
"fmt"
"hash"
"log"
)
func main() {
// Hash a common prefix once.
base := sha3.New256()
base.Write([]byte("ab"))
// Clone it and continue with different suffixes.
for _, suffix := range []string{"c", "d"} {
c, err := base.Clone()
if err != nil {
log.Fatal(err)
}
c.Write([]byte(suffix))
fmt.Printf("ab%s %x\n", suffix, c.Sum(nil))
}
fmt.Printf("abc %x (sha3.Sum256)\n", sha3.Sum256([]byte("abc")))
// sha256.New returns hash.Hash; type-assert to hash.Cloner.
var h hash.Hash = sha256.New()
h.Write([]byte("a"))
c, err := h.(hash.Cloner).Clone()
if err != nil {
log.Fatal(err)
}
c.Write([]byte("bc"))
fmt.Printf("abc %x\n", c.Sum(nil))
fmt.Printf("a %x\n", h.Sum(nil)) // original is unchanged
}
abc 3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532
abd f5f119fa0e57ad6839cdcd08902827a07120b6cf490e34af8f12144dc0dcec45
abc 3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532 (sha3.Sum256)
abc ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
a ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb
The clone and the original are independent: writing to one doesn't affect the other.
All hashes in the standard library implement hash.Cloner (except when built with the frozen GOFIPS140=v1.0.0 module). Hashes from third-party packages may not, and a hash that wraps another hash can only find out at run time whether cloning is possible; it then returns an error wrapping errors.ErrUnsupported. A helper that handles both cases:
package main
import (
"crypto/hmac"
"crypto/sha256"
"errors"
"fmt"
"hash"
)
// clone returns an independent copy of h's state.
func clone(h hash.Hash) (hash.Hash, error) {
c, ok := h.(hash.Cloner)
if !ok {
return nil, fmt.Errorf("%T: %w", h, errors.ErrUnsupported)
}
return c.Clone()
}
func main() {
mac := hmac.New(sha256.New, []byte("key"))
mac.Write([]byte("header|"))
c, err := clone(mac)
if err != nil {
fmt.Println("error:", err)
return
}
c.Write([]byte("body"))
fmt.Printf("%x\n", c.Sum(nil))
whole := hmac.New(sha256.New, []byte("key"))
whole.Write([]byte("header|body"))
fmt.Printf("%x\n", whole.Sum(nil))
}
8fe2888aa2233cb2b810a5e2ab35e6d1c35b0c297ec937a7108f46634b82f272
8fe2888aa2233cb2b810a5e2ab35e6d1c35b0c297ec937a7108f46634b82f272
HMAC is a hash that wraps another hash: it can be cloned because sha256 can.
Saving state with MarshalBinary
Clone copies state in memory. To save it to disk or a database, for example to resume hashing a large upload in a later request, use MarshalBinary and UnmarshalBinary. *sha3.SHAKE has no Clone method, but it can be copied the same way:
package main
import (
"crypto/sha3"
"fmt"
"log"
)
func main() {
h := sha3.New256()
h.Write([]byte("first part of a large upload, "))
// Save the state, e.g. to a database, between requests.
state, err := h.MarshalBinary()
if err != nil {
log.Fatal(err)
}
fmt.Println("state size:", len(state))
// Later, possibly in another process:
h2 := sha3.New256()
if err := h2.UnmarshalBinary(state); err != nil {
log.Fatal(err)
}
h2.Write([]byte("second part"))
fmt.Printf("%x\n", h2.Sum(nil))
fmt.Printf("%x\n", sha3.Sum256([]byte("first part of a large upload, second part")))
// SHAKE has no Clone, but its state can be copied the same way.
x := sha3.NewSHAKE128()
x.Write([]byte("abc"))
snap, _ := x.MarshalBinary()
y := sha3.NewSHAKE128()
y.UnmarshalBinary(snap)
a, b := make([]byte, 8), make([]byte, 8)
x.Read(a)
y.Read(b)
fmt.Printf("%x %x\n", a, b)
}
state size: 207
e246bcd4716b2996e8ec3687fa028a9978f46484e326f1d9e1dc6ff8d86e720b
e246bcd4716b2996e8ec3687fa028a9978f46484e326f1d9e1dc6ff8d86e720b
5881092dd818bf5c 5881092dd818bf5c
The saved state can contain parts of the input in their original form. If the input is secret, protect the state as you would protect the input. hmac.New hashes don't support MarshalBinary, since the state would expose the key.
Summary
| task | use |
|---|---|
| general-purpose hash | sha256.Sum256 (or sha3.Sum256 when SHA-3 is required) |
| variable-length hash output | sha3.SumSHAKE128, sha3.SumSHAKE256 |
| deterministic byte stream from a seed | sha3.NewSHAKE256() as hash.XOF / io.Reader |
| domain-separated SHAKE | sha3.NewCSHAKE128(nil, customization) |
| keys from a shared secret | hkdf.Key(sha256.New, secret, salt, info, n) |
| many keys from one secret | hkdf.Extract once, hkdf.Expand per key |
| keys from a password | not HKDF: Password hashing |
| reuse a hashed prefix | hash.Cloner and Clone() |
| persist hash state | MarshalBinary / UnmarshalBinary |