Skip to content

Commit 0ec829d

Browse files
samiponkanensshnicholasberlin
authored andcommitted
hkdf: Replace nil salt with a slice of a preallocated all zeros buffer (#260)
* hkdf: Replace nil salt with a slice of a preallocated all zeros buffer. This fixes HKDF when using KeyPair FIPS Provider for OpenSSL 3 * hkdf: fixed PR review comments * hkdf: second round of PR comment fixes * hkdf: third round of PR comment fixes
1 parent b757f9d commit 0ec829d

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

hkdf.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,14 @@ func (c *hkdf1) Read(p []byte) (int, error) {
123123
return n, nil
124124
}
125125

126+
// hkdfAllZerosSalt is a preallocated buffer of zeros used in ExtractHKDF().
127+
// The size should be kept as large as the output length of any hash algorithm
128+
// used with HKDF.
129+
var hkdfAllZerosSalt [64]byte
130+
131+
// ExtractHDKF implements the HDKF extract step.
132+
// If salt is nil, then this function replaces it internally with a buffer of
133+
// zeros whose length equals the output length of the specified hash algorithm.
126134
func ExtractHKDF(h func() hash.Hash, secret, salt []byte) ([]byte, error) {
127135
if !SupportsHKDF() {
128136
return nil, errUnsupportedVersion()
@@ -133,6 +141,20 @@ func ExtractHKDF(h func() hash.Hash, secret, salt []byte) ([]byte, error) {
133141
return nil, err
134142
}
135143

144+
// If calling code specifies nil salt, replace it with a buffer of hashLen
145+
// zeros, as specified in RFC 5896 and as OpenSSL EVP_KDF-HKDF documentation
146+
// instructs. Take a slice of a preallocated buffer to avoid allocating new
147+
// buffer per call, but fall back to allocating a buffer if preallocated
148+
// buffer is not large enough.
149+
if salt == nil {
150+
hlen := h().Size()
151+
if hlen > len(hkdfAllZerosSalt) {
152+
salt = make([]byte, hlen)
153+
} else {
154+
salt = hkdfAllZerosSalt[:hlen]
155+
}
156+
}
157+
136158
switch vMajor {
137159
case 1:
138160
ctx, err := newHKDFCtx1(md, C.GO_EVP_KDF_HKDF_MODE_EXTRACT_ONLY, secret, salt, nil, nil)

0 commit comments

Comments
 (0)