use core::fmt;
use tc_block_cipher::{
BlockCipher, BlockCipherInit, BlockError, CipherDirection, InitError, KeyParams,
};
use tc_zeroize::Zeroize;
use super::{ALGO_NAME, BLOCK_BYTES, KEY_BYTES, cipher};
pub struct Cast6Engine {
schedule: cipher::Cast6KeySchedule,
for_encryption: bool,
initialised: bool,
}
impl Cast6Engine {
pub const fn new() -> Self {
Self {
schedule: cipher::Cast6KeySchedule::new(),
for_encryption: false,
initialised: false,
}
}
}
impl Default for Cast6Engine {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for Cast6Engine {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(ALGO_NAME)
}
}
impl Drop for Cast6Engine {
fn drop(&mut self) {
self.schedule.zeroize();
}
}
impl BlockCipher for Cast6Engine {
type Error = BlockError;
fn block_size(&self) -> usize {
BLOCK_BYTES
}
fn process_block(&mut self, input: &[u8], output: &mut [u8]) -> Result<usize, BlockError> {
if !self.initialised {
return Err(BlockError::NotInitialised);
}
if input.len() < BLOCK_BYTES || output.len() < BLOCK_BYTES {
return Err(BlockError::BufferTooShort);
}
let input: &[u8; BLOCK_BYTES] = input[..BLOCK_BYTES].try_into().unwrap();
let output: &mut [u8; BLOCK_BYTES] = (&mut output[..BLOCK_BYTES]).try_into().unwrap();
if self.for_encryption {
self.schedule.encrypt_block(input, output);
} else {
self.schedule.decrypt_block(input, output);
}
Ok(BLOCK_BYTES)
}
}
impl<P: KeyParams + ?Sized> BlockCipherInit<P> for Cast6Engine {
type Error = InitError;
fn init(&mut self, direction: CipherDirection, params: &P) -> Result<(), InitError> {
let key = params.key();
if !KEY_BYTES.contains(&key.len()) {
return Err(InitError::InvalidKeyLength(key.len()));
}
self.schedule.set_key(key);
self.for_encryption = direction == CipherDirection::Encrypt;
self.initialised = true;
Ok(())
}
}