use anyhow::Result;
use std::fs;
use std::io::{Read, Write};
#[derive(Debug, Clone, Copy)]
pub enum EncryptionAlgorithm {
Aes256,
Xor, }
pub struct DataEncryptor {
algorithm: EncryptionAlgorithm,
}
impl DataEncryptor {
pub fn new(algorithm: EncryptionAlgorithm) -> Self {
Self { algorithm }
}
pub fn encrypt_file(&self, input_path: &str, output_path: &str, key: &[u8]) -> Result<()> {
let mut input_data = Vec::new();
let mut file = std::fs::File::open(input_path)
.with_context(|| format!("Failed to open input file: {}", input_path))?;
file.read_to_end(&mut input_data)?;
let encrypted = match self.algorithm {
EncryptionAlgorithm::Aes256 => {
self.xor_encrypt(&input_data, key)
}
EncryptionAlgorithm::Xor => self.xor_encrypt(&input_data, key),
}?;
let mut output_file = std::fs::File::create(output_path)
.with_context(|| format!("Failed to create output file: {}", output_path))?;
output_file.write_all(&encrypted)?;
Ok(())
}
pub fn decrypt_file(&self, input_path: &str, output_path: &str, key: &[u8]) -> Result<()> {
self.encrypt_file(input_path, output_path, key)
}
pub fn encrypt_data(&self, data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
match self.algorithm {
EncryptionAlgorithm::Aes256 => self.xor_encrypt(data, key),
EncryptionAlgorithm::Xor => self.xor_encrypt(data, key),
}
}
pub fn decrypt_data(&self, data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
self.encrypt_data(data, key)
}
fn xor_encrypt(&self, data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
if key.is_empty() {
anyhow::bail!("Encryption key cannot be empty");
}
Ok(data
.iter()
.enumerate()
.map(|(i, &byte)| byte ^ key[i % key.len()])
.collect())
}
pub fn load_key_from_file(&self, key_path: &str) -> Result<Vec<u8>> {
fs::read(key_path).with_context(|| format!("Failed to read key file: {}", key_path))
}
}
use anyhow::Context;