use super::aead12::RecordCrypter12;
#[cfg(feature = "tls-legacy")]
use super::cbc_rec::CbcRecordCrypter;
use crate::tls::{ContentType, Error, ProtocolVersion};
use alloc::boxed::Box;
use alloc::vec::Vec;
pub(crate) enum RecordProtection {
Aead(Box<RecordCrypter12>),
#[cfg(feature = "tls-legacy")]
Cbc(Box<CbcRecordCrypter>),
}
impl RecordProtection {
pub(crate) fn encrypt(
&mut self,
ct: ContentType,
#[cfg_attr(not(feature = "tls-legacy"), allow(unused_variables))] version: ProtocolVersion,
payload: &[u8],
) -> Result<Vec<u8>, Error> {
match self {
RecordProtection::Aead(c) => c.encrypt(ct, payload),
#[cfg(feature = "tls-legacy")]
RecordProtection::Cbc(c) => Ok(c.encrypt(ct, version, payload)),
}
}
pub(crate) fn decrypt(
&mut self,
record_header: &[u8; 5],
fragment: &[u8],
) -> Result<(ContentType, Vec<u8>), Error> {
match self {
RecordProtection::Aead(c) => c.decrypt(record_header, fragment),
#[cfg(feature = "tls-legacy")]
RecordProtection::Cbc(c) => {
let ct = ContentType::from_u8(record_header[0]);
let version = ProtocolVersion::from_u16(u16::from_be_bytes([
record_header[1],
record_header[2],
]));
let plain = c.decrypt(ct, version, fragment)?;
Ok((ct, plain))
}
}
}
}
impl From<RecordCrypter12> for RecordProtection {
fn from(c: RecordCrypter12) -> Self {
RecordProtection::Aead(Box::new(c))
}
}
#[cfg(feature = "tls-legacy")]
impl From<CbcRecordCrypter> for RecordProtection {
fn from(c: CbcRecordCrypter) -> Self {
RecordProtection::Cbc(Box::new(c))
}
}