Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hkdf: Replace nil salt with a slice of a preallocated all zeros buffer #260

Open
wants to merge 4 commits into
base: v2
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions hkdf.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,14 @@ func (c *hkdf1) Read(p []byte) (int, error) {
return n, nil
}

// hkdfAllZerosSalt is a preallocated buffer of zeros used in ExtractHKDF().
// The size should be kept as large as the output length of any hash algorithm
// used with HKDF.
var hkdfAllZerosSalt [64]byte

// ExtractHDKF implements the HDKF extract step.
// If salt is nil, then this function replaces it internally with a buffer of
// zeros whose length equals the output length of the specified hash algorithm.
func ExtractHKDF(h func() hash.Hash, secret, salt []byte) ([]byte, error) {
if !SupportsHKDF() {
return nil, errUnsupportedVersion()
Expand All @@ -119,6 +127,20 @@ func ExtractHKDF(h func() hash.Hash, secret, salt []byte) ([]byte, error) {
return nil, err
}

// If calling code specifies nil salt, replace it with a buffer of hashLen
// zeros, as specified in RFC 5896 and as OpenSSL EVP_KDF-HKDF documentation
// instructs. Take a slice of a preallocated buffer to avoid allocating new
// buffer per call, but fall back to allocating a buffer if preallocated
// buffer is not large enough.
if salt == nil {
hlen := h().Size()
if hlen > len(hkdfAllZerosSalt) {
salt = make([]byte, hlen)
} else {
salt = hkdfAllZerosSalt[:hlen]
}
}

switch vMajor {
case 1:
ctx, err := newHKDFCtx1(md, _EVP_KDF_HKDF_MODE_EXTRACT_ONLY, secret, salt, nil, nil)
Expand Down
Loading