Skip to main content

rustcrypt_jasypt/
encryptor.rs

1//! [`Encryptor`]: AES-GCM with PBKDF2-HMAC-SHA256 (the family's own format).
2
3use 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
17/// Default PBKDF2 iteration count for [`Encryptor`].
18pub const DEFAULT_ITERATIONS: u32 = 10_000;
19
20/// Default salt size in bytes for [`Encryptor`].
21pub const DEFAULT_SALT_SIZE: usize = 16;
22
23/// Default AES key size in bytes for [`Encryptor`] (32 = AES-256).
24pub const DEFAULT_KEY_SIZE: usize = 32;
25
26/// GCM nonce size in bytes (fixed, matches Go's `cipher.NewGCM`).
27pub(crate) const GCM_NONCE_SIZE: usize = 12;
28
29/// AES-GCM cipher selected by key size.
30enum 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/// AES-256-GCM encryptor with PBKDF2-HMAC-SHA256 key derivation.
66///
67/// This is the recommended encryptor for values that only need to be read by
68/// members of the GoCrypt/PyCrypt/NodeCrypt/PHPCrypt/RustCrypt family. It
69/// provides authenticated encryption, so a wrong password or tampered
70/// ciphertext is always detected. **It is not readable by Java Jasypt**; use
71/// [`JasyptEncryptor`](crate::JasyptEncryptor) for that.
72///
73/// # Wire format
74///
75/// `base64( salt ‖ nonce ‖ ciphertext ‖ tag )` with a random `salt`
76/// (16 bytes by default), a random 12-byte GCM `nonce`, and the 16-byte GCM
77/// tag appended to the ciphertext. No associated data is used.
78///
79/// # Example
80///
81/// ```
82/// use rustcrypt_jasypt::Encryptor;
83///
84/// # fn main() -> rustcrypt_jasypt::Result<()> {
85/// let enc = Encryptor::new("my-password")?;
86/// let wrapped = enc.encrypt_with_prefix("db_password_123")?;
87/// assert!(wrapped.starts_with("ENC("));
88/// assert_eq!(enc.decrypt_prefixed(&wrapped)?, "db_password_123");
89/// # Ok(())
90/// # }
91/// ```
92///
93/// Parameters can be tuned with the builder methods:
94///
95/// ```
96/// use rustcrypt_jasypt::Encryptor;
97///
98/// # fn main() -> rustcrypt_jasypt::Result<()> {
99/// let enc = Encryptor::new("my-password")?
100///     .with_iterations(50_000)
101///     .with_salt_size(32)
102///     .with_key_size(32)?;
103/// # let _ = enc;
104/// # Ok(())
105/// # }
106/// ```
107#[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    /// Creates an encryptor with the default parameters
117    /// ([`DEFAULT_ITERATIONS`], [`DEFAULT_SALT_SIZE`], [`DEFAULT_KEY_SIZE`]).
118    ///
119    /// Returns [`Error::EmptyPassword`] when `password` is empty.
120    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    /// Sets the PBKDF2 iteration count (default `10000`). Higher is slower
133    /// but stronger. Both sides must use the same value.
134    #[must_use]
135    pub fn with_iterations(mut self, iterations: u32) -> Self {
136        self.iterations = iterations;
137        self
138    }
139
140    /// Sets the salt size in bytes (default `16`). Both sides must use the
141    /// same value because the salt length is not encoded in the output.
142    #[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    /// Sets the AES key size in bytes: `16` (AES-128), `24` (AES-192) or
149    /// `32` (AES-256, default).
150    ///
151    /// Returns [`Error::InvalidParameter`] for any other value.
152    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    /// The configured PBKDF2 iteration count.
165    pub fn iterations(&self) -> u32 {
166        self.iterations
167    }
168
169    /// The configured salt size in bytes.
170    pub fn salt_size(&self) -> usize {
171        self.salt_size
172    }
173
174    /// The configured AES key size in bytes.
175    pub fn key_size(&self) -> usize {
176        self.key_size
177    }
178
179    /// Encrypts `plaintext` and returns the base64 payload (without the
180    /// `ENC(...)` wrapper). A fresh random salt and nonce are used every time.
181    ///
182    /// Returns [`Error::EmptyValue`] when `plaintext` is empty.
183    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    /// Deterministic core of [`encrypt`](Self::encrypt) used by tests to
195    /// compare against vectors produced by GoCrypt.
196    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    /// Decrypts a base64 payload produced by [`encrypt`](Self::encrypt) (or by
223    /// any family member's default encryptor with the same parameters).
224    ///
225    /// Returns [`Error::EmptyValue`] for empty input, [`Error::Base64`] for
226    /// malformed base64 and [`Error::DecryptionFailed`] for a wrong password,
227    /// tampered data or a payload that is too short.
228    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        // Layout: salt(16) ‖ nonce(12) ‖ ct(5) ‖ tag(16) = 49 bytes.
282        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}