phoenix_crypto/
encryption.rs1use std::collections::HashMap;
2
3use aes_gcm::{
4 Aes256Gcm, Nonce,
5 aead::{Aead, AeadCore, KeyInit, OsRng, Payload},
6};
7use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
8use serde::{Deserialize, Serialize};
9use thiserror::Error;
10use zeroize::Zeroizing;
11
12#[derive(Clone)]
14pub struct EncryptionKey {
15 id: String,
16 key: Zeroizing<[u8; 32]>,
17}
18
19impl EncryptionKey {
20 pub fn new(id: impl Into<String>, key: impl AsRef<[u8]>) -> Result<Self, EncryptionError> {
24 let id = id.into();
25 if id.trim().is_empty() {
26 return Err(EncryptionError::InvalidKeyId);
27 }
28 let key: [u8; 32] = key
29 .as_ref()
30 .try_into()
31 .map_err(|_| EncryptionError::InvalidKeyLength)?;
32 Ok(Self {
33 id,
34 key: Zeroizing::new(key),
35 })
36 }
37
38 #[must_use]
39 pub fn id(&self) -> &str {
40 &self.id
41 }
42}
43
44impl std::fmt::Debug for EncryptionKey {
45 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46 formatter
47 .debug_struct("EncryptionKey")
48 .field("id", &self.id)
49 .field("key", &"[REDACTED]")
50 .finish()
51 }
52}
53
54#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
56pub struct Ciphertext {
57 pub version: u8,
58 pub algorithm: String,
59 pub key_id: String,
60 pub nonce: String,
61 pub ciphertext: String,
62}
63
64#[derive(Clone, Debug)]
66pub struct Encryptor {
67 active_key_id: String,
68 keys: HashMap<String, EncryptionKey>,
69}
70
71impl Encryptor {
72 #[must_use]
73 pub fn new(active: EncryptionKey) -> Self {
74 Self {
75 active_key_id: active.id.clone(),
76 keys: HashMap::from([(active.id.clone(), active)]),
77 }
78 }
79
80 #[must_use]
81 pub fn with_decryption_key(mut self, key: EncryptionKey) -> Self {
82 self.keys.insert(key.id.clone(), key);
83 self
84 }
85
86 pub fn seal(
92 &self,
93 plaintext: &[u8],
94 associated_data: &[u8],
95 ) -> Result<Ciphertext, EncryptionError> {
96 let key = self
97 .keys
98 .get(&self.active_key_id)
99 .ok_or(EncryptionError::UnknownKey)?;
100 let cipher = Aes256Gcm::new_from_slice(key.key.as_ref())
101 .map_err(|_| EncryptionError::InvalidKeyLength)?;
102 let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
103 let ciphertext = cipher
104 .encrypt(
105 &nonce,
106 Payload {
107 msg: plaintext,
108 aad: associated_data,
109 },
110 )
111 .map_err(|_| EncryptionError::EncryptionFailed)?;
112 Ok(Ciphertext {
113 version: 1,
114 algorithm: "A256GCM".to_owned(),
115 key_id: key.id.clone(),
116 nonce: URL_SAFE_NO_PAD.encode(nonce),
117 ciphertext: URL_SAFE_NO_PAD.encode(ciphertext),
118 })
119 }
120
121 pub fn open(
127 &self,
128 sealed: &Ciphertext,
129 associated_data: &[u8],
130 ) -> Result<Vec<u8>, EncryptionError> {
131 if sealed.version != 1 || sealed.algorithm != "A256GCM" {
132 return Err(EncryptionError::InvalidEnvelope);
133 }
134 let key = self
135 .keys
136 .get(&sealed.key_id)
137 .ok_or(EncryptionError::UnknownKey)?;
138 let nonce = URL_SAFE_NO_PAD
139 .decode(&sealed.nonce)
140 .map_err(|_| EncryptionError::InvalidEnvelope)?;
141 let nonce: [u8; 12] = nonce
142 .try_into()
143 .map_err(|_| EncryptionError::InvalidEnvelope)?;
144 let ciphertext = URL_SAFE_NO_PAD
145 .decode(&sealed.ciphertext)
146 .map_err(|_| EncryptionError::InvalidEnvelope)?;
147 let cipher = Aes256Gcm::new_from_slice(key.key.as_ref())
148 .map_err(|_| EncryptionError::InvalidKeyLength)?;
149 cipher
150 .decrypt(
151 Nonce::from_slice(&nonce),
152 Payload {
153 msg: &ciphertext,
154 aad: associated_data,
155 },
156 )
157 .map_err(|_| EncryptionError::AuthenticationFailed)
158 }
159}
160
161#[derive(Debug, Error)]
162pub enum EncryptionError {
163 #[error("encryption key IDs cannot be empty")]
164 InvalidKeyId,
165 #[error("AES-256-GCM keys must be exactly 32 bytes")]
166 InvalidKeyLength,
167 #[error("encryption key ID is not recognized")]
168 UnknownKey,
169 #[error("encrypted data has an unsupported or malformed envelope")]
170 InvalidEnvelope,
171 #[error("encryption failed")]
172 EncryptionFailed,
173 #[error("encrypted data failed authentication")]
174 AuthenticationFailed,
175}
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180
181 #[test]
182 fn authenticates_context_and_supports_decryption_rotation() {
183 let old = EncryptionKey::new("old", [11_u8; 32]).unwrap();
184 assert!(format!("{old:?}").contains("[REDACTED]"));
185 let sealed = Encryptor::new(old.clone())
186 .seal(b"private value", b"users:7:email")
187 .unwrap();
188 let encryptor = Encryptor::new(EncryptionKey::new("current", [12_u8; 32]).unwrap())
189 .with_decryption_key(old);
190
191 assert_eq!(
192 encryptor.open(&sealed, b"users:7:email").unwrap(),
193 b"private value"
194 );
195 assert!(matches!(
196 encryptor.open(&sealed, b"users:8:email"),
197 Err(EncryptionError::AuthenticationFailed)
198 ));
199 }
200
201 #[test]
202 fn rejects_bad_keys_envelopes_and_unknown_rotation_ids() {
203 assert!(matches!(
204 EncryptionKey::new("short", [1_u8; 16]),
205 Err(EncryptionError::InvalidKeyLength)
206 ));
207 let encryptor = Encryptor::new(EncryptionKey::new("active", [2_u8; 32]).unwrap());
208 let mut sealed = encryptor.seal(b"payload", b"purpose").unwrap();
209 sealed.version = 2;
210 assert!(matches!(
211 encryptor.open(&sealed, b"purpose"),
212 Err(EncryptionError::InvalidEnvelope)
213 ));
214 sealed.version = 1;
215 sealed.key_id = "missing".to_owned();
216 assert!(matches!(
217 encryptor.open(&sealed, b"purpose"),
218 Err(EncryptionError::UnknownKey)
219 ));
220 }
221}