Skip to main content

rustcrypt_jasypt/
prefix.rs

1//! `ENC(...)` wrapper helpers and the [`StringEncryptor`] trait shared by
2//! every encryptor in the crate.
3
4use std::collections::HashMap;
5use std::sync::OnceLock;
6
7use regex::Regex;
8
9use crate::{Error, Result};
10
11/// Prefix of a wrapped encrypted value (`ENC(`).
12pub const ENC_PREFIX: &str = "ENC(";
13
14/// Suffix of a wrapped encrypted value (`)`).
15pub const ENC_SUFFIX: &str = ")";
16
17/// Returns `true` when `value` (ignoring surrounding whitespace) looks like an
18/// `ENC(...)` wrapped value.
19///
20/// This only checks the wrapper, not whether the payload is valid.
21///
22/// ```
23/// use rustcrypt_jasypt::is_encrypted;
24///
25/// assert!(is_encrypted("ENC(abc123)"));
26/// assert!(is_encrypted("  ENC(abc123)  "));
27/// assert!(!is_encrypted("abc123"));
28/// ```
29pub fn is_encrypted(value: &str) -> bool {
30    let v = value.trim();
31    v.starts_with(ENC_PREFIX) && v.ends_with(ENC_SUFFIX)
32}
33
34/// Wraps an encoded payload as `ENC(payload)`.
35pub(crate) fn wrap(encoded: &str) -> String {
36    let mut out = String::with_capacity(ENC_PREFIX.len() + encoded.len() + ENC_SUFFIX.len());
37    out.push_str(ENC_PREFIX);
38    out.push_str(encoded);
39    out.push_str(ENC_SUFFIX);
40    out
41}
42
43/// Validates the `ENC(...)` wrapper (after trimming whitespace) and returns
44/// the inner payload, which may be empty.
45pub(crate) fn unwrap_enc(value: &str) -> Result<&str> {
46    let v = value.trim();
47    if !(v.starts_with(ENC_PREFIX) && v.ends_with(ENC_SUFFIX)) {
48        return Err(Error::InvalidEncFormat);
49    }
50    v.get(ENC_PREFIX.len()..v.len() - ENC_SUFFIX.len())
51        .ok_or(Error::InvalidEncFormat)
52}
53
54/// The compiled `ENC\(([^)]+)\)` pattern used to scan free text.
55pub(crate) fn enc_pattern() -> &'static Regex {
56    static PATTERN: OnceLock<Regex> = OnceLock::new();
57    PATTERN.get_or_init(|| Regex::new(r"ENC\(([^)]+)\)").expect("ENC pattern is a valid regex"))
58}
59
60/// Replaces every `ENC(...)` match in `input` with `f(match)`.
61///
62/// When `f` fails for a match the original text is kept and the error is
63/// remembered; the *last* error is returned alongside the fully processed
64/// string (GoCrypt `DecryptAllInString` semantics).
65pub(crate) fn replace_all_enc<F>(input: &str, mut f: F) -> (String, Option<Error>)
66where
67    F: FnMut(&str) -> Result<String>,
68{
69    let mut last_err = None;
70    let out = enc_pattern().replace_all(input, |caps: &regex::Captures<'_>| {
71        let matched = caps.get(0).map(|m| m.as_str()).unwrap_or_default();
72        match f(matched) {
73            Ok(replacement) => replacement,
74            Err(err) => {
75                last_err = Some(err);
76                matched.to_owned()
77            }
78        }
79    });
80    (out.into_owned(), last_err)
81}
82
83/// Decrypts every value of `map` that [`is_encrypted`] using `f`; other values
84/// are copied through unchanged. The first failure aborts with
85/// [`Error::KeyDecrypt`] carrying the offending key.
86pub(crate) fn decrypt_map_with<F>(
87    map: &HashMap<String, String>,
88    mut f: F,
89) -> Result<HashMap<String, String>>
90where
91    F: FnMut(&str) -> Result<String>,
92{
93    let mut out = HashMap::with_capacity(map.len());
94    for (key, value) in map {
95        let decrypted = if is_encrypted(value) {
96            f(value).map_err(|err| Error::key_decrypt(key.clone(), err))?
97        } else {
98            value.clone()
99        };
100        out.insert(key.clone(), decrypted);
101    }
102    Ok(out)
103}
104
105/// Common interface implemented by [`Encryptor`](crate::Encryptor),
106/// [`JasyptEncryptor`](crate::JasyptEncryptor) and
107/// [`JasyptStrongEncryptor`](crate::JasyptStrongEncryptor).
108///
109/// Every concrete encryptor also exposes these methods inherently, so you only
110/// need to import the trait when writing code that is generic over the
111/// encryptor (for example `fn load<E: StringEncryptor>(enc: &E)`), or when
112/// working with `Box<dyn StringEncryptor>`.
113pub trait StringEncryptor {
114    /// Encrypts `plaintext` and returns the raw base64 payload (no `ENC(...)`).
115    fn encrypt(&self, plaintext: &str) -> Result<String>;
116
117    /// Decrypts a raw base64 payload (no `ENC(...)` wrapper).
118    fn decrypt(&self, encoded: &str) -> Result<String>;
119
120    /// Encrypts `plaintext` and wraps the result as `ENC(...)`.
121    fn encrypt_with_prefix(&self, plaintext: &str) -> Result<String> {
122        Ok(wrap(&self.encrypt(plaintext)?))
123    }
124
125    /// Decrypts an `ENC(...)`-wrapped value. Surrounding whitespace is ignored.
126    ///
127    /// Returns [`Error::InvalidEncFormat`] when the wrapper is missing.
128    fn decrypt_prefixed(&self, value: &str) -> Result<String> {
129        self.decrypt(unwrap_enc(value)?)
130    }
131
132    /// Replaces every `ENC(...)` occurrence in `input` with its plaintext.
133    ///
134    /// Matches that fail to decrypt are left untouched and, after the whole
135    /// input has been processed, the last error is returned (GoCrypt
136    /// semantics). Use [`decrypt_all_in_string_lossy`](Self::decrypt_all_in_string_lossy)
137    /// when you want the best-effort output regardless of failures.
138    fn decrypt_all_in_string(&self, input: &str) -> Result<String> {
139        let (out, err) = replace_all_enc(input, |m| self.decrypt_prefixed(m));
140        match err {
141            Some(err) => Err(err),
142            None => Ok(out),
143        }
144    }
145
146    /// Like [`decrypt_all_in_string`](Self::decrypt_all_in_string) but never
147    /// fails: matches that cannot be decrypted are kept verbatim
148    /// (NodeCrypt/PyCrypt semantics, and what the `rustcrypt decrypt-file`
149    /// command uses).
150    fn decrypt_all_in_string_lossy(&self, input: &str) -> String {
151        replace_all_enc(input, |m| self.decrypt_prefixed(m)).0
152    }
153
154    /// Decrypts every `ENC(...)` value in `map`; other values are copied as-is.
155    ///
156    /// The first failure aborts with [`Error::KeyDecrypt`] naming the key.
157    fn decrypt_map(&self, map: &HashMap<String, String>) -> Result<HashMap<String, String>> {
158        decrypt_map_with(map, |v| self.decrypt_prefixed(v))
159    }
160}
161
162impl<T: StringEncryptor + ?Sized> StringEncryptor for &T {
163    fn encrypt(&self, plaintext: &str) -> Result<String> {
164        (**self).encrypt(plaintext)
165    }
166    fn decrypt(&self, encoded: &str) -> Result<String> {
167        (**self).decrypt(encoded)
168    }
169    fn encrypt_with_prefix(&self, plaintext: &str) -> Result<String> {
170        (**self).encrypt_with_prefix(plaintext)
171    }
172    fn decrypt_prefixed(&self, value: &str) -> Result<String> {
173        (**self).decrypt_prefixed(value)
174    }
175    fn decrypt_all_in_string(&self, input: &str) -> Result<String> {
176        (**self).decrypt_all_in_string(input)
177    }
178    fn decrypt_all_in_string_lossy(&self, input: &str) -> String {
179        (**self).decrypt_all_in_string_lossy(input)
180    }
181    fn decrypt_map(&self, map: &HashMap<String, String>) -> Result<HashMap<String, String>> {
182        (**self).decrypt_map(map)
183    }
184}
185
186impl<T: StringEncryptor + ?Sized> StringEncryptor for Box<T> {
187    fn encrypt(&self, plaintext: &str) -> Result<String> {
188        (**self).encrypt(plaintext)
189    }
190    fn decrypt(&self, encoded: &str) -> Result<String> {
191        (**self).decrypt(encoded)
192    }
193    fn encrypt_with_prefix(&self, plaintext: &str) -> Result<String> {
194        (**self).encrypt_with_prefix(plaintext)
195    }
196    fn decrypt_prefixed(&self, value: &str) -> Result<String> {
197        (**self).decrypt_prefixed(value)
198    }
199    fn decrypt_all_in_string(&self, input: &str) -> Result<String> {
200        (**self).decrypt_all_in_string(input)
201    }
202    fn decrypt_all_in_string_lossy(&self, input: &str) -> String {
203        (**self).decrypt_all_in_string_lossy(input)
204    }
205    fn decrypt_map(&self, map: &HashMap<String, String>) -> Result<HashMap<String, String>> {
206        (**self).decrypt_map(map)
207    }
208}
209
210/// Generates the inherent convenience methods for an encryptor type that
211/// already has inherent `encrypt` / `decrypt` methods, and implements
212/// [`StringEncryptor`] by forwarding to them.
213macro_rules! impl_string_encryptor {
214    ($t:ty) => {
215        impl $t {
216            /// Encrypts `plaintext` and wraps the result as `ENC(...)`.
217            ///
218            /// Each call produces a different ciphertext because the salt
219            /// (and nonce, where applicable) is random.
220            pub fn encrypt_with_prefix(&self, plaintext: &str) -> $crate::Result<String> {
221                Ok($crate::prefix::wrap(&self.encrypt(plaintext)?))
222            }
223
224            /// Decrypts an `ENC(...)`-wrapped value. Surrounding whitespace is
225            /// ignored.
226            ///
227            /// Returns [`Error::InvalidEncFormat`]($crate::Error::InvalidEncFormat)
228            /// when the wrapper is missing.
229            pub fn decrypt_prefixed(&self, value: &str) -> $crate::Result<String> {
230                self.decrypt($crate::prefix::unwrap_enc(value)?)
231            }
232
233            /// Replaces every `ENC(...)` occurrence in `input` with its
234            /// plaintext.
235            ///
236            /// Matches that fail to decrypt are left untouched and, after the
237            /// whole input has been processed, the last error is returned
238            /// (GoCrypt semantics). Use
239            /// [`decrypt_all_in_string_lossy`](Self::decrypt_all_in_string_lossy)
240            /// for the best-effort output regardless of failures.
241            pub fn decrypt_all_in_string(&self, input: &str) -> $crate::Result<String> {
242                let (out, err) =
243                    $crate::prefix::replace_all_enc(input, |m| self.decrypt_prefixed(m));
244                match err {
245                    Some(err) => Err(err),
246                    None => Ok(out),
247                }
248            }
249
250            /// Like [`decrypt_all_in_string`](Self::decrypt_all_in_string) but
251            /// never fails: matches that cannot be decrypted are kept verbatim.
252            pub fn decrypt_all_in_string_lossy(&self, input: &str) -> String {
253                $crate::prefix::replace_all_enc(input, |m| self.decrypt_prefixed(m)).0
254            }
255
256            /// Decrypts every `ENC(...)` value in `map`; other values are
257            /// copied as-is. The first failure aborts with
258            /// [`Error::KeyDecrypt`]($crate::Error::KeyDecrypt) naming the key.
259            pub fn decrypt_map(
260                &self,
261                map: &::std::collections::HashMap<String, String>,
262            ) -> $crate::Result<::std::collections::HashMap<String, String>> {
263                $crate::prefix::decrypt_map_with(map, |v| self.decrypt_prefixed(v))
264            }
265        }
266
267        impl $crate::StringEncryptor for $t {
268            fn encrypt(&self, plaintext: &str) -> $crate::Result<String> {
269                <$t>::encrypt(self, plaintext)
270            }
271            fn decrypt(&self, encoded: &str) -> $crate::Result<String> {
272                <$t>::decrypt(self, encoded)
273            }
274            fn encrypt_with_prefix(&self, plaintext: &str) -> $crate::Result<String> {
275                <$t>::encrypt_with_prefix(self, plaintext)
276            }
277            fn decrypt_prefixed(&self, value: &str) -> $crate::Result<String> {
278                <$t>::decrypt_prefixed(self, value)
279            }
280            fn decrypt_all_in_string(&self, input: &str) -> $crate::Result<String> {
281                <$t>::decrypt_all_in_string(self, input)
282            }
283            fn decrypt_all_in_string_lossy(&self, input: &str) -> String {
284                <$t>::decrypt_all_in_string_lossy(self, input)
285            }
286            fn decrypt_map(
287                &self,
288                map: &::std::collections::HashMap<String, String>,
289            ) -> $crate::Result<::std::collections::HashMap<String, String>> {
290                <$t>::decrypt_map(self, map)
291            }
292        }
293    };
294}
295
296pub(crate) use impl_string_encryptor;
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    /// Toy encryptor: "encrypts" by reversing; fails to decrypt "bad".
303    struct Reverse;
304
305    impl StringEncryptor for Reverse {
306        fn encrypt(&self, plaintext: &str) -> Result<String> {
307            if plaintext.is_empty() {
308                return Err(Error::EmptyValue);
309            }
310            Ok(plaintext.chars().rev().collect())
311        }
312        fn decrypt(&self, encoded: &str) -> Result<String> {
313            if encoded == "bad" {
314                return Err(Error::DecryptionFailed);
315            }
316            Ok(encoded.chars().rev().collect())
317        }
318    }
319
320    #[test]
321    fn is_encrypted_matches_gocrypt() {
322        for ok in ["ENC(abc)", "  ENC(abc)  ", "ENC()", "\tENC(a b)\n"] {
323            assert!(is_encrypted(ok), "{ok:?}");
324        }
325        for bad in [
326            "enc(abc)",
327            "ENC(abc",
328            "abc",
329            "",
330            "ENC(",
331            "ENC",
332            ")",
333            "xENC(abc)",
334        ] {
335            assert!(!is_encrypted(bad), "{bad:?}");
336        }
337    }
338
339    #[test]
340    fn unwrap_enc_extracts_payload() {
341        assert_eq!(unwrap_enc("ENC(x)").unwrap(), "x");
342        assert_eq!(unwrap_enc("  ENC(abc==)\n").unwrap(), "abc==");
343        assert_eq!(unwrap_enc("ENC()").unwrap(), "");
344        assert!(matches!(unwrap_enc("x"), Err(Error::InvalidEncFormat)));
345        assert!(matches!(unwrap_enc("ENC(x"), Err(Error::InvalidEncFormat)));
346        assert!(matches!(unwrap_enc(""), Err(Error::InvalidEncFormat)));
347    }
348
349    #[test]
350    fn wrap_adds_prefix_and_suffix() {
351        assert_eq!(wrap("abc"), "ENC(abc)");
352        assert_eq!(wrap(""), "ENC()");
353    }
354
355    #[test]
356    fn replace_all_enc_zero_one_many() {
357        let upper = |m: &str| Ok(unwrap_enc(m)?.to_uppercase());
358
359        let (out, err) = replace_all_enc("nothing here", upper);
360        assert_eq!(out, "nothing here");
361        assert!(err.is_none());
362
363        let (out, err) = replace_all_enc("k=ENC(abc)", upper);
364        assert_eq!(out, "k=ABC");
365        assert!(err.is_none());
366
367        let (out, err) = replace_all_enc("a=ENC(x) b=ENC(y)\nc=ENC(z)", upper);
368        assert_eq!(out, "a=X b=Y\nc=Z");
369        assert!(err.is_none());
370    }
371
372    #[test]
373    fn replace_all_enc_keeps_failed_match_and_returns_last_error() {
374        let f = |m: &str| {
375            let inner = unwrap_enc(m)?;
376            if inner == "bad" {
377                Err(Error::DecryptionFailed)
378            } else {
379                Ok(inner.to_uppercase())
380            }
381        };
382        let (out, err) = replace_all_enc("a=ENC(x) b=ENC(bad) c=ENC(y)", f);
383        assert_eq!(out, "a=X b=ENC(bad) c=Y");
384        assert!(matches!(err, Some(Error::DecryptionFailed)));
385    }
386
387    #[test]
388    fn replace_all_enc_regex_edge_cases() {
389        let mut seen = Vec::new();
390        let mut spy = |m: &str| {
391            seen.push(m.to_owned());
392            Ok(String::from("_"))
393        };
394        // `ENC()` needs at least one char, so it is not a match; nested
395        // wrappers match greedily up to the first `)`.
396        let (out, _) = replace_all_enc("ENC() ENC(ENC(x)) ENC(a(b)", &mut spy);
397        assert_eq!(out, "ENC() _) _");
398        assert_eq!(seen, vec!["ENC(ENC(x)", "ENC(a(b)"]);
399    }
400
401    #[test]
402    fn decrypt_map_with_mixed_values() {
403        let mut map = HashMap::new();
404        map.insert("host".to_owned(), "localhost".to_owned());
405        map.insert("secret".to_owned(), "ENC(abc)".to_owned());
406        let out = decrypt_map_with(&map, |v| Ok(unwrap_enc(v)?.to_uppercase())).unwrap();
407        assert_eq!(out["host"], "localhost");
408        assert_eq!(out["secret"], "ABC");
409        assert_eq!(out.len(), 2);
410    }
411
412    #[test]
413    fn decrypt_map_with_reports_failing_key() {
414        let mut map = HashMap::new();
415        map.insert("ok".to_owned(), "ENC(abc)".to_owned());
416        map.insert("api_key".to_owned(), "ENC(bad)".to_owned());
417        let err = decrypt_map_with(&map, |v| {
418            let inner = unwrap_enc(v)?;
419            if inner == "bad" {
420                Err(Error::DecryptionFailed)
421            } else {
422                Ok(inner.to_owned())
423            }
424        })
425        .unwrap_err();
426        match err {
427            Error::KeyDecrypt { key, source } => {
428                assert_eq!(key, "api_key");
429                assert!(matches!(*source, Error::DecryptionFailed));
430            }
431            other => panic!("unexpected error: {other:?}"),
432        }
433    }
434
435    #[test]
436    fn trait_default_methods() {
437        let enc = Reverse;
438        assert_eq!(enc.encrypt_with_prefix("abc").unwrap(), "ENC(cba)");
439        assert_eq!(enc.decrypt_prefixed(" ENC(cba) ").unwrap(), "abc");
440        assert!(matches!(
441            enc.decrypt_prefixed("cba"),
442            Err(Error::InvalidEncFormat)
443        ));
444        assert_eq!(
445            enc.decrypt_all_in_string("x=ENC(cba) y=ENC(fed)").unwrap(),
446            "x=abc y=def"
447        );
448        assert!(matches!(
449            enc.decrypt_all_in_string("x=ENC(cba) y=ENC(bad)"),
450            Err(Error::DecryptionFailed)
451        ));
452        assert_eq!(
453            enc.decrypt_all_in_string_lossy("x=ENC(cba) y=ENC(bad)"),
454            "x=abc y=ENC(bad)"
455        );
456
457        let mut map = HashMap::new();
458        map.insert("a".to_owned(), "ENC(cba)".to_owned());
459        map.insert("b".to_owned(), "plain".to_owned());
460        let out = enc.decrypt_map(&map).unwrap();
461        assert_eq!(out["a"], "abc");
462        assert_eq!(out["b"], "plain");
463    }
464
465    #[test]
466    fn trait_is_object_safe_and_forwards_through_box_and_ref() {
467        let boxed: Box<dyn StringEncryptor> = Box::new(Reverse);
468        assert_eq!(boxed.encrypt_with_prefix("abc").unwrap(), "ENC(cba)");
469        let by_ref: &dyn StringEncryptor = &Reverse;
470        assert_eq!(by_ref.decrypt_prefixed("ENC(cba)").unwrap(), "abc");
471
472        fn generic<E: StringEncryptor>(e: E) -> String {
473            e.decrypt("cba").unwrap()
474        }
475        assert_eq!(generic(&Reverse), "abc");
476        assert_eq!(generic(boxed), "abc");
477    }
478}