use alloc::boxed::Box;
use pki_types::FipsStatus;
use super::hmac;
use super::kx::ActiveKeyExchange;
use crate::enums::ProtocolVersion;
use crate::error::Error;
#[expect(clippy::exhaustive_structs)]
pub struct PrfUsingHmac<'a>(pub &'a dyn hmac::Hmac);
impl Prf for PrfUsingHmac<'_> {
fn for_key_exchange(
&self,
output: &mut [u8; 48],
kx: Box<dyn ActiveKeyExchange>,
peer_pub_key: &[u8],
label: &[u8],
seed: &[u8],
) -> Result<(), Error> {
prf(
output,
self.0
.with_key(
kx.complete_for_tls_version(peer_pub_key, ProtocolVersion::TLSv1_2)?
.secret_bytes(),
)
.as_ref(),
label,
seed,
);
Ok(())
}
fn new_secret(&self, secret: &[u8; 48]) -> Box<dyn PrfSecret> {
Box::new(PrfSecretUsingHmac(self.0.with_key(secret)))
}
}
struct PrfSecretUsingHmac(Box<dyn hmac::Key>);
impl PrfSecret for PrfSecretUsingHmac {
fn prf(&self, output: &mut [u8], label: &[u8], seed: &[u8]) {
prf(output, &*self.0, label, seed)
}
}
pub trait Prf: Send + Sync {
fn for_key_exchange(
&self,
output: &mut [u8; 48],
kx: Box<dyn ActiveKeyExchange>,
peer_pub_key: &[u8],
label: &[u8],
seed: &[u8],
) -> Result<(), Error>;
fn new_secret(&self, master_secret: &[u8; 48]) -> Box<dyn PrfSecret>;
fn fips(&self) -> FipsStatus {
FipsStatus::Unvalidated
}
}
pub trait PrfSecret: Send + Sync {
fn prf(&self, output: &mut [u8], label: &[u8], seed: &[u8]);
}
#[doc(hidden)]
pub fn prf(out: &mut [u8], hmac_key: &dyn hmac::Key, label: &[u8], seed: &[u8]) {
let mut previous_a: Option<hmac::Tag> = None;
let chunk_size = hmac_key.tag_len();
for chunk in out.chunks_mut(chunk_size) {
let a_i = match previous_a {
None => hmac_key.sign(&[label, seed]),
Some(previous_a) => hmac_key.sign(&[previous_a.as_ref()]),
};
let p_term = hmac_key.sign(&[a_i.as_ref(), label, seed]);
chunk.copy_from_slice(&p_term.as_ref()[..chunk.len()]);
previous_a = Some(a_i);
}
}