use core::fmt;
use tc_block_cipher::{
BlockCipher, BlockCipherInit, BlockError, CipherDirection, InitError, KeyParams,
};
use tc_zeroize::Zeroize;
use crate::cipher::WORKING_KEY_WORDS;
use crate::{ALGO_NAME, BLOCK_BYTES, KEY_BYTES, cipher};
pub struct SeedEngine {
working_key: [u32; WORKING_KEY_WORDS],
for_encryption: bool,
initialised: bool,
}
impl SeedEngine {
pub const fn new() -> Self {
Self {
working_key: [0; WORKING_KEY_WORDS],
for_encryption: false,
initialised: false,
}
}
}
impl Default for SeedEngine {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for SeedEngine {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(ALGO_NAME)
}
}
impl Drop for SeedEngine {
fn drop(&mut self) {
self.working_key.zeroize();
}
}
impl BlockCipher for SeedEngine {
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);
}
let (Some(input), Some(output)) = (
input.first_chunk::<BLOCK_BYTES>(),
output.first_chunk_mut::<BLOCK_BYTES>(),
) else {
return Err(BlockError::BufferTooShort);
};
if self.for_encryption {
cipher::encrypt_block(&self.working_key, input, output);
} else {
cipher::decrypt_block(&self.working_key, input, output);
}
Ok(BLOCK_BYTES)
}
}
impl<P: KeyParams + ?Sized> BlockCipherInit<P> for SeedEngine {
type Error = InitError;
fn init(&mut self, direction: CipherDirection, params: &P) -> Result<(), InitError> {
let key = params.key();
let key: &[u8; KEY_BYTES] = key
.try_into()
.map_err(|_| InitError::InvalidKeyLength(key.len()))?;
let for_encryption = direction == CipherDirection::Encrypt;
self.working_key.zeroize();
cipher::create_working_key(key, &mut self.working_key);
self.for_encryption = for_encryption;
self.initialised = true;
Ok(())
}
}