feat(factory): add cipher/algorithm helper functions

This commit is contained in:
2025-11-24 12:02:22 +02:00
parent 051bba33a8
commit 46a47102b9
8 changed files with 120 additions and 41 deletions

View File

@@ -32,13 +32,17 @@ impl Des {
let subkeys = Subkeys::from_key(&key.into());
Self { subkeys }
}
#[inline]
#[must_use]
pub fn from_key(key: impl Into<Key>) -> Self {
Self::new(key)
}
}
impl BlockCipher for Des {
const BLOCK_SIZE: usize = 8;
fn from_key(key: &[u8]) -> Self {
Self::new(key)
fn block_size(&self) -> usize {
8
}
fn transform_impl(
@@ -46,9 +50,10 @@ impl BlockCipher for Des {
block: &[u8],
action: cipher_core::CipherAction,
) -> cipher_core::CipherResult<cipher_core::Output> {
let block_arr: [u8; Self::BLOCK_SIZE] = block
let block_size = self.block_size();
let block_arr: [u8; 8] = block
.try_into()
.map_err(|_| CipherError::invalid_block_size(Self::BLOCK_SIZE, block.len()))?;
.map_err(|_| CipherError::invalid_block_size(block_size, block.len()))?;
let block64 = Block64::from_be_bytes(block_arr);
let permutated_block = ip(block64);

View File

@@ -1,6 +1,8 @@
use std::fmt::Debug;
use zeroize::ZeroizeOnDrop;
use crate::Block64;
/// 64-bit Key for DES
#[derive(ZeroizeOnDrop)]
pub struct Key([u8; 8]);
@@ -36,13 +38,19 @@ impl From<&[u8]> for Key {
let mut bytes = [0; 8];
let len = value.len().min(8);
bytes[..len].copy_from_slice(&value[..len]);
Self(bytes)
bytes.into()
}
}
impl From<u64> for Key {
fn from(key: u64) -> Self {
Self(key.to_be_bytes())
key.to_be_bytes().into()
}
}
impl From<Block64> for Key {
fn from(key: Block64) -> Self {
key.to_be_bytes().into()
}
}