Skip to content

Commit 9b5f537

Browse files
qmuntalgdamsdagood
authored
Support ExpandHKDF with zero-length keys (#330)
* add test * fix test * Apply suggestions from code review Co-authored-by: Davis Goodin <dagood@users.noreply.github.com> --------- Co-authored-by: George Adams <georgeadams1995@gmail.com> Co-authored-by: Davis Goodin <dagood@users.noreply.github.com>
1 parent 05bc310 commit 9b5f537

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

hkdf.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,12 @@ func ExpandHKDFOneShot(h func() hash.Hash, pseudorandomKey, info []byte, keyLeng
208208
return nil, err
209209
}
210210
defer ossl.EVP_PKEY_CTX_free(ctx)
211+
if len(out) == 0 {
212+
// Nothing to do, so exit early.
213+
// We also can't call EVP_PKEY_derive because some engines error on zero-length output.
214+
// We can only exit after calling newHKDFCtx1 because we still need it to validate the parameters.
215+
return out, nil
216+
}
211217
keylen := keyLength
212218
if _, err := ossl.EVP_PKEY_derive(ctx, base(out), &keylen); err != nil {
213219
return nil, err
@@ -218,6 +224,12 @@ func ExpandHKDFOneShot(h func() hash.Hash, pseudorandomKey, info []byte, keyLeng
218224
return nil, err
219225
}
220226
defer ossl.EVP_KDF_CTX_free(ctx)
227+
if len(out) == 0 {
228+
// Nothing to do, so exit early.
229+
// We also can't call EVP_PKEY_derive because some engines error on zero-length output.
230+
// We can only exit after calling newHKDFCtx3 because we still need it to validate the parameters.
231+
return out, nil
232+
}
221233
if _, err := ossl.EVP_KDF_derive(ctx, base(out), keyLength, nil); err != nil {
222234
return nil, err
223235
}

hkdf_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -646,3 +646,23 @@ func TestExpandTLS13KDF(t *testing.T) {
646646
}
647647
}
648648
}
649+
650+
func TestExpandHKDFZeroLengthKey(t *testing.T) {
651+
if !openssl.SupportsHKDF() {
652+
t.Skip("HKDF is not supported")
653+
}
654+
hash := openssl.NewSHA256
655+
master := []byte{0x00, 0x01, 0x02, 0x03}
656+
info := []byte{}
657+
prk, err := openssl.ExtractHKDF(hash, master, nil)
658+
if err != nil {
659+
t.Fatalf("error extracting HKDF: %v.", err)
660+
}
661+
out, err := openssl.ExpandHKDFOneShot(hash, prk, info, 0)
662+
if err != nil {
663+
t.Errorf("error expanding HKDF zero-length key: %v.", err)
664+
}
665+
if len(out) != 0 {
666+
t.Errorf("incorrect output length for zero-length key: have %d, need 0.", len(out))
667+
}
668+
}

0 commit comments

Comments
 (0)