Skip to main content

haste_encryption/encryption/
aes.rs

1use crate::{
2    error::EncryptionError,
3    traits::{EncryptionResult, Encryptor},
4};
5use aes_gcm::{
6    Aes256Gcm, Key,
7    aead::{Aead, Generate, KeyInit, Nonce, Payload},
8};
9use haste_fhir_operation_error::OperationOutcomeError;
10
11const KEY_LEN: usize = 32;
12
13/// AES-256-GCM encryption. Output is `nonce || ciphertext`, with a fresh
14/// random nonce generated for every `encrypt` call.
15pub struct AesGcmEncryptor {
16    cipher: Aes256Gcm,
17}
18
19impl AesGcmEncryptor {
20    /// Creates a new AES-256-GCM cipher from the provided key.
21    ///
22    /// # Errors
23    ///
24    /// Returns [`OperationOutcomeError`] if `key` is not exactly `KEY_LEN` bytes
25    /// long.
26    pub fn new(key: &[u8]) -> Result<Self, OperationOutcomeError> {
27        let key_array = Key::<Aes256Gcm>::try_from(key)
28            .map_err(|_| EncryptionError::InvalidKeyLength(KEY_LEN, key.len()))?;
29
30        Ok(Self {
31            cipher: Aes256Gcm::new(&key_array),
32        })
33    }
34}
35
36impl Encryptor for AesGcmEncryptor {
37    fn encrypt_with_aad(
38        &self,
39        plaintext: &[u8],
40        aad: &[u8],
41    ) -> Result<EncryptionResult, OperationOutcomeError> {
42        let nonce = Nonce::<Aes256Gcm>::generate();
43
44        let ciphertext = self
45            .cipher
46            .encrypt(
47                &nonce,
48                Payload {
49                    msg: plaintext,
50                    aad,
51                },
52            )
53            .map_err(|e| EncryptionError::EncryptionFailed(e.to_string()))?;
54
55        Ok(EncryptionResult {
56            nonce: nonce.to_vec(),
57            ciphertext,
58        })
59    }
60
61    fn decrypt_with_aad(
62        &self,
63        encrypted_result: &EncryptionResult,
64        aad: &[u8],
65    ) -> Result<Vec<u8>, OperationOutcomeError> {
66        let nonce = Nonce::<Aes256Gcm>::try_from(encrypted_result.nonce.as_slice())
67            .map_err(|e| EncryptionError::DecryptionFailed(e.to_string()))?;
68
69        let plaintext = self
70            .cipher
71            .decrypt(
72                &nonce,
73                Payload {
74                    msg: encrypted_result.ciphertext.as_slice(),
75                    aad,
76                },
77            )
78            .map_err(|e| EncryptionError::DecryptionFailed(e.to_string()))?;
79
80        Ok(plaintext)
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    #[test]
89    fn round_trips_plaintext() {
90        let encryptor = AesGcmEncryptor::new(&[7u8; KEY_LEN]).unwrap();
91        let plaintext = b"totp-secret-material";
92
93        let ciphertext = encryptor.encrypt(plaintext).unwrap();
94        assert_ne!(ciphertext.ciphertext, plaintext);
95
96        let decrypted = encryptor.decrypt(&ciphertext).unwrap();
97        assert_eq!(decrypted, plaintext);
98    }
99
100    #[test]
101    fn rejects_wrong_key_length() {
102        assert!(AesGcmEncryptor::new(&[0u8; 16]).is_err());
103    }
104
105    #[test]
106    fn rejects_tampered_ciphertext() {
107        let encryptor = AesGcmEncryptor::new(&[7u8; KEY_LEN]).unwrap();
108        let mut result = encryptor.encrypt(b"totp-secret-material").unwrap();
109
110        let last = result.ciphertext.len() - 1;
111        result.ciphertext[last] ^= 0xFF;
112
113        assert!(encryptor.decrypt(&result).is_err());
114    }
115
116    #[test]
117    fn round_trips_plaintext_with_associated_data() {
118        let encryptor = AesGcmEncryptor::new(&[7u8; KEY_LEN]).unwrap();
119        let plaintext = b"totp-secret-material";
120
121        let result = encryptor
122            .encrypt_with_aad(plaintext, b"tenant-a/user-1")
123            .unwrap();
124
125        let decrypted = encryptor
126            .decrypt_with_aad(&result, b"tenant-a/user-1")
127            .unwrap();
128        assert_eq!(decrypted, plaintext);
129    }
130
131    /// A ciphertext copied to another owner's row does not decrypt there.
132    #[test]
133    fn rejects_other_associated_data() {
134        let encryptor = AesGcmEncryptor::new(&[7u8; KEY_LEN]).unwrap();
135        let result = encryptor
136            .encrypt_with_aad(b"totp-secret-material", b"tenant-a/user-1")
137            .unwrap();
138
139        assert!(
140            encryptor
141                .decrypt_with_aad(&result, b"tenant-b/user-1")
142                .is_err()
143        );
144        assert!(encryptor.decrypt(&result).is_err());
145    }
146
147    /// What `encrypt` wrote before associated data existed still decrypts.
148    #[test]
149    fn no_associated_data_is_empty_associated_data() {
150        let encryptor = AesGcmEncryptor::new(&[7u8; KEY_LEN]).unwrap();
151        let plaintext = b"totp-secret-material";
152
153        let without = encryptor.encrypt(plaintext).unwrap();
154        assert_eq!(
155            encryptor.decrypt_with_aad(&without, &[]).unwrap(),
156            plaintext
157        );
158
159        let empty = encryptor.encrypt_with_aad(plaintext, &[]).unwrap();
160        assert_eq!(encryptor.decrypt(&empty).unwrap(), plaintext);
161    }
162}