use core::fmt;
use blowfish::Blowfish;
use blowfish::cipher::{Block, BlockCipherDecrypt, BlockCipherEncrypt, KeyInit};
use tc_block_cipher::{
BlockCipher, BlockCipherInit, BlockError, CipherDirection, InitError, KeyParams,
};
use crate::{ALGO_NAME, BLOCK_BYTES, MAX_KEY_BYTES, MIN_KEY_BYTES};
pub struct BlowfishRustCryptoEngine {
cipher: Option<Blowfish>,
direction: CipherDirection,
}
impl BlowfishRustCryptoEngine {
pub const fn new() -> Self {
Self {
cipher: None,
direction: CipherDirection::Encrypt,
}
}
}
impl Default for BlowfishRustCryptoEngine {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for BlowfishRustCryptoEngine {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(ALGO_NAME)
}
}
impl BlockCipher for BlowfishRustCryptoEngine {
type Error = BlockError;
fn block_size(&self) -> usize {
BLOCK_BYTES
}
fn process_block(&mut self, input: &[u8], output: &mut [u8]) -> Result<usize, BlockError> {
let cipher = self.cipher.as_ref().ok_or(BlockError::NotInitialised)?;
let (Some(input), Some(output)) = (
input
.get(..BLOCK_BYTES)
.and_then(Block::<Blowfish>::slice_as_array),
output
.get_mut(..BLOCK_BYTES)
.and_then(Block::<Blowfish>::slice_as_mut_array),
) else {
return Err(BlockError::BufferTooShort);
};
match self.direction {
CipherDirection::Encrypt => cipher.encrypt_block_b2b(input, output),
CipherDirection::Decrypt => cipher.decrypt_block_b2b(input, output),
}
Ok(BLOCK_BYTES)
}
}
impl<P: KeyParams + ?Sized> BlockCipherInit<P> for BlowfishRustCryptoEngine {
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 cipher =
Blowfish::new_from_slice(key).map_err(|_| InitError::InvalidKeyLength(key.len()))?;
self.cipher = Some(cipher);
self.direction = direction;
Ok(())
}
}