Skip to main content

fetchium_core/privacy/
encryption.rs

1//! AES-256-GCM cache encryption (PRD §36.3).
2//!
3//! Key derivation: Argon2id with a fixed salt (uniqueness via per-message nonces).
4//! Nonce generation: UUID v4 bytes (CSPRNG-backed via the `uuid` crate).
5
6use crate::error::FetchiumError;
7use aes_gcm::{
8    aead::{Aead, KeyInit},
9    Aes256Gcm, Key, Nonce,
10};
11
12const NONCE_LEN: usize = 12;
13
14/// Fixed 16-byte salt for deterministic key derivation.
15/// Uniqueness is ensured by per-message random nonces, not the salt.
16const KDF_SALT: &[u8] = b"fetchiumcache__";
17
18/// AES-256-GCM encryption engine, keyed from a passphrase via Argon2id.
19pub struct CacheEncryption {
20    cipher: Aes256Gcm,
21}
22
23impl CacheEncryption {
24    /// Derive a 256-bit key from `passphrase` using Argon2id.
25    pub fn new(passphrase: &str) -> Result<Self, FetchiumError> {
26        let mut key_bytes = [0u8; 32];
27        argon2::Argon2::default()
28            .hash_password_into(passphrase.as_bytes(), KDF_SALT, &mut key_bytes)
29            .map_err(|e| FetchiumError::Internal(format!("argon2 key derivation error: {e}")))?;
30
31        let key = Key::<Aes256Gcm>::from_slice(&key_bytes);
32        let cipher = Aes256Gcm::new(key);
33        Ok(Self { cipher })
34    }
35
36    /// Encrypt `data` with a random nonce. Returns `nonce || ciphertext`.
37    pub fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>, FetchiumError> {
38        // Generate a 12-byte nonce from a UUID v4 (CSPRNG-backed).
39        let uuid_bytes = uuid::Uuid::new_v4().into_bytes();
40        let nonce_bytes: [u8; NONCE_LEN] = uuid_bytes[..NONCE_LEN]
41            .try_into()
42            .expect("uuid is 16 bytes, nonce is 12");
43
44        let nonce = Nonce::from_slice(&nonce_bytes);
45        let ciphertext = self
46            .cipher
47            .encrypt(nonce, data)
48            .map_err(|e| FetchiumError::Internal(format!("encrypt error: {e}")))?;
49
50        let mut out = nonce_bytes.to_vec();
51        out.extend(ciphertext);
52        Ok(out)
53    }
54
55    /// Decrypt `data` (format: `nonce || ciphertext`).
56    pub fn decrypt(&self, data: &[u8]) -> Result<Vec<u8>, FetchiumError> {
57        if data.len() <= NONCE_LEN {
58            return Err(FetchiumError::Internal("Data too short to decrypt".into()));
59        }
60        let (nonce_bytes, ciphertext) = data.split_at(NONCE_LEN);
61        let nonce = Nonce::from_slice(nonce_bytes);
62        self.cipher
63            .decrypt(nonce, ciphertext)
64            .map_err(|e| FetchiumError::Internal(format!("decrypt error: {e}")))
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    #[test]
73    fn roundtrip_encrypt_decrypt() {
74        let enc = CacheEncryption::new("test-passphrase").unwrap();
75        let plaintext = b"hello, world!";
76        let encrypted = enc.encrypt(plaintext).unwrap();
77        let decrypted = enc.decrypt(&encrypted).unwrap();
78        assert_eq!(decrypted, plaintext);
79    }
80
81    #[test]
82    fn different_passphrases_fail_to_decrypt() {
83        let enc1 = CacheEncryption::new("passphrase-A").unwrap();
84        let enc2 = CacheEncryption::new("passphrase-B").unwrap();
85        let encrypted = enc1.encrypt(b"secret").unwrap();
86        assert!(enc2.decrypt(&encrypted).is_err());
87    }
88}