Skip to main content

larastvel_core/encryption/
mod.rs

1use aes_gcm::{
2    aead::{Aead, KeyInit, OsRng},
3    Aes256Gcm, Nonce,
4};
5use rand::RngCore;
6
7const NONCE_SIZE: usize = 12;
8const KEY_SIZE: usize = 32;
9
10#[derive(Debug, thiserror::Error)]
11pub enum EncryptError {
12    #[error("Encryption failed: {0}")]
13    EncryptionFailed(String),
14    #[error("Decryption failed: {0}")]
15    DecryptionFailed(String),
16    #[error("Invalid key: {0}")]
17    InvalidKey(String),
18}
19
20pub struct Encrypter {
21    cipher: Aes256Gcm,
22}
23
24impl Encrypter {
25    pub fn new(key: &[u8]) -> Result<Self, EncryptError> {
26        if key.len() != KEY_SIZE {
27            return Err(EncryptError::InvalidKey(format!(
28                "key must be {} bytes, got {}",
29                KEY_SIZE,
30                key.len()
31            )));
32        }
33        let key_arr: &[u8; KEY_SIZE] = key
34            .try_into()
35            .map_err(|_| EncryptError::InvalidKey("key conversion failed".to_string()))?;
36        let cipher = Aes256Gcm::new_from_slice(key_arr)
37            .map_err(|e| EncryptError::InvalidKey(e.to_string()))?;
38        Ok(Self { cipher })
39    }
40
41    pub fn encrypt(&self, plaintext: &str) -> Result<String, EncryptError> {
42        let mut nonce_bytes = [0u8; NONCE_SIZE];
43        OsRng.fill_bytes(&mut nonce_bytes);
44        let nonce = Nonce::from_slice(&nonce_bytes);
45
46        let ciphertext = self
47            .cipher
48            .encrypt(nonce, plaintext.as_bytes())
49            .map_err(|e| EncryptError::EncryptionFailed(e.to_string()))?;
50
51        let mut payload = Vec::with_capacity(NONCE_SIZE + ciphertext.len());
52        payload.extend_from_slice(&nonce_bytes);
53        payload.extend_from_slice(&ciphertext);
54
55        Ok(base64::Engine::encode(
56            &base64::engine::general_purpose::STANDARD,
57            payload,
58        ))
59    }
60
61    pub fn decrypt(&self, payload_b64: &str) -> Result<String, EncryptError> {
62        let payload =
63            base64::Engine::decode(&base64::engine::general_purpose::STANDARD, payload_b64)
64                .map_err(|e| EncryptError::DecryptionFailed(format!("invalid base64: {}", e)))?;
65
66        if payload.len() < NONCE_SIZE {
67            return Err(EncryptError::DecryptionFailed(
68                "payload too short".to_string(),
69            ));
70        }
71
72        let (nonce_bytes, ciphertext) = payload.split_at(NONCE_SIZE);
73        let nonce = Nonce::from_slice(nonce_bytes);
74
75        let plaintext = self
76            .cipher
77            .decrypt(nonce, ciphertext)
78            .map_err(|e| EncryptError::DecryptionFailed(e.to_string()))?;
79
80        String::from_utf8(plaintext)
81            .map_err(|e| EncryptError::DecryptionFailed(format!("invalid utf-8: {}", e)))
82    }
83
84    pub fn generate_key() -> [u8; KEY_SIZE] {
85        let mut key = [0u8; KEY_SIZE];
86        OsRng.fill_bytes(&mut key);
87        key
88    }
89}
90
91pub fn generate_key() -> String {
92    let key = Encrypter::generate_key();
93    base64::Engine::encode(&base64::engine::general_purpose::STANDARD, key)
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    fn test_key() -> Vec<u8> {
101        vec![
102            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
103            0xee, 0xff, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb,
104            0xcc, 0xdd, 0xee, 0xff,
105        ]
106    }
107
108    #[test]
109    fn test_encrypt_decrypt() {
110        let encrypter = Encrypter::new(&test_key()).unwrap();
111        let ciphertext = encrypter.encrypt("hello world").unwrap();
112        let plaintext = encrypter.decrypt(&ciphertext).unwrap();
113        assert_eq!(plaintext, "hello world");
114    }
115
116    #[test]
117    fn test_encrypt_empty_string() {
118        let encrypter = Encrypter::new(&test_key()).unwrap();
119        let ciphertext = encrypter.encrypt("").unwrap();
120        let plaintext = encrypter.decrypt(&ciphertext).unwrap();
121        assert_eq!(plaintext, "");
122    }
123
124    #[test]
125    fn test_encrypt_unicode() {
126        let encrypter = Encrypter::new(&test_key()).unwrap();
127        let ciphertext = encrypter.encrypt("héllo wörld 🎉").unwrap();
128        let plaintext = encrypter.decrypt(&ciphertext).unwrap();
129        assert_eq!(plaintext, "héllo wörld 🎉");
130    }
131
132    #[test]
133    fn test_encrypt_unique_nonces() {
134        let encrypter = Encrypter::new(&test_key()).unwrap();
135        let a = encrypter.encrypt("same").unwrap();
136        let b = encrypter.encrypt("same").unwrap();
137        assert_ne!(a, b);
138    }
139
140    #[test]
141    fn test_encrypt_decrypt_long_string() {
142        let encrypter = Encrypter::new(&test_key()).unwrap();
143        let long = "a".repeat(10_000);
144        let ciphertext = encrypter.encrypt(&long).unwrap();
145        let plaintext = encrypter.decrypt(&ciphertext).unwrap();
146        assert_eq!(plaintext, long);
147    }
148
149    #[test]
150    fn test_decrypt_invalid_base64() {
151        let encrypter = Encrypter::new(&test_key()).unwrap();
152        let result = encrypter.decrypt("!!!invalid-base64!!!");
153        assert!(result.is_err());
154    }
155
156    #[test]
157    fn test_decrypt_truncated_payload() {
158        let encrypter = Encrypter::new(&test_key()).unwrap();
159        let result = encrypter.decrypt("dGVzdA==");
160        assert!(result.is_err());
161    }
162
163    #[test]
164    fn test_encrypt_wrong_key() {
165        let encrypter_a = Encrypter::new(&test_key()).unwrap();
166
167        let mut wrong_key = test_key();
168        wrong_key[0] = 0xff;
169        let encrypter_b = Encrypter::new(&wrong_key).unwrap();
170
171        let ciphertext = encrypter_a.encrypt("secret").unwrap();
172        let result = encrypter_b.decrypt(&ciphertext);
173        assert!(result.is_err());
174    }
175
176    #[test]
177    fn test_invalid_key_size() {
178        let result = Encrypter::new(&[0u8; 16]);
179        assert!(result.is_err());
180    }
181
182    #[test]
183    fn test_generate_key() {
184        let key1 = generate_key();
185        let key2 = generate_key();
186        assert_ne!(key1, key2);
187        let decoded =
188            base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &key1).unwrap();
189        assert_eq!(decoded.len(), 32);
190    }
191}