Skip to content

Commit

Permalink
fix HKDF-Extract with empty salt #45 (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
寧靜 authored Dec 8, 2020
1 parent e413e0a commit 77c221d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
8 changes: 3 additions & 5 deletions hkdf/src/hkdf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,9 @@ where
{
/// Initiates the HKDF-Extract context with the given optional salt
pub fn new(salt: Option<&[u8]>) -> HkdfExtract<D> {
let hmac = match salt {
Some(s) => Hmac::<D>::new_varkey(s).expect("HMAC can take a key of any size"),
None => Hmac::<D>::new(&Default::default()),
};

let default_salt = GenericArray::<u8, D::OutputSize>::default();
let salt = salt.unwrap_or(&default_salt);
let hmac = Hmac::<D>::new_varkey(salt).expect("HMAC can take a key of any size");
HkdfExtract { hmac }
}

Expand Down
14 changes: 12 additions & 2 deletions hkdf/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Sha256>::extract(Option::from(&salt[..]), &ikm[..]);
let salt = if salt.is_empty() {
None
} else {
Some(&salt[..])
};
let (prk, hkdf) = Hkdf::<Sha256>::extract(salt, &ikm[..]);
let mut okm = vec![0u8; t.length];
assert!(hkdf.expand(&info[..], &mut okm).is_ok());

Expand Down Expand Up @@ -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::<Sha1>::extract(Some(&salt[..]), &ikm[..]);
let salt = if salt.is_empty() {
None
} else {
Some(&salt[..])
};
let (prk, hkdf) = Hkdf::<Sha1>::extract(salt, &ikm[..]);
let mut okm = vec![0u8; t.length];
assert!(hkdf.expand(&info[..], &mut okm).is_ok());

Expand Down

0 comments on commit 77c221d

Please sign in to comment.