use crate::error::Unspecified;
use crate::{digest, hmac};
use aws_lc::{HKDF_expand, HKDF_extract};
use core::fmt;
use std::mem::MaybeUninit;
use zeroize::Zeroize;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Algorithm(hmac::Algorithm);
impl Algorithm {
#[inline]
#[must_use]
pub fn hmac_algorithm(&self) -> hmac::Algorithm {
self.0
}
}
pub static HKDF_SHA1_FOR_LEGACY_USE_ONLY: Algorithm =
Algorithm(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY);
pub static HKDF_SHA256: Algorithm = Algorithm(hmac::HMAC_SHA256);
pub static HKDF_SHA384: Algorithm = Algorithm(hmac::HMAC_SHA384);
pub static HKDF_SHA512: Algorithm = Algorithm(hmac::HMAC_SHA512);
const MAX_HKDF_SALT_LEN: usize = 80;
const MAX_HKDF_INFO_LEN: usize = 80;
const MAX_HKDF_PRK_LEN: usize = digest::MAX_OUTPUT_LEN;
impl KeyType for Algorithm {
fn len(&self) -> usize {
self.0.digest_algorithm().output_len
}
}
pub struct Salt {
algorithm: Algorithm,
key_bytes: [u8; MAX_HKDF_SALT_LEN],
key_len: usize,
}
#[allow(clippy::missing_fields_in_debug)]
impl fmt::Debug for Salt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("hkdf::Salt")
.field("algorithm", &self.algorithm.0)
.finish()
}
}
impl Drop for Salt {
fn drop(&mut self) {
self.key_bytes.zeroize();
}
}
impl Salt {
#[must_use]
pub fn new(algorithm: Algorithm, value: &[u8]) -> Self {
Salt::try_new(algorithm, value).expect("Salt length limit exceeded.")
}
fn try_new(algorithm: Algorithm, value: &[u8]) -> Result<Salt, Unspecified> {
let key_len = value.len();
if key_len > MAX_HKDF_SALT_LEN {
return Err(Unspecified);
}
let mut key_bytes = [0u8; MAX_HKDF_SALT_LEN];
key_bytes[0..key_len].copy_from_slice(value);
Ok(Self {
algorithm,
key_bytes,
key_len,
})
}
#[inline]
#[must_use]
pub fn extract(&self, secret: &[u8]) -> Prk {
Self::try_extract(self, secret).expect("HKDF_extract failed")
}
#[inline]
fn try_extract(&self, secret: &[u8]) -> Result<Prk, Unspecified> {
unsafe {
let mut key_bytes = MaybeUninit::<[u8; MAX_HKDF_PRK_LEN]>::uninit();
let mut key_len = MaybeUninit::<usize>::uninit();
if 1 != HKDF_extract(
key_bytes.as_mut_ptr().cast(),
key_len.as_mut_ptr(),
*digest::match_digest_type(&self.algorithm.0.digest_algorithm().id),
secret.as_ptr(),
secret.len(),
self.key_bytes.as_ptr(),
self.key_len,
) {
return Err(Unspecified);
};
let key_bytes = key_bytes.assume_init();
let key_len = key_len.assume_init();
debug_assert!(key_len <= MAX_HKDF_PRK_LEN);
Ok(Prk {
algorithm: self.algorithm,
key_bytes,
key_len,
})
}
}
#[inline]
#[must_use]
pub fn algorithm(&self) -> Algorithm {
Algorithm(self.algorithm.hmac_algorithm())
}
}
#[allow(clippy::assertions_on_constants)]
const _: () = assert!(MAX_HKDF_PRK_LEN <= MAX_HKDF_SALT_LEN);
impl From<Okm<'_, Algorithm>> for Salt {
fn from(okm: Okm<'_, Algorithm>) -> Self {
let algorithm = okm.prk.algorithm;
let mut key_bytes = [0u8; MAX_HKDF_SALT_LEN];
let key_len = okm.len().len();
okm.fill(&mut key_bytes[..key_len]).unwrap();
Self {
algorithm,
key_bytes,
key_len,
}
}
}
#[allow(clippy::len_without_is_empty)]
pub trait KeyType {
fn len(&self) -> usize;
}
#[derive(Clone)]
pub struct Prk {
algorithm: Algorithm,
key_bytes: [u8; MAX_HKDF_PRK_LEN],
key_len: usize,
}
#[allow(clippy::missing_fields_in_debug)]
impl fmt::Debug for Prk {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("hkdf::Prk")
.field("algorithm", &self.algorithm.0)
.finish()
}
}
impl Drop for Prk {
fn drop(&mut self) {
self.key_bytes.zeroize();
}
}
impl Prk {
#[must_use]
pub fn new_less_safe(algorithm: Algorithm, value: &[u8]) -> Self {
Prk::try_new_less_safe(algorithm, value).expect("Prk length limit exceeded.")
}
fn try_new_less_safe(algorithm: Algorithm, value: &[u8]) -> Result<Prk, Unspecified> {
let key_len = value.len();
if key_len > MAX_HKDF_PRK_LEN {
return Err(Unspecified);
}
let mut key_bytes = [0u8; MAX_HKDF_PRK_LEN];
key_bytes[0..key_len].copy_from_slice(value);
Ok(Self {
algorithm,
key_bytes,
key_len,
})
}
#[inline]
pub fn expand<'a, L: KeyType>(
&'a self,
info: &'a [&'a [u8]],
len: L,
) -> Result<Okm<'a, L>, Unspecified> {
let len_cached = len.len();
if len_cached > 255 * self.algorithm.0.digest_algorithm().output_len {
return Err(Unspecified);
}
let mut info_bytes = [0u8; MAX_HKDF_INFO_LEN];
let mut info_len = 0;
for byte_ary in info {
let new_info_len = info_len + byte_ary.len();
if new_info_len > MAX_HKDF_INFO_LEN {
return Err(Unspecified);
}
info_bytes[info_len..new_info_len].copy_from_slice(byte_ary);
info_len = new_info_len;
}
Ok(Okm {
prk: self,
info_bytes,
info_len,
len,
})
}
}
impl From<Okm<'_, Algorithm>> for Prk {
fn from(okm: Okm<Algorithm>) -> Self {
let algorithm = okm.len;
let key_len = okm.len.len();
let mut key_bytes = [0u8; MAX_HKDF_PRK_LEN];
okm.fill(&mut key_bytes[0..key_len]).unwrap();
Self {
algorithm,
key_bytes,
key_len,
}
}
}
pub struct Okm<'a, L: KeyType> {
prk: &'a Prk,
info_bytes: [u8; MAX_HKDF_INFO_LEN],
info_len: usize,
len: L,
}
impl<'a, L: KeyType> fmt::Debug for Okm<'a, L> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("hkdf::Okm").field("prk", &self.prk).finish()
}
}
impl<'a, L: KeyType> Drop for Okm<'a, L> {
fn drop(&mut self) {
self.info_bytes.zeroize();
}
}
impl<L: KeyType> Okm<'_, L> {
#[inline]
pub fn len(&self) -> &L {
&self.len
}
#[inline]
pub fn fill(self, out: &mut [u8]) -> Result<(), Unspecified> {
if out.len() != self.len.len() {
return Err(Unspecified);
}
unsafe {
if 1 != HKDF_expand(
out.as_mut_ptr(),
out.len(),
*digest::match_digest_type(&self.prk.algorithm.0.digest_algorithm().id),
self.prk.key_bytes.as_ptr(),
self.prk.key_len,
self.info_bytes.as_ptr(),
self.info_len,
) {
return Err(Unspecified);
};
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::hkdf::{Salt, HKDF_SHA256, HKDF_SHA384};
#[test]
fn hkdf_coverage() {
assert_ne!(HKDF_SHA256, HKDF_SHA384);
assert_eq!("Algorithm(Algorithm(SHA256))", format!("{HKDF_SHA256:?}"));
}
#[test]
fn test_debug() {
const SALT: &[u8; 32] = &[
29, 113, 120, 243, 11, 202, 39, 222, 206, 81, 163, 184, 122, 153, 52, 192, 98, 195,
240, 32, 34, 19, 160, 128, 178, 111, 97, 232, 113, 101, 221, 143,
];
const SECRET1: &[u8; 32] = &[
157, 191, 36, 107, 110, 131, 193, 6, 175, 226, 193, 3, 168, 133, 165, 181, 65, 120,
194, 152, 31, 92, 37, 191, 73, 222, 41, 112, 207, 236, 196, 174,
];
const INFO1: &[&[u8]] = &[
&[
2, 130, 61, 83, 192, 248, 63, 60, 211, 73, 169, 66, 101, 160, 196, 212, 250, 113,
],
&[
80, 46, 248, 123, 78, 204, 171, 178, 67, 204, 96, 27, 131, 24,
],
];
let alg = HKDF_SHA256;
let salt = Salt::new(alg, SALT);
let prk = salt.extract(SECRET1);
let okm = prk.expand(INFO1, alg).unwrap();
assert_eq!(
"hkdf::Salt { algorithm: Algorithm(SHA256) }",
format!("{salt:?}")
);
assert_eq!(
"hkdf::Prk { algorithm: Algorithm(SHA256) }",
format!("{prk:?}")
);
assert_eq!(
"hkdf::Okm { prk: hkdf::Prk { algorithm: Algorithm(SHA256) } }",
format!("{okm:?}")
);
}
}