mirror of
https://github.com/kristoferssolo/cipher-workshop.git
synced 2026-02-04 06:42:11 +00:00
feat: add CipherContext struct
This commit is contained in:
32
cipher-factory/src/context.rs
Normal file
32
cipher-factory/src/context.rs
Normal 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user