1use anyhow::Result;
6use std::fs;
7use std::io::{Read, Write};
8
9#[derive(Debug, Clone, Copy)]
11pub enum EncryptionAlgorithm {
12 Aes256,
13 Xor, }
15
16pub struct DataEncryptor {
18 algorithm: EncryptionAlgorithm,
19}
20
21impl DataEncryptor {
22 pub fn new(algorithm: EncryptionAlgorithm) -> Self {
23 Self { algorithm }
24 }
25
26 pub fn encrypt_file(&self, input_path: &str, output_path: &str, key: &[u8]) -> Result<()> {
28 let mut input_data = Vec::new();
29 let mut file = std::fs::File::open(input_path)
30 .with_context(|| format!("Failed to open input file: {}", input_path))?;
31 file.read_to_end(&mut input_data)?;
32
33 let encrypted = match self.algorithm {
34 EncryptionAlgorithm::Aes256 => {
35 self.xor_encrypt(&input_data, key)
38 }
39 EncryptionAlgorithm::Xor => self.xor_encrypt(&input_data, key),
40 }?;
41
42 let mut output_file = std::fs::File::create(output_path)
43 .with_context(|| format!("Failed to create output file: {}", output_path))?;
44 output_file.write_all(&encrypted)?;
45
46 Ok(())
47 }
48
49 pub fn decrypt_file(&self, input_path: &str, output_path: &str, key: &[u8]) -> Result<()> {
51 self.encrypt_file(input_path, output_path, key)
53 }
54
55 pub fn encrypt_data(&self, data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
57 match self.algorithm {
58 EncryptionAlgorithm::Aes256 => self.xor_encrypt(data, key),
59 EncryptionAlgorithm::Xor => self.xor_encrypt(data, key),
60 }
61 }
62
63 pub fn decrypt_data(&self, data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
65 self.encrypt_data(data, key)
67 }
68
69 fn xor_encrypt(&self, data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
70 if key.is_empty() {
71 anyhow::bail!("Encryption key cannot be empty");
72 }
73
74 Ok(data
75 .iter()
76 .enumerate()
77 .map(|(i, &byte)| byte ^ key[i % key.len()])
78 .collect())
79 }
80
81 pub fn load_key_from_file(&self, key_path: &str) -> Result<Vec<u8>> {
83 fs::read(key_path).with_context(|| format!("Failed to read key file: {}", key_path))
84 }
85}
86
87use anyhow::Context;