1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package hkdf implements the HMAC-based Extract-and-Expand Key Derivation
6 // Function (HKDF) as defined in RFC 5869.
8 // HKDF is a cryptographic key derivation function (KDF) with the goal of
9 // expanding limited input keying material into one or more cryptographically
10 // strong secret keys.
12 // RFC 5869: https://tools.ietf.org/html/rfc5869
13 package hkdf // import "golang.org/x/crypto/hkdf"
33 func (f *hkdf) Read(p []byte) (int, error) {
34 // Check whether enough data can be generated
36 remains := len(f.cache) + int(255-f.counter+1)*f.size
38 return 0, errors.New("hkdf: entropy limit reached")
40 // Read from the cache, if enough data is present
47 f.expander.Write(f.prev)
48 f.expander.Write(f.info)
49 f.expander.Write([]byte{f.counter})
50 f.prev = f.expander.Sum(f.prev[:0])
53 // Copy the new batch into p
58 // Save leftovers for next run
64 // New returns a new HKDF using the given hash, the secret keying material to expand
65 // and optional salt and info fields.
66 func New(hash func() hash.Hash, secret, salt, info []byte) io.Reader {
68 salt = make([]byte, hash().Size())
70 extractor := hmac.New(hash, salt)
71 extractor.Write(secret)
72 prk := extractor.Sum(nil)
74 return &hkdf{hmac.New(hash, prk), extractor.Size(), info, 1, nil, nil}