use alloc::boxed::Box;
use alloc::vec::Vec;
use core::marker::PhantomData;
use rustls::crypto::hmac;
use rustls::crypto::hmac::Tag;
use rustls::crypto::tls13::{self, HkdfExpander, HkdfUsingHmac, OkmBlock, OutputLengthError};
use verified_garbage::hashes::sha256::Sha256;
use verified_garbage::hashes::sha384::Sha384;
use verified_garbage::hmac::{Hmac, HmacHash};
use verified_garbage::kdf::hkdf::{Hkdf as VgHkdf, HkdfHash};
pub(crate) static HKDF_SHA256: Hkdf<Sha256> = Hkdf(PhantomData, &crate::hmac::HMAC_SHA256);
pub(crate) static HKDF_SHA384: Hkdf<Sha384> = Hkdf(PhantomData, &crate::hmac::HMAC_SHA384);
pub(crate) struct Hkdf<H>(PhantomData<fn() -> H>, &'static dyn hmac::Hmac);
impl<H: HkdfHash + HmacHash + Send + Sync + 'static> tls13::Hkdf for Hkdf<H> {
fn extract_from_zero_ikm(&self, salt: Option<&[u8]>) -> Box<dyn HkdfExpander> {
let zeroes = [0u8; Tag::MAX_LEN];
Box::new(Expander(VgHkdf::<H>::new(salt, &zeroes[..H::OUTPUT_SIZE])))
}
fn extract_from_secret(&self, salt: Option<&[u8]>, secret: &[u8]) -> Box<dyn HkdfExpander> {
Box::new(Expander(VgHkdf::<H>::new(salt, secret)))
}
fn expander_for_okm(&self, okm: &OkmBlock) -> Box<dyn HkdfExpander> {
match VgHkdf::<H>::from_prk(okm.as_ref()) {
Ok(prk) => Box::new(Expander(prk)),
Err(_) => HkdfUsingHmac(self.1).expander_for_okm(okm),
}
}
fn hmac_sign(&self, key: &OkmBlock, message: &[u8]) -> Tag {
Tag::new(Hmac::<H>::mac(key.as_ref(), message).as_ref())
}
}
const MAX_LABEL: usize = 2 + 1 + 255 + 1 + 255;
struct Expander<H: HkdfHash>(VgHkdf<H>);
impl<H: HkdfHash> Expander<H> {
fn expand(&self, info: &[&[u8]], output: &mut [u8]) {
let len: usize = info.iter().map(|p| p.len()).sum();
let mut stack = [0u8; MAX_LABEL];
let mut heap = Vec::new();
let buf = if len <= MAX_LABEL {
&mut stack[..len]
} else {
heap.resize(len, 0);
&mut heap[..]
};
let mut at = 0;
for piece in info {
buf[at..at + piece.len()].copy_from_slice(piece);
at += piece.len();
}
self.0
.expand(buf, output)
.expect("the output is at most 255 digests long");
}
}
impl<H: HkdfHash + Send + Sync> HkdfExpander for Expander<H> {
fn expand_slice(&self, info: &[&[u8]], output: &mut [u8]) -> Result<(), OutputLengthError> {
if output.len() > 255 * H::OUTPUT_SIZE {
return Err(OutputLengthError);
}
self.expand(info, output);
Ok(())
}
fn expand_block(&self, info: &[&[u8]]) -> OkmBlock {
let mut block = [0u8; Tag::MAX_LEN];
self.expand(info, &mut block[..H::OUTPUT_SIZE]);
OkmBlock::new(&block[..H::OUTPUT_SIZE])
}
fn hash_len(&self) -> usize {
H::OUTPUT_SIZE
}
}