refactor(des): use InputBlock trait

This commit is contained in:
2025-11-04 10:03:20 +02:00
parent 211a7cefe6
commit db53ae2ee7
16 changed files with 180 additions and 199 deletions

View File

@@ -1,6 +1,7 @@
use std::num::ParseIntError;
use thiserror::Error;
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum CipherError {
/// Invalid key size for the cipher
#[error("Invalid key size: expected {expected} bytes, got {actual}")]
@@ -27,3 +28,33 @@ impl CipherError {
/// Type alias for clean Result types
pub type CipherResult<T> = core::result::Result<T, CipherError>;
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum BlockError {
/// Input data is empty
#[error("Inputed block is empty")]
EmptyBlock,
/// Parse error
#[error("Error parsing block")]
ParseError(#[from] ParseIntError),
/// Byte size length
#[error("Invalid byte string length: expected no more than 8, found {0}")]
InvalidByteStringLength(usize),
/// String to int conversion error
#[error("String-to-{typ} conversion error: {err}")]
ConversionError { typ: String, err: String },
}
impl BlockError {
#[inline]
#[must_use]
pub fn conversion_error(typ: &str, err: &str) -> Self {
Self::ConversionError {
typ: typ.into(),
err: err.into(),
}
}
}

View File

@@ -3,7 +3,7 @@ mod traits;
mod types;
pub use {
error::{CipherError, CipherResult},
traits::BlockCipher,
types::{CipherAction, CipherOutput},
error::{BlockError, CipherError, CipherResult},
traits::{BlockCipher, BlockParser, InputBlock},
types::{CipherAction, Output},
};

View File

@@ -1,4 +1,4 @@
use crate::{CipherAction, CipherError, CipherOutput, CipherResult};
use crate::{CipherAction, CipherError, CipherResult, Output};
/// Generic block cipher trait.
///
@@ -15,7 +15,7 @@ pub trait BlockCipher: Sized {
/// # Errors
///
/// Returns `CipherError` if the transformation fails.
fn transform_impl(&self, block: &[u8], action: CipherAction) -> CipherResult<CipherOutput>;
fn transform_impl(&self, block: &[u8], action: CipherAction) -> CipherResult<Output>;
/// Transforms a block with validation.
///
@@ -25,7 +25,7 @@ pub trait BlockCipher: Sized {
/// # Errors
///
/// Returns `CipherError::InvalidBlockSize` if `block.len() != BLOCK_SIZE`.
fn transform(&self, block: &[u8], action: CipherAction) -> CipherResult<CipherOutput> {
fn transform(&self, block: &[u8], action: CipherAction) -> CipherResult<Output> {
if block.len() != Self::BLOCK_SIZE {
return Err(CipherError::invalid_block_size(
Self::BLOCK_SIZE,
@@ -40,7 +40,7 @@ pub trait BlockCipher: Sized {
/// # Errors
///
/// Returns `CipherError::InvalidBlockSize` if the plaintext is not exactly `BLOCK_SIZE` bytes.
fn encrypt(&self, plaintext: &[u8]) -> CipherResult<CipherOutput> {
fn encrypt(&self, plaintext: &[u8]) -> CipherResult<Output> {
self.transform(plaintext, CipherAction::Encrypt)
}
@@ -49,7 +49,7 @@ pub trait BlockCipher: Sized {
/// # Errors
///
/// Returns `CipherError::InvalidBlockSize` if the plaintext is not exactly `BLOCK_SIZE` bytes.
fn decrypt(&self, ciphertext: &[u8]) -> CipherResult<CipherOutput> {
fn decrypt(&self, ciphertext: &[u8]) -> CipherResult<Output> {
self.transform(ciphertext, CipherAction::Decrypt)
}
}

View File

@@ -0,0 +1,24 @@
use std::ops::{Deref, DerefMut};
pub trait InputBlock: Sized {
const BLOCK_SIZE: usize;
fn as_bytes(&self) -> &[u8];
fn as_bytes_mut(&mut self) -> &mut [u8];
}
#[derive(Debug, Clone)]
pub struct BlockParser<T: InputBlock>(pub T);
impl<T: InputBlock> Deref for BlockParser<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T: InputBlock> DerefMut for BlockParser<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}

View File

@@ -0,0 +1,5 @@
mod block_cipher;
mod input_block;
pub use block_cipher::BlockCipher;
pub use input_block::{BlockParser, InputBlock};

View File

@@ -0,0 +1,9 @@
mod output;
pub use output::Output;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CipherAction {
Encrypt,
Decrypt,
}

View File

@@ -4,16 +4,10 @@ use std::{
str::from_utf8,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CipherAction {
Encrypt,
Decrypt,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CipherOutput(Vec<u8>);
pub struct Output(Vec<u8>);
impl CipherOutput {
impl Output {
#[inline]
#[must_use]
pub fn new(value: &[u8]) -> Self {
@@ -21,7 +15,7 @@ impl CipherOutput {
}
}
impl UpperHex for CipherOutput {
impl UpperHex for Output {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for byte in &self.0 {
write!(f, "{byte:02X}")?;
@@ -30,7 +24,7 @@ impl UpperHex for CipherOutput {
}
}
impl LowerHex for CipherOutput {
impl LowerHex for Output {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for byte in &self.0 {
write!(f, "{byte:02x}")?;
@@ -39,7 +33,7 @@ impl LowerHex for CipherOutput {
}
}
impl Octal for CipherOutput {
impl Octal for Output {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for byte in &self.0 {
write!(f, "{byte:03o}")?;
@@ -48,7 +42,7 @@ impl Octal for CipherOutput {
}
}
impl Binary for CipherOutput {
impl Binary for Output {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for byte in &self.0 {
write!(f, "{byte:08b}")?;
@@ -57,7 +51,7 @@ impl Binary for CipherOutput {
}
}
impl Display for CipherOutput {
impl Display for Output {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match from_utf8(&self.0) {
Ok(s) => f.write_str(s),
@@ -66,14 +60,14 @@ impl Display for CipherOutput {
}
}
impl Deref for CipherOutput {
impl Deref for Output {
type Target = Vec<u8>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> From<T> for CipherOutput
impl<T> From<T> for Output
where
T: Into<Vec<u8>>,
{