use std::fmt;
use aes::Aes256;
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
use cipher::block_padding::Pkcs7;
use cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
use des::Des;
use rand_core::{OsRng, RngCore};
use crate::kdf;
use crate::prefix::impl_string_encryptor;
use crate::{Error, Result};
pub const JASYPT_DEFAULT_ITERATIONS: u32 = 1_000;
pub const JASYPT_SALT_SIZE: usize = 8;
pub const JASYPT_STRONG_DEFAULT_ITERATIONS: u32 = 1_000;
pub const JASYPT_STRONG_DEFAULT_SALT_SIZE: usize = 16;
const DES_BLOCK_SIZE: usize = 8;
const AES_BLOCK_SIZE: usize = 16;
type DesCbcEnc = cbc::Encryptor<Des>;
type DesCbcDec = cbc::Decryptor<Des>;
type Aes256CbcEnc = cbc::Encryptor<Aes256>;
type Aes256CbcDec = cbc::Decryptor<Aes256>;
fn invalid_key_iv() -> Error {
Error::InvalidParameter("invalid key or IV length".to_owned())
}
#[derive(Clone)]
pub struct JasyptEncryptor {
password: Vec<u8>,
iterations: u32,
}
impl JasyptEncryptor {
pub fn new(password: &str) -> Result<Self> {
if password.is_empty() {
return Err(Error::EmptyPassword);
}
Ok(Self {
password: password.as_bytes().to_vec(),
iterations: JASYPT_DEFAULT_ITERATIONS,
})
}
#[must_use]
pub fn with_iterations(mut self, iterations: u32) -> Self {
self.iterations = iterations;
self
}
pub fn iterations(&self) -> u32 {
self.iterations
}
pub fn encrypt(&self, plaintext: &str) -> Result<String> {
if plaintext.is_empty() {
return Err(Error::EmptyValue);
}
let mut salt = [0u8; JASYPT_SALT_SIZE];
OsRng.fill_bytes(&mut salt);
self.encrypt_with_salt(&salt, plaintext)
}
pub(crate) fn encrypt_with_salt(
&self,
salt: &[u8; JASYPT_SALT_SIZE],
plaintext: &str,
) -> Result<String> {
if plaintext.is_empty() {
return Err(Error::EmptyValue);
}
let derived = kdf::pbkdf1_md5(&self.password, salt, self.iterations);
let (key, iv) = derived.split_at(8);
let ciphertext = DesCbcEnc::new_from_slices(key, iv)
.map_err(|_| invalid_key_iv())?
.encrypt_padded_vec_mut::<Pkcs7>(plaintext.as_bytes());
let mut combined = Vec::with_capacity(salt.len() + ciphertext.len());
combined.extend_from_slice(salt);
combined.extend_from_slice(&ciphertext);
Ok(BASE64.encode(combined))
}
pub fn decrypt(&self, encoded: &str) -> Result<String> {
if encoded.is_empty() {
return Err(Error::EmptyValue);
}
let combined = BASE64.decode(encoded)?;
if combined.len() < JASYPT_SALT_SIZE + DES_BLOCK_SIZE {
return Err(Error::InvalidJasyptData);
}
let (salt, ciphertext) = combined.split_at(JASYPT_SALT_SIZE);
if ciphertext.len() % DES_BLOCK_SIZE != 0 {
return Err(Error::InvalidJasyptData);
}
let derived = kdf::pbkdf1_md5(&self.password, salt, self.iterations);
let (key, iv) = derived.split_at(8);
let plaintext = DesCbcDec::new_from_slices(key, iv)
.map_err(|_| invalid_key_iv())?
.decrypt_padded_vec_mut::<Pkcs7>(ciphertext)
.map_err(|_| Error::DecryptionFailed)?;
String::from_utf8(plaintext).map_err(|_| Error::DecryptionFailed)
}
}
impl_string_encryptor!(JasyptEncryptor);
impl fmt::Debug for JasyptEncryptor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("JasyptEncryptor")
.field("password", &"<redacted>")
.field("iterations", &self.iterations)
.finish()
}
}
#[derive(Clone)]
pub struct JasyptStrongEncryptor {
password: Vec<u8>,
iterations: u32,
salt_size: usize,
}
impl JasyptStrongEncryptor {
pub fn new(password: &str) -> Result<Self> {
if password.is_empty() {
return Err(Error::EmptyPassword);
}
Ok(Self {
password: password.as_bytes().to_vec(),
iterations: JASYPT_STRONG_DEFAULT_ITERATIONS,
salt_size: JASYPT_STRONG_DEFAULT_SALT_SIZE,
})
}
#[must_use]
pub fn with_iterations(mut self, iterations: u32) -> Self {
self.iterations = iterations;
self
}
#[must_use]
pub fn with_salt_size(mut self, salt_size: usize) -> Self {
self.salt_size = salt_size;
self
}
pub fn iterations(&self) -> u32 {
self.iterations
}
pub fn salt_size(&self) -> usize {
self.salt_size
}
pub fn encrypt(&self, plaintext: &str) -> Result<String> {
if plaintext.is_empty() {
return Err(Error::EmptyValue);
}
let mut salt = vec![0u8; self.salt_size];
OsRng.fill_bytes(&mut salt);
self.encrypt_with_salt(&salt, plaintext)
}
pub(crate) fn encrypt_with_salt(&self, salt: &[u8], plaintext: &str) -> Result<String> {
if plaintext.is_empty() {
return Err(Error::EmptyValue);
}
let derived = kdf::pbkdf2_sha256(&self.password, salt, self.iterations, 48);
let (key, iv) = derived.split_at(32);
let ciphertext = Aes256CbcEnc::new_from_slices(key, iv)
.map_err(|_| invalid_key_iv())?
.encrypt_padded_vec_mut::<Pkcs7>(plaintext.as_bytes());
let mut combined = Vec::with_capacity(salt.len() + ciphertext.len());
combined.extend_from_slice(salt);
combined.extend_from_slice(&ciphertext);
Ok(BASE64.encode(combined))
}
pub fn decrypt(&self, encoded: &str) -> Result<String> {
if encoded.is_empty() {
return Err(Error::EmptyValue);
}
let combined = BASE64.decode(encoded)?;
if combined.len() < self.salt_size + AES_BLOCK_SIZE {
return Err(Error::InvalidJasyptData);
}
let (salt, ciphertext) = combined.split_at(self.salt_size);
if ciphertext.len() % AES_BLOCK_SIZE != 0 {
return Err(Error::InvalidJasyptData);
}
let derived = kdf::pbkdf2_sha256(&self.password, salt, self.iterations, 48);
let (key, iv) = derived.split_at(32);
let plaintext = Aes256CbcDec::new_from_slices(key, iv)
.map_err(|_| invalid_key_iv())?
.decrypt_padded_vec_mut::<Pkcs7>(ciphertext)
.map_err(|_| Error::DecryptionFailed)?;
String::from_utf8(plaintext).map_err(|_| Error::DecryptionFailed)
}
}
impl_string_encryptor!(JasyptStrongEncryptor);
impl fmt::Debug for JasyptStrongEncryptor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("JasyptStrongEncryptor")
.field("password", &"<redacted>")
.field("iterations", &self.iterations)
.field("salt_size", &self.salt_size)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn des_fixed_salt_is_deterministic_and_block_aligned() {
let enc = JasyptEncryptor::new("rustcrypt-test-2026").unwrap();
let salt = [1u8, 2, 3, 4, 5, 6, 7, 8];
let a = enc.encrypt_with_salt(&salt, "hello").unwrap();
let b = enc.encrypt_with_salt(&salt, "hello").unwrap();
assert_eq!(a, b);
assert_eq!(enc.decrypt(&a).unwrap(), "hello");
assert_eq!(BASE64.decode(&a).unwrap().len(), 16);
let full = enc.encrypt_with_salt(&salt, "12345678").unwrap();
assert_eq!(BASE64.decode(&full).unwrap().len(), 8 + 16);
}
#[test]
fn strong_fixed_salt_is_deterministic_and_block_aligned() {
let enc = JasyptStrongEncryptor::new("rustcrypt-test-2026").unwrap();
let salt = [7u8; 16];
let a = enc.encrypt_with_salt(&salt, "hello").unwrap();
let b = enc.encrypt_with_salt(&salt, "hello").unwrap();
assert_eq!(a, b);
assert_eq!(enc.decrypt(&a).unwrap(), "hello");
assert_eq!(BASE64.decode(&a).unwrap().len(), 16 + 16);
let full = enc.encrypt_with_salt(&salt, "0123456789abcdef").unwrap();
assert_eq!(BASE64.decode(&full).unwrap().len(), 16 + 32);
}
#[test]
fn debug_does_not_leak_password() {
let a = format!("{:?}", JasyptEncryptor::new("hunter2").unwrap());
let b = format!("{:?}", JasyptStrongEncryptor::new("hunter2").unwrap());
assert!(!a.contains("hunter2") && a.contains("<redacted>"));
assert!(!b.contains("hunter2") && b.contains("<redacted>"));
}
}