fetchium_core/privacy/
encryption.rs1use crate::error::FetchiumError;
7use aes_gcm::{
8 aead::{Aead, KeyInit},
9 Aes256Gcm, Key, Nonce,
10};
11
12const NONCE_LEN: usize = 12;
13
14const KDF_SALT: &[u8] = b"fetchiumcache__";
17
18pub struct CacheEncryption {
20 cipher: Aes256Gcm,
21}
22
23impl CacheEncryption {
24 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 pub fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>, FetchiumError> {
38 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 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}