Skip to content

Commit 7fa651e

Browse files
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 57098a7 commit 7fa651e

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
@@ -108,6 +108,14 @@ func (c *hkdf1) Read(p []byte) (int, error) {
108108
return n, nil
109109
}
110110

111+
// hkdfAllZerosSalt is a preallocated buffer of zeros used in ExtractHKDF().
112+
// The size should be kept as large as the output length of any hash algorithm
113+
// used with HKDF.
114+
var hkdfAllZerosSalt [64]byte
115+
116+
// ExtractHDKF implements the HDKF extract step.
117+
// If salt is nil, then this function replaces it internally with a buffer of
118+
// zeros whose length equals the output length of the specified hash algorithm.
111119
func ExtractHKDF(h func() hash.Hash, secret, salt []byte) ([]byte, error) {
112120
if !SupportsHKDF() {
113121
return nil, errUnsupportedVersion()
@@ -118,6 +126,20 @@ func ExtractHKDF(h func() hash.Hash, secret, salt []byte) ([]byte, error) {
118126
return nil, err
119127
}
120128

129+
// If calling code specifies nil salt, replace it with a buffer of hashLen
130+
// zeros, as specified in RFC 5896 and as OpenSSL EVP_KDF-HKDF documentation
131+
// instructs. Take a slice of a preallocated buffer to avoid allocating new
132+
// buffer per call, but fall back to allocating a buffer if preallocated
133+
// buffer is not large enough.
134+
if salt == nil {
135+
hlen := h().Size()
136+
if hlen > len(hkdfAllZerosSalt) {
137+
salt = make([]byte, hlen)
138+
} else {
139+
salt = hkdfAllZerosSalt[:hlen]
140+
}
141+
}
142+
121143
switch vMajor {
122144
case 1:
123145
ctx, err := newHKDFCtx1(md, _EVP_KDF_HKDF_MODE_EXTRACT_ONLY, secret, salt, nil, nil)

0 commit comments

Comments
 (0)