...
Package 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.
▾ Example (Usage)
Usage example that expands one master secret into three other
cryptographically secure keys.
Code:
hash := sha256.New
keyLen := hash().Size()
secret := []byte{0x00, 0x01, 0x02, 0x03}
salt := make([]byte, hash().Size())
if _, err := rand.Read(salt); err != nil {
panic(err)
}
info := "hkdf example"
var keys [][]byte
for i := 0; i < 3; i++ {
key, err := hkdf.Key(hash, secret, salt, info, keyLen)
if 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)))
}
Output:
Key #1: true
Key #2: true
Key #3: true
- func Expand[H hash.Hash](h func() H, pseudorandomKey []byte, info string, keyLength int) ([]byte, error)
- func Extract[H hash.Hash](h func() H, secret, salt []byte) ([]byte, error)
- func Key[Hash hash.Hash](h func() Hash, secret, salt []byte, info string, keyLength int) ([]byte, error)
Package files
hkdf.go
func Expand[H hash.Hash](h func() H, pseudorandomKey []byte, info string, keyLength int) ([]byte, error)
Expand derives a key from the given hash, key, and optional context info,
returning a []byte of length keyLength that can be used as cryptographic key.
The extraction step is skipped.
The key 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 Key instead.
func Extract[H hash.Hash](h func() H, secret, salt []byte) ([]byte, error)
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 Key instead.
func Key
¶
1.24
func Key[Hash hash.Hash](h func() Hash, secret, salt []byte, info string, keyLength int) ([]byte, error)
Key derives a key from the given hash, secret, salt and context info,
returning a []byte of length keyLength that can be used as cryptographic key.
Salt and info can be nil.