feat: add CipherContext struct

This commit is contained in:
2025-11-26 01:38:11 +02:00
parent 2254ecaf7c
commit 5f22690ef7
4 changed files with 55 additions and 37 deletions

View File

@@ -0,0 +1,32 @@
use crate::{Algorithm, OperationChoice, OutputFormat};
use cipher_core::{BlockCipher, CipherResult};
pub struct CipherContext {
pub algorithm: Algorithm,
pub operation: OperationChoice,
pub key: String,
pub input_text: String,
pub output_format: OutputFormat,
}
impl CipherContext {
pub fn process(&self) -> CipherResult<String> {
let text_bytes = self.algorithm.parse_text(&self.input_text)?;
let cipher = self.algorithm.new_cipher(&self.key)?;
self.execute(cipher.as_ref(), &text_bytes)
}
fn execute(&self, cipher: &dyn BlockCipher, text_bytes: &[u8]) -> CipherResult<String> {
match self.operation {
OperationChoice::Encrypt => {
let ciphertext = cipher.encrypt(text_bytes)?;
Ok(format!("{ciphertext:X}"))
}
OperationChoice::Decrypt => {
let plaintext = cipher.decrypt(text_bytes)?;
let output = self.output_format.to_string(&plaintext);
Ok(output)
}
}
}
}

View File

@@ -1,5 +1,8 @@
mod algorithm;
mod context;
mod operation;
mod output;
pub use {algorithm::Algorithm, operation::OperationChoice, output::OutputFormat};
pub use {
algorithm::Algorithm, context::CipherContext, operation::OperationChoice, output::OutputFormat,
};