rustcrypt_jasypt/lib.rs
1//! # rustcrypt-jasypt
2//!
3//! Jasypt-compatible `ENC(...)` encryption for Rust configuration: the 🦀 Rust
4//! member of a cross-language family whose members all read each other's
5//! values.
6//!
7//! | Library | Language | Package |
8//! |---|---|---|
9//! | [GoCrypt](https://github.com/farizfadian/gocrypt) | Go | `github.com/farizfadian/gocrypt` |
10//! | [PyCrypt](https://github.com/farizfadian/pycrypt) | Python | `pycrypt-jasypt` |
11//! | [NodeCrypt](https://github.com/farizfadian/nodecrypt) | Node.js | `nodecrypt-jasypt` |
12//! | [PHPCrypt](https://github.com/farizfadian/phpcrypt) | PHP | `farizfadian/phpcrypt` |
13//! | **RustCrypt** (this crate) | Rust | `rustcrypt-jasypt` |
14//! | [Jasypt](http://www.jasypt.org/) | Java | the original |
15//!
16//! One `.env` / YAML / JSON file containing `ENC(...)` values can therefore be
17//! shared by services written in any of these languages.
18//!
19//! ## Three encryptors
20//!
21//! | Type | Algorithm | Readable by Java Jasypt | Use when |
22//! |---|---|---|---|
23//! | [`Encryptor`] | AES-256-GCM, PBKDF2-HMAC-SHA256 | no | only family members read the value; authenticated encryption |
24//! | [`JasyptEncryptor`] | `PBEWithMD5AndDES` | **yes** | the config is shared with Java Jasypt (e.g. a JasperReport service) |
25//! | [`JasyptStrongEncryptor`] | PBKDF2-HMAC-SHA256, AES-256-CBC | family format only | a stronger Jasypt-style mode shared inside the family |
26//!
27//! ## Quick start
28//!
29//! ```
30//! use rustcrypt_jasypt::{Encryptor, JasyptEncryptor};
31//!
32//! # fn main() -> rustcrypt_jasypt::Result<()> {
33//! // Family-internal AES-256-GCM
34//! let enc = Encryptor::new("my-password")?;
35//! let wrapped = enc.encrypt_with_prefix("db_password_123")?; // "ENC(...)"
36//! assert_eq!(enc.decrypt_prefixed(&wrapped)?, "db_password_123");
37//!
38//! // Java-compatible PBEWithMD5AndDES
39//! let jasypt = JasyptEncryptor::new("my-password")?;
40//! let wrapped = jasypt.encrypt_with_prefix("shared-secret")?;
41//! assert_eq!(jasypt.decrypt_prefixed(&wrapped)?, "shared-secret");
42//!
43//! // Builder-style options (both sides must agree)
44//! let tuned = Encryptor::new("my-password")?
45//! .with_iterations(50_000)
46//! .with_salt_size(32);
47//! # let _ = tuned;
48//! # Ok(())
49//! # }
50//! ```
51//!
52//! ## Helpers
53//!
54//! ```
55//! use std::collections::HashMap;
56//! use rustcrypt_jasypt::{is_encrypted, Encryptor};
57//!
58//! # fn main() -> rustcrypt_jasypt::Result<()> {
59//! let enc = Encryptor::new("my-password")?;
60//! let secret = enc.encrypt_with_prefix("s3cr3t")?;
61//! assert!(is_encrypted(&secret));
62//!
63//! // Replace every ENC(...) inside a block of text
64//! let text = format!("DB_HOST=localhost\nDB_PASS={secret}\n");
65//! assert_eq!(
66//! enc.decrypt_all_in_string(&text)?,
67//! "DB_HOST=localhost\nDB_PASS=s3cr3t\n"
68//! );
69//!
70//! // Decrypt only the ENC(...) values of a map
71//! let mut map = HashMap::new();
72//! map.insert("host".to_string(), "localhost".to_string());
73//! map.insert("password".to_string(), secret);
74//! let decrypted = enc.decrypt_map(&map)?;
75//! assert_eq!(decrypted["host"], "localhost");
76//! assert_eq!(decrypted["password"], "s3cr3t");
77//! # Ok(())
78//! # }
79//! ```
80//!
81//! ## Config files (feature `config`, enabled by default)
82//!
83//! ```no_run
84//! # #[cfg(feature = "config")]
85//! # fn main() -> rustcrypt_jasypt::Result<()> {
86//! use rustcrypt_jasypt::{ConfigLoader, JasyptEncryptor};
87//!
88//! // AES-256-GCM, like GoCrypt's NewConfigLoader
89//! let loader = ConfigLoader::new("my-password")?;
90//! let config = loader.load_env_file(".env")?; // HashMap<String, String>
91//! let yaml = loader.load_yaml("config.yml")?; // flat key: value lines
92//! loader.set_to_env(".env")?; // export to std::env
93//!
94//! // Jasypt mode for files shared with Java
95//! let loader = ConfigLoader::with_encryptor(JasyptEncryptor::new("my-password")?);
96//! let shared = loader.load_env_file("shared.env")?;
97//! # let _ = (config, yaml, shared);
98//! # Ok(())
99//! # }
100//! # #[cfg(not(feature = "config"))]
101//! # fn main() {}
102//! ```
103//!
104//! `load_json` deserialises into any `serde` type after decrypting every
105//! `ENC(...)` string at any depth; see [`ConfigLoader`] for details.
106//!
107//! ## Generic code
108//!
109//! All three encryptors implement [`StringEncryptor`], so code can be written
110//! once for any of them (or for `Box<dyn StringEncryptor>`):
111//!
112//! ```
113//! use rustcrypt_jasypt::{Encryptor, JasyptEncryptor, StringEncryptor};
114//!
115//! fn roundtrip<E: StringEncryptor>(enc: &E) -> rustcrypt_jasypt::Result<String> {
116//! let wrapped = enc.encrypt_with_prefix("value")?;
117//! enc.decrypt_prefixed(&wrapped)
118//! }
119//!
120//! # fn main() -> rustcrypt_jasypt::Result<()> {
121//! assert_eq!(roundtrip(&Encryptor::new("pw")?)?, "value");
122//! assert_eq!(roundtrip(&JasyptEncryptor::new("pw")?)?, "value");
123//! let boxed: Box<dyn StringEncryptor> = Box::new(Encryptor::new("pw")?);
124//! assert_eq!(roundtrip(&boxed)?, "value");
125//! # Ok(())
126//! # }
127//! ```
128//!
129//! ## Command line (feature `cli`, enabled by default)
130//!
131//! ```text
132//! cargo install rustcrypt-jasypt
133//!
134//! rustcrypt encrypt -p mySecret -v "db_password" # ENC(...)
135//! rustcrypt encrypt -p mySecret -v "db_password" --jasypt # Java-readable
136//! rustcrypt decrypt -p mySecret -v "ENC(...)"
137//! rustcrypt encrypt-file -p mySecret -i .env.plain -o .env.encrypted
138//! rustcrypt decrypt-file -p mySecret -i .env.encrypted -o -
139//! ```
140//!
141//! The password can also come from the `RUSTCRYPT_PASSWORD` environment
142//! variable.
143//!
144//! ## Feature flags
145//!
146//! | Feature | Default | Adds |
147//! |---|---|---|
148//! | `config` | yes | [`ConfigLoader`] (`serde`, `serde_json`) |
149//! | `cli` | yes | the `rustcrypt` binary (`clap`); implies `config` |
150//!
151//! With `default-features = false` only the encryptors and helpers remain,
152//! backed purely by RustCrypto crates (no OpenSSL, no C code).
153//!
154//! ## Wire formats
155//!
156//! Every payload is standard, padded base64 and is wrapped as `ENC(base64)`
157//! by the `*_with_prefix` methods. All three formats are byte-identical to
158//! GoCrypt (the reference implementation) and are verified against vectors
159//! generated by it in this crate's test suite.
160//!
161//! * [`Encryptor`]: `salt(16) ‖ nonce(12) ‖ ciphertext ‖ tag(16)`
162//! * [`JasyptEncryptor`]: `salt(8) ‖ DES-CBC ciphertext` (PKCS5 padding)
163//! * [`JasyptStrongEncryptor`]: `salt(16) ‖ AES-256-CBC ciphertext` (PKCS7 padding)
164//!
165//! ## Known issues
166//!
167//! * [`JasyptStrongEncryptor`] uses the family's layout, which is **not**
168//! byte-identical to Java Jasypt's real `PBEWithHmacSHA256AndAES_256`
169//! (Java prepends a random IV). It is fully interoperable with GoCrypt,
170//! PyCrypt, NodeCrypt and PHPCrypt.
171//! * [`JasyptEncryptor`] relies on DES and MD5, which are weak by modern
172//! standards, and has no integrity check: a wrong password can occasionally
173//! yield garbage instead of an error. Use it for Java compatibility only.
174
175#![deny(unsafe_code)]
176#![warn(missing_docs)]
177#![deny(rustdoc::broken_intra_doc_links)]
178
179#[cfg(feature = "config")]
180mod config_loader;
181mod encryptor;
182pub mod error;
183#[cfg(test)]
184mod golden;
185mod jasypt;
186mod kdf;
187mod prefix;
188
189#[cfg(feature = "config")]
190pub use config_loader::ConfigLoader;
191pub use encryptor::{Encryptor, DEFAULT_ITERATIONS, DEFAULT_KEY_SIZE, DEFAULT_SALT_SIZE};
192pub use error::{Error, Result};
193pub use jasypt::{
194 JasyptEncryptor, JasyptStrongEncryptor, JASYPT_DEFAULT_ITERATIONS, JASYPT_SALT_SIZE,
195 JASYPT_STRONG_DEFAULT_ITERATIONS, JASYPT_STRONG_DEFAULT_SALT_SIZE,
196};
197pub use prefix::{is_encrypted, StringEncryptor, ENC_PREFIX, ENC_SUFFIX};