Skip to main content

rustcrypt_jasypt/
jasypt.rs

1//! Java Jasypt compatible encryptors: [`JasyptEncryptor`] (`PBEWithMD5AndDES`)
2//! and [`JasyptStrongEncryptor`] (the family's `PBEWithHmacSHA256AndAES_256`
3//! format).
4
5use std::fmt;
6
7use aes::Aes256;
8use base64::engine::general_purpose::STANDARD as BASE64;
9use base64::Engine;
10use cipher::block_padding::Pkcs7;
11use cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
12use des::Des;
13use rand_core::{OsRng, RngCore};
14
15use crate::kdf;
16use crate::prefix::impl_string_encryptor;
17use crate::{Error, Result};
18
19/// Default iteration count for [`JasyptEncryptor`] (Jasypt's default).
20pub const JASYPT_DEFAULT_ITERATIONS: u32 = 1_000;
21
22/// Salt size in bytes used by [`JasyptEncryptor`] (fixed at 8 for DES).
23pub const JASYPT_SALT_SIZE: usize = 8;
24
25/// Default iteration count for [`JasyptStrongEncryptor`].
26pub const JASYPT_STRONG_DEFAULT_ITERATIONS: u32 = 1_000;
27
28/// Default salt size in bytes for [`JasyptStrongEncryptor`].
29pub const JASYPT_STRONG_DEFAULT_SALT_SIZE: usize = 16;
30
31const DES_BLOCK_SIZE: usize = 8;
32const AES_BLOCK_SIZE: usize = 16;
33
34type DesCbcEnc = cbc::Encryptor<Des>;
35type DesCbcDec = cbc::Decryptor<Des>;
36type Aes256CbcEnc = cbc::Encryptor<Aes256>;
37type Aes256CbcDec = cbc::Decryptor<Aes256>;
38
39fn invalid_key_iv() -> Error {
40    Error::InvalidParameter("invalid key or IV length".to_owned())
41}
42
43// ═══════════════════════════════════════════════════════════════════════════
44// JasyptEncryptor — PBEWithMD5AndDES
45// ═══════════════════════════════════════════════════════════════════════════
46
47/// Encryptor compatible with Java Jasypt's default algorithm,
48/// `PBEWithMD5AndDES`.
49///
50/// Use this when values must be shared with Java Jasypt (for example a
51/// JasperReport service) or with any other family member in Jasypt mode.
52///
53/// # Wire format
54///
55/// `base64( salt ‖ ciphertext )` with a random 8-byte `salt`. The DES key and
56/// IV are the first and second 8 bytes of PBKDF1-MD5
57/// (`md5(password ‖ salt)` iterated `iterations` times, default 1000).
58/// The ciphertext is DES-CBC with PKCS5 padding.
59///
60/// # Security
61///
62/// DES is a legacy 56-bit cipher and MD5 is a weak hash: this mode is provided
63/// **for compatibility only**. It also has no integrity check, so decrypting
64/// with a wrong password can either fail with
65/// [`Error::DecryptionFailed`] or, occasionally, succeed and return garbage.
66///
67/// # Example
68///
69/// ```
70/// use rustcrypt_jasypt::JasyptEncryptor;
71///
72/// # fn main() -> rustcrypt_jasypt::Result<()> {
73/// let enc = JasyptEncryptor::new("my-password")?;
74/// let wrapped = enc.encrypt_with_prefix("secret")?;
75/// assert_eq!(enc.decrypt_prefixed(&wrapped)?, "secret");
76/// # Ok(())
77/// # }
78/// ```
79#[derive(Clone)]
80pub struct JasyptEncryptor {
81    password: Vec<u8>,
82    iterations: u32,
83}
84
85impl JasyptEncryptor {
86    /// Creates a `PBEWithMD5AndDES` encryptor with Jasypt's default 1000
87    /// iterations.
88    ///
89    /// Returns [`Error::EmptyPassword`] when `password` is empty.
90    pub fn new(password: &str) -> Result<Self> {
91        if password.is_empty() {
92            return Err(Error::EmptyPassword);
93        }
94        Ok(Self {
95            password: password.as_bytes().to_vec(),
96            iterations: JASYPT_DEFAULT_ITERATIONS,
97        })
98    }
99
100    /// Sets the key-derivation iteration count (default `1000`). Must match
101    /// the `keyObtentionIterations` used on the Java side.
102    #[must_use]
103    pub fn with_iterations(mut self, iterations: u32) -> Self {
104        self.iterations = iterations;
105        self
106    }
107
108    /// The configured iteration count.
109    pub fn iterations(&self) -> u32 {
110        self.iterations
111    }
112
113    /// Encrypts `plaintext` and returns the base64 payload (without the
114    /// `ENC(...)` wrapper). A fresh random salt is used every time.
115    ///
116    /// Returns [`Error::EmptyValue`] when `plaintext` is empty.
117    pub fn encrypt(&self, plaintext: &str) -> Result<String> {
118        if plaintext.is_empty() {
119            return Err(Error::EmptyValue);
120        }
121        let mut salt = [0u8; JASYPT_SALT_SIZE];
122        OsRng.fill_bytes(&mut salt);
123        self.encrypt_with_salt(&salt, plaintext)
124    }
125
126    /// Deterministic core of [`encrypt`](Self::encrypt) used by tests.
127    pub(crate) fn encrypt_with_salt(
128        &self,
129        salt: &[u8; JASYPT_SALT_SIZE],
130        plaintext: &str,
131    ) -> Result<String> {
132        if plaintext.is_empty() {
133            return Err(Error::EmptyValue);
134        }
135        let derived = kdf::pbkdf1_md5(&self.password, salt, self.iterations);
136        let (key, iv) = derived.split_at(8);
137        let ciphertext = DesCbcEnc::new_from_slices(key, iv)
138            .map_err(|_| invalid_key_iv())?
139            .encrypt_padded_vec_mut::<Pkcs7>(plaintext.as_bytes());
140
141        let mut combined = Vec::with_capacity(salt.len() + ciphertext.len());
142        combined.extend_from_slice(salt);
143        combined.extend_from_slice(&ciphertext);
144        Ok(BASE64.encode(combined))
145    }
146
147    /// Decrypts a base64 payload produced by Java Jasypt (`PBEWithMD5AndDES`)
148    /// or by any family member's Jasypt encryptor.
149    ///
150    /// Returns [`Error::EmptyValue`] for empty input, [`Error::Base64`] for
151    /// malformed base64, [`Error::InvalidJasyptData`] when the payload is
152    /// shorter than 16 bytes or not a multiple of the DES block size, and
153    /// [`Error::DecryptionFailed`] when the padding check fails.
154    pub fn decrypt(&self, encoded: &str) -> Result<String> {
155        if encoded.is_empty() {
156            return Err(Error::EmptyValue);
157        }
158        let combined = BASE64.decode(encoded)?;
159        // Minimum: 8 (salt) + 8 (one DES block).
160        if combined.len() < JASYPT_SALT_SIZE + DES_BLOCK_SIZE {
161            return Err(Error::InvalidJasyptData);
162        }
163        let (salt, ciphertext) = combined.split_at(JASYPT_SALT_SIZE);
164        if ciphertext.len() % DES_BLOCK_SIZE != 0 {
165            return Err(Error::InvalidJasyptData);
166        }
167
168        let derived = kdf::pbkdf1_md5(&self.password, salt, self.iterations);
169        let (key, iv) = derived.split_at(8);
170        let plaintext = DesCbcDec::new_from_slices(key, iv)
171            .map_err(|_| invalid_key_iv())?
172            .decrypt_padded_vec_mut::<Pkcs7>(ciphertext)
173            .map_err(|_| Error::DecryptionFailed)?;
174        String::from_utf8(plaintext).map_err(|_| Error::DecryptionFailed)
175    }
176}
177
178impl_string_encryptor!(JasyptEncryptor);
179
180impl fmt::Debug for JasyptEncryptor {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        f.debug_struct("JasyptEncryptor")
183            .field("password", &"<redacted>")
184            .field("iterations", &self.iterations)
185            .finish()
186    }
187}
188
189// ═══════════════════════════════════════════════════════════════════════════
190// JasyptStrongEncryptor — PBEWithHmacSHA256AndAES_256 (family format)
191// ═══════════════════════════════════════════════════════════════════════════
192
193/// Stronger Jasypt-style encryptor: PBKDF2-HMAC-SHA256 + AES-256-CBC.
194///
195/// # Wire format
196///
197/// `base64( salt ‖ ciphertext )` with a random `salt` (16 bytes by default).
198/// PBKDF2-HMAC-SHA256 (`iterations`, default 1000) derives 48 bytes: the first
199/// 32 are the AES-256 key and the remaining 16 the CBC IV. The ciphertext is
200/// AES-256-CBC with PKCS7 padding.
201///
202/// # Compatibility note
203///
204/// This is the format shared by GoCrypt, PyCrypt, NodeCrypt, PHPCrypt and
205/// RustCrypt, and it is fully interoperable between them. It is **not**
206/// byte-identical to Java Jasypt's real `PBEWithHmacSHA256AndAES_256`, which
207/// prepends a random IV (`salt ‖ iv ‖ ciphertext`). Do not change this format
208/// here; any move to the true Jasypt layout will be a coordinated release of
209/// all five libraries.
210///
211/// Like every CBC mode without a MAC it has no integrity check: a wrong
212/// password usually fails the padding check but can occasionally yield
213/// garbage.
214///
215/// # Example
216///
217/// ```
218/// use rustcrypt_jasypt::JasyptStrongEncryptor;
219///
220/// # fn main() -> rustcrypt_jasypt::Result<()> {
221/// let enc = JasyptStrongEncryptor::new("my-password")?.with_iterations(5_000);
222/// let wrapped = enc.encrypt_with_prefix("secret")?;
223/// assert_eq!(enc.decrypt_prefixed(&wrapped)?, "secret");
224/// # Ok(())
225/// # }
226/// ```
227#[derive(Clone)]
228pub struct JasyptStrongEncryptor {
229    password: Vec<u8>,
230    iterations: u32,
231    salt_size: usize,
232}
233
234impl JasyptStrongEncryptor {
235    /// Creates a strong encryptor with the defaults
236    /// ([`JASYPT_STRONG_DEFAULT_ITERATIONS`], [`JASYPT_STRONG_DEFAULT_SALT_SIZE`]).
237    ///
238    /// Returns [`Error::EmptyPassword`] when `password` is empty.
239    pub fn new(password: &str) -> Result<Self> {
240        if password.is_empty() {
241            return Err(Error::EmptyPassword);
242        }
243        Ok(Self {
244            password: password.as_bytes().to_vec(),
245            iterations: JASYPT_STRONG_DEFAULT_ITERATIONS,
246            salt_size: JASYPT_STRONG_DEFAULT_SALT_SIZE,
247        })
248    }
249
250    /// Sets the PBKDF2 iteration count (default `1000`).
251    #[must_use]
252    pub fn with_iterations(mut self, iterations: u32) -> Self {
253        self.iterations = iterations;
254        self
255    }
256
257    /// Sets the salt size in bytes (default `16`). Both sides must agree.
258    #[must_use]
259    pub fn with_salt_size(mut self, salt_size: usize) -> Self {
260        self.salt_size = salt_size;
261        self
262    }
263
264    /// The configured PBKDF2 iteration count.
265    pub fn iterations(&self) -> u32 {
266        self.iterations
267    }
268
269    /// The configured salt size in bytes.
270    pub fn salt_size(&self) -> usize {
271        self.salt_size
272    }
273
274    /// Encrypts `plaintext` and returns the base64 payload (without the
275    /// `ENC(...)` wrapper). A fresh random salt is used every time.
276    ///
277    /// Returns [`Error::EmptyValue`] when `plaintext` is empty.
278    pub fn encrypt(&self, plaintext: &str) -> Result<String> {
279        if plaintext.is_empty() {
280            return Err(Error::EmptyValue);
281        }
282        let mut salt = vec![0u8; self.salt_size];
283        OsRng.fill_bytes(&mut salt);
284        self.encrypt_with_salt(&salt, plaintext)
285    }
286
287    /// Deterministic core of [`encrypt`](Self::encrypt) used by tests.
288    pub(crate) fn encrypt_with_salt(&self, salt: &[u8], plaintext: &str) -> Result<String> {
289        if plaintext.is_empty() {
290            return Err(Error::EmptyValue);
291        }
292        let derived = kdf::pbkdf2_sha256(&self.password, salt, self.iterations, 48);
293        let (key, iv) = derived.split_at(32);
294        let ciphertext = Aes256CbcEnc::new_from_slices(key, iv)
295            .map_err(|_| invalid_key_iv())?
296            .encrypt_padded_vec_mut::<Pkcs7>(plaintext.as_bytes());
297
298        let mut combined = Vec::with_capacity(salt.len() + ciphertext.len());
299        combined.extend_from_slice(salt);
300        combined.extend_from_slice(&ciphertext);
301        Ok(BASE64.encode(combined))
302    }
303
304    /// Decrypts a base64 payload produced by any family member's strong
305    /// encryptor with the same parameters.
306    ///
307    /// Returns [`Error::EmptyValue`] for empty input, [`Error::Base64`] for
308    /// malformed base64, [`Error::InvalidJasyptData`] when the payload is
309    /// shorter than `salt_size + 16` bytes or not a multiple of the AES block
310    /// size, and [`Error::DecryptionFailed`] when the padding check fails.
311    pub fn decrypt(&self, encoded: &str) -> Result<String> {
312        if encoded.is_empty() {
313            return Err(Error::EmptyValue);
314        }
315        let combined = BASE64.decode(encoded)?;
316        if combined.len() < self.salt_size + AES_BLOCK_SIZE {
317            return Err(Error::InvalidJasyptData);
318        }
319        let (salt, ciphertext) = combined.split_at(self.salt_size);
320        if ciphertext.len() % AES_BLOCK_SIZE != 0 {
321            return Err(Error::InvalidJasyptData);
322        }
323
324        let derived = kdf::pbkdf2_sha256(&self.password, salt, self.iterations, 48);
325        let (key, iv) = derived.split_at(32);
326        let plaintext = Aes256CbcDec::new_from_slices(key, iv)
327            .map_err(|_| invalid_key_iv())?
328            .decrypt_padded_vec_mut::<Pkcs7>(ciphertext)
329            .map_err(|_| Error::DecryptionFailed)?;
330        String::from_utf8(plaintext).map_err(|_| Error::DecryptionFailed)
331    }
332}
333
334impl_string_encryptor!(JasyptStrongEncryptor);
335
336impl fmt::Debug for JasyptStrongEncryptor {
337    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338        f.debug_struct("JasyptStrongEncryptor")
339            .field("password", &"<redacted>")
340            .field("iterations", &self.iterations)
341            .field("salt_size", &self.salt_size)
342            .finish()
343    }
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349
350    #[test]
351    fn des_fixed_salt_is_deterministic_and_block_aligned() {
352        let enc = JasyptEncryptor::new("rustcrypt-test-2026").unwrap();
353        let salt = [1u8, 2, 3, 4, 5, 6, 7, 8];
354        let a = enc.encrypt_with_salt(&salt, "hello").unwrap();
355        let b = enc.encrypt_with_salt(&salt, "hello").unwrap();
356        assert_eq!(a, b);
357        assert_eq!(enc.decrypt(&a).unwrap(), "hello");
358        // salt(8) + one padded DES block(8)
359        assert_eq!(BASE64.decode(&a).unwrap().len(), 16);
360        // exactly one block of input needs a full padding block
361        let full = enc.encrypt_with_salt(&salt, "12345678").unwrap();
362        assert_eq!(BASE64.decode(&full).unwrap().len(), 8 + 16);
363    }
364
365    #[test]
366    fn strong_fixed_salt_is_deterministic_and_block_aligned() {
367        let enc = JasyptStrongEncryptor::new("rustcrypt-test-2026").unwrap();
368        let salt = [7u8; 16];
369        let a = enc.encrypt_with_salt(&salt, "hello").unwrap();
370        let b = enc.encrypt_with_salt(&salt, "hello").unwrap();
371        assert_eq!(a, b);
372        assert_eq!(enc.decrypt(&a).unwrap(), "hello");
373        assert_eq!(BASE64.decode(&a).unwrap().len(), 16 + 16);
374        let full = enc.encrypt_with_salt(&salt, "0123456789abcdef").unwrap();
375        assert_eq!(BASE64.decode(&full).unwrap().len(), 16 + 32);
376    }
377
378    #[test]
379    fn debug_does_not_leak_password() {
380        let a = format!("{:?}", JasyptEncryptor::new("hunter2").unwrap());
381        let b = format!("{:?}", JasyptStrongEncryptor::new("hunter2").unwrap());
382        assert!(!a.contains("hunter2") && a.contains("<redacted>"));
383        assert!(!b.contains("hunter2") && b.contains("<redacted>"));
384    }
385}