From 77c221d941a8180a3c67fc6147ad6d6dddc47097 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AF=A7=E9=9D=9C?= Date: Tue, 8 Dec 2020 13:37:08 +0800 Subject: [PATCH] fix HKDF-Extract with empty salt #45 (#46) --- hkdf/src/hkdf.rs | 8 +++----- hkdf/tests/tests.rs | 14 ++++++++++++-- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/hkdf/src/hkdf.rs b/hkdf/src/hkdf.rs index e61d658..1a6cfd4 100644 --- a/hkdf/src/hkdf.rs +++ b/hkdf/src/hkdf.rs @@ -69,11 +69,9 @@ where { /// Initiates the HKDF-Extract context with the given optional salt pub fn new(salt: Option<&[u8]>) -> HkdfExtract { - let hmac = match salt { - Some(s) => Hmac::::new_varkey(s).expect("HMAC can take a key of any size"), - None => Hmac::::new(&Default::default()), - }; - + let default_salt = GenericArray::::default(); + let salt = salt.unwrap_or(&default_salt); + let hmac = Hmac::::new_varkey(salt).expect("HMAC can take a key of any size"); HkdfExtract { hmac } } diff --git a/hkdf/tests/tests.rs b/hkdf/tests/tests.rs index 7257923..6b18e0d 100644 --- a/hkdf/tests/tests.rs +++ b/hkdf/tests/tests.rs @@ -65,7 +65,12 @@ fn test_derive_sha256() { let ikm = hex::decode(&t.ikm).unwrap(); let salt = hex::decode(&t.salt).unwrap(); let info = hex::decode(&t.info).unwrap(); - let (prk, hkdf) = Hkdf::::extract(Option::from(&salt[..]), &ikm[..]); + let salt = if salt.is_empty() { + None + } else { + Some(&salt[..]) + }; + let (prk, hkdf) = Hkdf::::extract(salt, &ikm[..]); let mut okm = vec![0u8; t.length]; assert!(hkdf.expand(&info[..], &mut okm).is_ok()); @@ -204,7 +209,12 @@ fn test_derive_sha1() { let ikm = hex::decode(&t.ikm).unwrap(); let salt = hex::decode(&t.salt).unwrap(); let info = hex::decode(&t.info).unwrap(); - let (prk, hkdf) = Hkdf::::extract(Some(&salt[..]), &ikm[..]); + let salt = if salt.is_empty() { + None + } else { + Some(&salt[..]) + }; + let (prk, hkdf) = Hkdf::::extract(salt, &ikm[..]); let mut okm = vec![0u8; t.length]; assert!(hkdf.expand(&info[..], &mut okm).is_ok());