use core::fmt;
use tc_block_cipher::{
BlockCipher, BlockCipherInit, BlockError, CipherDirection, InitError, KeyParams,
};
use tc_zeroize::Zeroize;
use super::cipher;
use crate::{ALGO_NAME, BLOCK_BYTES, MAX_KEY_BYTES, MIN_KEY_BYTES};
pub struct BlowfishTableEngine {
state: cipher::BlowfishState,
for_encryption: bool,
initialised: bool,
}
impl BlowfishTableEngine {
pub const fn new() -> Self {
Self {
state: cipher::BlowfishState::new(),
for_encryption: false,
initialised: false,
}
}
}
impl Default for BlowfishTableEngine {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for BlowfishTableEngine {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(ALGO_NAME)
}
}
impl Drop for BlowfishTableEngine {
fn drop(&mut self) {
self.state.zeroize();
}
}
impl BlockCipher for BlowfishTableEngine {
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 {
self.state.encrypt_block(input, output);
} else {
self.state.decrypt_block(input, output);
}
Ok(BLOCK_BYTES)
}
}
impl<P: KeyParams + ?Sized> BlockCipherInit<P> for BlowfishTableEngine {
type Error = InitError;
fn init(&mut self, direction: CipherDirection, params: &P) -> Result<(), InitError> {
let key = params.key();
if !(MIN_KEY_BYTES..=MAX_KEY_BYTES).contains(&key.len()) {
return Err(InitError::InvalidKeyLength(key.len()));
}
let for_encryption = direction == CipherDirection::Encrypt;
self.state.zeroize();
self.state.expand_key(key);
self.for_encryption = for_encryption;
self.initialised = true;
Ok(())
}
}