rustcrypt_jasypt/
jasypt.rs1use 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
19pub const JASYPT_DEFAULT_ITERATIONS: u32 = 1_000;
21
22pub const JASYPT_SALT_SIZE: usize = 8;
24
25pub const JASYPT_STRONG_DEFAULT_ITERATIONS: u32 = 1_000;
27
28pub 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#[derive(Clone)]
80pub struct JasyptEncryptor {
81 password: Vec<u8>,
82 iterations: u32,
83}
84
85impl JasyptEncryptor {
86 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 #[must_use]
103 pub fn with_iterations(mut self, iterations: u32) -> Self {
104 self.iterations = iterations;
105 self
106 }
107
108 pub fn iterations(&self) -> u32 {
110 self.iterations
111 }
112
113 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 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 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 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#[derive(Clone)]
228pub struct JasyptStrongEncryptor {
229 password: Vec<u8>,
230 iterations: u32,
231 salt_size: usize,
232}
233
234impl JasyptStrongEncryptor {
235 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 #[must_use]
252 pub fn with_iterations(mut self, iterations: u32) -> Self {
253 self.iterations = iterations;
254 self
255 }
256
257 #[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 pub fn iterations(&self) -> u32 {
266 self.iterations
267 }
268
269 pub fn salt_size(&self) -> usize {
271 self.salt_size
272 }
273
274 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 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 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 assert_eq!(BASE64.decode(&a).unwrap().len(), 16);
360 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}