Skip to main content

xls_rs/
encryption.rs

1//! Data encryption operations
2//!
3//! Provides encryption and decryption capabilities for data files.
4
5use anyhow::Result;
6use std::fs;
7use std::io::{Read, Write};
8
9/// Encryption algorithm
10#[derive(Debug, Clone, Copy)]
11pub enum EncryptionAlgorithm {
12    Aes256,
13    Xor, // Simple XOR for testing (not secure for production)
14}
15
16/// Data encryptor/decryptor
17pub struct DataEncryptor {
18    algorithm: EncryptionAlgorithm,
19}
20
21impl DataEncryptor {
22    pub fn new(algorithm: EncryptionAlgorithm) -> Self {
23        Self { algorithm }
24    }
25
26    /// Encrypt a file
27    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                // For now, use simple XOR as placeholder
36                // In production, use proper AES-256-GCM
37                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    /// Decrypt a file
50    pub fn decrypt_file(&self, input_path: &str, output_path: &str, key: &[u8]) -> Result<()> {
51        // XOR encryption is symmetric
52        self.encrypt_file(input_path, output_path, key)
53    }
54
55    /// Encrypt data in memory
56    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    /// Decrypt data in memory
64    pub fn decrypt_data(&self, data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
65        // XOR is symmetric
66        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    /// Load key from file
82    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;