rustcrypt_jasypt/
encryptor.rs1use std::fmt;
4
5use aes_gcm::aead::consts::U12;
6use aes_gcm::aead::{Aead, KeyInit};
7use aes_gcm::aes::{Aes128, Aes192, Aes256};
8use aes_gcm::{AesGcm, Nonce};
9use base64::engine::general_purpose::STANDARD as BASE64;
10use base64::Engine;
11use rand_core::{OsRng, RngCore};
12
13use crate::kdf;
14use crate::prefix::impl_string_encryptor;
15use crate::{Error, Result};
16
17pub const DEFAULT_ITERATIONS: u32 = 10_000;
19
20pub const DEFAULT_SALT_SIZE: usize = 16;
22
23pub const DEFAULT_KEY_SIZE: usize = 32;
25
26pub(crate) const GCM_NONCE_SIZE: usize = 12;
28
29enum Gcm {
31 Aes128(AesGcm<Aes128, U12>),
32 Aes192(AesGcm<Aes192, U12>),
33 Aes256(AesGcm<Aes256, U12>),
34}
35
36impl Gcm {
37 fn new(key: &[u8]) -> Result<Self> {
38 let invalid = || Error::InvalidParameter("key size must be 16, 24 or 32".to_owned());
39 match key.len() {
40 16 => AesGcm::new_from_slice(key).map(Gcm::Aes128),
41 24 => AesGcm::new_from_slice(key).map(Gcm::Aes192),
42 32 => AesGcm::new_from_slice(key).map(Gcm::Aes256),
43 _ => return Err(invalid()),
44 }
45 .map_err(|_| invalid())
46 }
47
48 fn encrypt(&self, nonce: &Nonce<U12>, plaintext: &[u8]) -> aes_gcm::aead::Result<Vec<u8>> {
49 match self {
50 Gcm::Aes128(c) => c.encrypt(nonce, plaintext),
51 Gcm::Aes192(c) => c.encrypt(nonce, plaintext),
52 Gcm::Aes256(c) => c.encrypt(nonce, plaintext),
53 }
54 }
55
56 fn decrypt(&self, nonce: &Nonce<U12>, ciphertext: &[u8]) -> aes_gcm::aead::Result<Vec<u8>> {
57 match self {
58 Gcm::Aes128(c) => c.decrypt(nonce, ciphertext),
59 Gcm::Aes192(c) => c.decrypt(nonce, ciphertext),
60 Gcm::Aes256(c) => c.decrypt(nonce, ciphertext),
61 }
62 }
63}
64
65#[derive(Clone)]
108pub struct Encryptor {
109 password: Vec<u8>,
110 iterations: u32,
111 salt_size: usize,
112 key_size: usize,
113}
114
115impl Encryptor {
116 pub fn new(password: &str) -> Result<Self> {
121 if password.is_empty() {
122 return Err(Error::EmptyPassword);
123 }
124 Ok(Self {
125 password: password.as_bytes().to_vec(),
126 iterations: DEFAULT_ITERATIONS,
127 salt_size: DEFAULT_SALT_SIZE,
128 key_size: DEFAULT_KEY_SIZE,
129 })
130 }
131
132 #[must_use]
135 pub fn with_iterations(mut self, iterations: u32) -> Self {
136 self.iterations = iterations;
137 self
138 }
139
140 #[must_use]
143 pub fn with_salt_size(mut self, salt_size: usize) -> Self {
144 self.salt_size = salt_size;
145 self
146 }
147
148 pub fn with_key_size(mut self, key_size: usize) -> Result<Self> {
153 match key_size {
154 16 | 24 | 32 => {
155 self.key_size = key_size;
156 Ok(self)
157 }
158 _ => Err(Error::InvalidParameter(
159 "key size must be 16, 24 or 32".to_owned(),
160 )),
161 }
162 }
163
164 pub fn iterations(&self) -> u32 {
166 self.iterations
167 }
168
169 pub fn salt_size(&self) -> usize {
171 self.salt_size
172 }
173
174 pub fn key_size(&self) -> usize {
176 self.key_size
177 }
178
179 pub fn encrypt(&self, plaintext: &str) -> Result<String> {
184 if plaintext.is_empty() {
185 return Err(Error::EmptyValue);
186 }
187 let mut salt = vec![0u8; self.salt_size];
188 OsRng.fill_bytes(&mut salt);
189 let mut nonce = [0u8; GCM_NONCE_SIZE];
190 OsRng.fill_bytes(&mut nonce);
191 self.encrypt_with_salt_nonce(&salt, &nonce, plaintext)
192 }
193
194 pub(crate) fn encrypt_with_salt_nonce(
197 &self,
198 salt: &[u8],
199 nonce: &[u8],
200 plaintext: &str,
201 ) -> Result<String> {
202 if plaintext.is_empty() {
203 return Err(Error::EmptyValue);
204 }
205 if nonce.len() != GCM_NONCE_SIZE {
206 return Err(Error::InvalidParameter(format!(
207 "nonce must be {GCM_NONCE_SIZE} bytes"
208 )));
209 }
210 let key = kdf::pbkdf2_sha256(&self.password, salt, self.iterations, self.key_size);
211 let ciphertext = Gcm::new(&key)?
212 .encrypt(Nonce::<U12>::from_slice(nonce), plaintext.as_bytes())
213 .map_err(|_| Error::InvalidParameter("AES-GCM encryption failed".to_owned()))?;
214
215 let mut combined = Vec::with_capacity(salt.len() + nonce.len() + ciphertext.len());
216 combined.extend_from_slice(salt);
217 combined.extend_from_slice(nonce);
218 combined.extend_from_slice(&ciphertext);
219 Ok(BASE64.encode(combined))
220 }
221
222 pub fn decrypt(&self, encoded: &str) -> Result<String> {
229 if encoded.is_empty() {
230 return Err(Error::EmptyValue);
231 }
232 let combined = BASE64.decode(encoded)?;
233 if combined.len() < self.salt_size + GCM_NONCE_SIZE {
234 return Err(Error::DecryptionFailed);
235 }
236 let (salt, rest) = combined.split_at(self.salt_size);
237 let (nonce, ciphertext) = rest.split_at(GCM_NONCE_SIZE);
238
239 let key = kdf::pbkdf2_sha256(&self.password, salt, self.iterations, self.key_size);
240 let plaintext = Gcm::new(&key)?
241 .decrypt(Nonce::<U12>::from_slice(nonce), ciphertext)
242 .map_err(|_| Error::DecryptionFailed)?;
243 String::from_utf8(plaintext).map_err(|_| Error::DecryptionFailed)
244 }
245}
246
247impl_string_encryptor!(Encryptor);
248
249impl fmt::Debug for Encryptor {
250 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251 f.debug_struct("Encryptor")
252 .field("password", &"<redacted>")
253 .field("iterations", &self.iterations)
254 .field("salt_size", &self.salt_size)
255 .field("key_size", &self.key_size)
256 .finish()
257 }
258}
259
260#[cfg(test)]
261mod tests {
262 use super::*;
263
264 #[test]
265 fn debug_does_not_leak_password() {
266 let enc = Encryptor::new("super-secret").unwrap();
267 let dbg = format!("{enc:?}");
268 assert!(dbg.contains("<redacted>"));
269 assert!(!dbg.contains("super-secret"));
270 }
271
272 #[test]
273 fn fixed_salt_nonce_is_deterministic() {
274 let enc = Encryptor::new("rustcrypt-test-2026").unwrap();
275 let salt = [1u8; 16];
276 let nonce = [2u8; 12];
277 let a = enc.encrypt_with_salt_nonce(&salt, &nonce, "hello").unwrap();
278 let b = enc.encrypt_with_salt_nonce(&salt, &nonce, "hello").unwrap();
279 assert_eq!(a, b);
280 assert_eq!(enc.decrypt(&a).unwrap(), "hello");
281 assert_eq!(BASE64.decode(&a).unwrap().len(), 16 + 12 + 5 + 16);
283 }
284
285 #[test]
286 fn wrong_nonce_length_is_rejected() {
287 let enc = Encryptor::new("pw").unwrap();
288 assert!(matches!(
289 enc.encrypt_with_salt_nonce(&[0u8; 16], &[0u8; 11], "x"),
290 Err(Error::InvalidParameter(_))
291 ));
292 }
293}