package hkdf
import "golang.org/x/crypto/hkdf"
Package hkdf implements the HMAC-based Extract-and-Expand Key Derivation Function (HKDF) as defined in RFC 5869.
HKDF is a cryptographic key derivation function (KDF) with the goal of
expanding limited input keying material into one or more cryptographically
strong secret keys.
Usage example that expands one master secret into three other
cryptographically secure keys.
Code:play
Output:Example (Usage)¶
package main
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"fmt"
"io"
"golang.org/x/crypto/hkdf"
)
func main() {
// Underlying hash function for HMAC.
hash := sha256.New
// Cryptographically secure master secret.
secret := []byte{0x00, 0x01, 0x02, 0x03} // i.e. NOT this.
// Non-secret salt, optional (can be nil).
// Recommended: hash-length random value.
salt := make([]byte, hash().Size())
if _, err := rand.Read(salt); err != nil {
panic(err)
}
// Non-secret context info, optional (can be nil).
info := []byte("hkdf example")
// Generate three 128-bit derived keys.
hkdf := hkdf.New(hash, secret, salt, info)
var keys [][]byte
for i := 0; i < 3; i++ {
key := make([]byte, 16)
if _, err := io.ReadFull(hkdf, key); err != nil {
panic(err)
}
keys = append(keys, key)
}
for i := range keys {
fmt.Printf("Key #%d: %v\n", i+1, !bytes.Equal(keys[i], make([]byte, 16)))
}
}
Key #1: true
Key #2: true
Key #3: true
Index ¶
- func Expand(hash func() hash.Hash, pseudorandomKey, info []byte) io.Reader
- func Extract(hash func() hash.Hash, secret, salt []byte) []byte
- func New(hash func() hash.Hash, secret, salt, info []byte) io.Reader
Examples ¶
Functions ¶
func Expand ¶
Expand returns a Reader, from which keys can be read, using the given pseudorandom key and optional context info, skipping the extraction step.
The pseudorandomKey should have been generated by Extract, or be a uniformly random or pseudorandom cryptographically strong key. See RFC 5869, Section 3.3. Most common scenarios will want to use New instead.
func Extract ¶
Extract generates a pseudorandom key for use with Expand from an input secret and an optional independent salt.
Only use this function if you need to reuse the extracted key with multiple Expand invocations and different context values. Most common scenarios, including the generation of multiple keys, should use New instead.
func New ¶
New returns a Reader, from which keys can be read, using the given hash, secret, salt and context info. Salt and info can be nil.
Source Files ¶
hkdf.go
- Version
- v0.34.0 (latest)
- Published
- Feb 22, 2025
- Platform
- linux/amd64
- Imports
- 4 packages
- Last checked
- 8 hours ago –
Tools for package owners.