Skip to content

Commit cc0e4fc

Browse files
FiloSottilegopherbot
authored andcommitted
hkdf: forward Extract to the standard library
Change-Id: I82406eb153c53e7cbf167360e472724a6a6a6964 Reviewed-on: https://go-review.googlesource.com/c/crypto/+/769720 Reviewed-by: Daniel McCarney <daniel@binaryparadox.net> Reviewed-by: Roland Shoemaker <roland@golang.org> LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Reviewed-by: Carlos Amedee <carlos@golang.org> Auto-Submit: Filippo Valsorda <filippo@golang.org>
1 parent a8e9237 commit cc0e4fc

1 file changed

Lines changed: 13 additions & 8 deletions

File tree

hkdf/hkdf.go

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
package hkdf
1212

1313
import (
14+
"crypto/hkdf"
1415
"crypto/hmac"
1516
"errors"
1617
"hash"
@@ -24,15 +25,19 @@ import (
2425
// Expand invocations and different context values. Most common scenarios,
2526
// including the generation of multiple keys, should use New instead.
2627
func Extract(hash func() hash.Hash, secret, salt []byte) []byte {
27-
if salt == nil {
28-
salt = make([]byte, hash().Size())
28+
// Use the stdlib Extract, which disables FIPS 140 enforcement of the HMAC
29+
// key (which in HKDF is the salt). The only possible error is FIPS 140
30+
// enforcement of the hash, which had to panic under this API anyway. We
31+
// don't use the stdlib Expand, because it switched to returning a []byte
32+
// instead of an io.Reader, and Expand uses the HMAC key as a key.
33+
out, err := hkdf.Extract(hash, secret, salt)
34+
if err != nil {
35+
panic(err)
2936
}
30-
extractor := hmac.New(hash, salt)
31-
extractor.Write(secret)
32-
return extractor.Sum(nil)
37+
return out
3338
}
3439

35-
type hkdf struct {
40+
type hkdfReader struct {
3641
expander hash.Hash
3742
size int
3843

@@ -43,7 +48,7 @@ type hkdf struct {
4348
buf []byte
4449
}
4550

46-
func (f *hkdf) Read(p []byte) (int, error) {
51+
func (f *hkdfReader) Read(p []byte) (int, error) {
4752
// Check whether enough data can be generated
4853
need := len(p)
4954
remains := len(f.buf) + int(255-f.counter+1)*f.size
@@ -84,7 +89,7 @@ func (f *hkdf) Read(p []byte) (int, error) {
8489
// 3.3. Most common scenarios will want to use New instead.
8590
func Expand(hash func() hash.Hash, pseudorandomKey, info []byte) io.Reader {
8691
expander := hmac.New(hash, pseudorandomKey)
87-
return &hkdf{expander, expander.Size(), info, 1, nil, nil}
92+
return &hkdfReader{expander, expander.Size(), info, 1, nil, nil}
8893
}
8994

9095
// New returns a Reader, from which keys can be read, using the given hash,

0 commit comments

Comments
 (0)