Skip to main content

oxirs_chat/security/
encryption.rs

1//! Encryption utilities for secure credential storage
2//!
3//! Uses AES-256-GCM for authenticated encryption, which is already
4//! available in the workspace via the `aes-gcm` crate.
5
6use aes_gcm::{
7    aead::{Aead, KeyInit},
8    Aes256Gcm, Key, Nonce,
9};
10use anyhow::{anyhow, Result};
11use serde::{Deserialize, Serialize};
12
13/// Encryption configuration
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct EncryptionConfig {
16    pub algorithm: EncryptionAlgorithm,
17    pub key_derivation: KeyDerivation,
18}
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub enum EncryptionAlgorithm {
22    AES256GCM,
23    ChaCha20Poly1305,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub enum KeyDerivation {
28    PBKDF2,
29    Argon2,
30}
31
32impl Default for EncryptionConfig {
33    fn default() -> Self {
34        Self {
35            algorithm: EncryptionAlgorithm::AES256GCM,
36            key_derivation: KeyDerivation::Argon2,
37        }
38    }
39}
40
41/// Encryptor for credential protection using AES-256-GCM
42pub struct Encryptor {
43    key: Vec<u8>,
44    config: EncryptionConfig,
45}
46
47impl Encryptor {
48    /// Create new encryptor with random key
49    pub fn new() -> Result<Self> {
50        use scirs2_core::random::Random;
51
52        let mut rng = Random::default();
53        let key: Vec<u8> = (0..32).map(|_| rng.gen_range(0u8..=255u8)).collect();
54
55        Ok(Self {
56            key,
57            config: EncryptionConfig::default(),
58        })
59    }
60
61    /// Create encryptor with specific key (must be 32 bytes)
62    pub fn with_key(key: Vec<u8>) -> Result<Self> {
63        if key.len() != 32 {
64            return Err(anyhow!("Key must be 32 bytes for AES-256-GCM"));
65        }
66
67        Ok(Self {
68            key,
69            config: EncryptionConfig::default(),
70        })
71    }
72
73    /// Encrypt data using AES-256-GCM
74    ///
75    /// Returns the ciphertext with the 12-byte nonce prepended.
76    pub fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>> {
77        let key = <&Key<Aes256Gcm>>::try_from(&self.key[..])
78            .map_err(|_| anyhow!("Invalid key length for AES-256-GCM"))?;
79        let cipher = Aes256Gcm::new(key);
80
81        // Generate random 12-byte nonce
82        use scirs2_core::random::Random;
83        let mut rng = Random::default();
84        let nonce_bytes: Vec<u8> = (0..12).map(|_| rng.gen_range(0u8..=255u8)).collect();
85        let nonce =
86            <&Nonce<_>>::try_from(&nonce_bytes[..]).map_err(|_| anyhow!("Invalid nonce length"))?;
87
88        // Encrypt
89        let ciphertext = cipher
90            .encrypt(nonce, data)
91            .map_err(|e| anyhow!("AES-256-GCM encryption failed: {}", e))?;
92
93        // Prepend nonce to ciphertext
94        let mut result = nonce_bytes;
95        result.extend_from_slice(&ciphertext);
96
97        Ok(result)
98    }
99
100    /// Decrypt data using AES-256-GCM
101    ///
102    /// Expects the nonce (12 bytes) prepended to the ciphertext.
103    pub fn decrypt(&self, encrypted_data: &[u8]) -> Result<Vec<u8>> {
104        if encrypted_data.len() < 12 {
105            return Err(anyhow!(
106                "Invalid encrypted data: too short (need at least 12 bytes for nonce)"
107            ));
108        }
109
110        let key = <&Key<Aes256Gcm>>::try_from(&self.key[..])
111            .map_err(|_| anyhow!("Invalid key length for AES-256-GCM"))?;
112        let cipher = Aes256Gcm::new(key);
113
114        // Extract 12-byte nonce
115        let (nonce_bytes, ciphertext) = encrypted_data.split_at(12);
116        let nonce =
117            <&Nonce<_>>::try_from(nonce_bytes).map_err(|_| anyhow!("Invalid nonce length"))?;
118
119        // Decrypt
120        let plaintext = cipher
121            .decrypt(nonce, ciphertext)
122            .map_err(|e| anyhow!("AES-256-GCM decryption failed: {}", e))?;
123
124        Ok(plaintext)
125    }
126
127    /// Securely zero memory on key material
128    pub fn zeroize_key(&mut self) {
129        self.key.iter_mut().for_each(|b| *b = 0);
130    }
131
132    /// Get the encryption algorithm in use
133    pub fn algorithm(&self) -> &EncryptionAlgorithm {
134        &self.config.algorithm
135    }
136}
137
138impl Default for Encryptor {
139    fn default() -> Self {
140        Self::new().expect("Failed to create default Encryptor")
141    }
142}
143
144impl Drop for Encryptor {
145    fn drop(&mut self) {
146        self.zeroize_key();
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn test_encryption_decryption() {
156        let encryptor = Encryptor::new().expect("create encryptor");
157        let plaintext = b"sensitive API key: sk-test-123";
158
159        let encrypted = encryptor.encrypt(plaintext).expect("encrypt");
160        // Ciphertext (after nonce) should be different from plaintext
161        assert_ne!(&encrypted[12..], plaintext);
162
163        let decrypted = encryptor.decrypt(&encrypted).expect("decrypt");
164        assert_eq!(decrypted, plaintext);
165    }
166
167    #[test]
168    fn test_different_keys_produce_different_ciphertext() {
169        let encryptor1 = Encryptor::new().expect("create encryptor 1");
170        let encryptor2 = Encryptor::new().expect("create encryptor 2");
171
172        let plaintext = b"test data";
173        let encrypted1 = encryptor1.encrypt(plaintext).expect("encrypt 1");
174        let encrypted2 = encryptor2.encrypt(plaintext).expect("encrypt 2");
175
176        // Different keys should produce different ciphertexts
177        assert_ne!(encrypted1, encrypted2);
178    }
179
180    #[test]
181    fn test_invalid_key_length() {
182        let result = Encryptor::with_key(vec![0; 16]);
183        assert!(result.is_err());
184    }
185
186    #[test]
187    fn test_decrypt_invalid_data_too_short() {
188        let encryptor = Encryptor::new().expect("create encryptor");
189        let result = encryptor.decrypt(&[0; 5]);
190        assert!(result.is_err());
191    }
192
193    #[test]
194    fn test_decrypt_tampered_data() {
195        let encryptor = Encryptor::new().expect("create encryptor");
196        let plaintext = b"hello world";
197        let mut encrypted = encryptor.encrypt(plaintext).expect("encrypt");
198        // Tamper with ciphertext (after nonce)
199        if let Some(byte) = encrypted.get_mut(15) {
200            *byte ^= 0xFF;
201        }
202        let result = encryptor.decrypt(&encrypted);
203        assert!(
204            result.is_err(),
205            "Tampered ciphertext should fail decryption"
206        );
207    }
208
209    #[test]
210    fn test_encrypt_empty_data() {
211        let encryptor = Encryptor::new().expect("create encryptor");
212        let plaintext: &[u8] = b"";
213
214        let encrypted = encryptor.encrypt(plaintext).expect("encrypt empty");
215        let decrypted = encryptor.decrypt(&encrypted).expect("decrypt empty");
216        assert_eq!(decrypted, plaintext);
217    }
218
219    #[test]
220    fn test_32_byte_key() {
221        let key = vec![0x42u8; 32];
222        let encryptor = Encryptor::with_key(key).expect("create with key");
223        let plaintext = b"test with fixed key";
224        let encrypted = encryptor.encrypt(plaintext).expect("encrypt");
225        let decrypted = encryptor.decrypt(&encrypted).expect("decrypt");
226        assert_eq!(decrypted, plaintext);
227    }
228}