1use std::fmt;
2use std::str::FromStr;
3
4use aes::{Aes128, Aes256};
5use aes_gcm::aead::{AeadInPlace, KeyInit};
6use aes_gcm::{Aes128Gcm, Aes256Gcm, Nonce, Tag};
7use base64::engine::general_purpose::STANDARD;
8use base64::Engine as _;
9use cbc::cipher::block_padding::Pkcs7;
10use cbc::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
11use hmac::{Hmac, Mac};
12use sha2::Sha256;
13use subtle::ConstantTimeEq;
14use zeroize::Zeroizing;
15
16use crate::error::{Error, Result};
17use crate::php::{self, Value};
18
19const GCM_TAG_LEN: usize = 16;
20const GCM_IV_LEN: usize = 12;
21const CBC_IV_LEN: usize = 16;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
25pub enum Cipher {
26 Aes128Cbc,
28 #[default]
30 Aes256Cbc,
31 Aes128Gcm,
33 Aes256Gcm,
35}
36
37impl Cipher {
38 pub fn name(self) -> &'static str {
40 match self {
41 Cipher::Aes128Cbc => "aes-128-cbc",
42 Cipher::Aes256Cbc => "aes-256-cbc",
43 Cipher::Aes128Gcm => "aes-128-gcm",
44 Cipher::Aes256Gcm => "aes-256-gcm",
45 }
46 }
47
48 pub fn key_size(self) -> usize {
50 match self {
51 Cipher::Aes128Cbc | Cipher::Aes128Gcm => 16,
52 Cipher::Aes256Cbc | Cipher::Aes256Gcm => 32,
53 }
54 }
55
56 fn is_aead(self) -> bool {
58 matches!(self, Cipher::Aes128Gcm | Cipher::Aes256Gcm)
59 }
60
61 fn iv_len(self) -> usize {
62 if self.is_aead() {
63 GCM_IV_LEN
64 } else {
65 CBC_IV_LEN
66 }
67 }
68}
69
70impl fmt::Display for Cipher {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 f.write_str(self.name())
73 }
74}
75
76impl FromStr for Cipher {
77 type Err = Error;
78
79 fn from_str(s: &str) -> Result<Self> {
81 match s.to_ascii_lowercase().as_str() {
82 "aes-128-cbc" => Ok(Cipher::Aes128Cbc),
83 "aes-256-cbc" => Ok(Cipher::Aes256Cbc),
84 "aes-128-gcm" => Ok(Cipher::Aes128Gcm),
85 "aes-256-gcm" => Ok(Cipher::Aes256Gcm),
86 _ => Err(Error::UnsupportedCipher),
87 }
88 }
89}
90
91pub fn parse_key(key: &str) -> Result<Vec<u8>> {
101 if key.is_empty() {
102 return Err(Error::InvalidKey);
103 }
104 if let Some(encoded) = key.strip_prefix("base64:") {
105 return STANDARD.decode(encoded).map_err(|_| Error::InvalidKey);
106 }
107 match STANDARD.decode(key) {
108 Ok(decoded) if matches!(decoded.len(), 16 | 32) => Ok(decoded),
109 _ => Ok(key.as_bytes().to_vec()),
110 }
111}
112
113#[derive(Clone)]
119pub struct Encrypter {
120 cipher: Cipher,
121 key: Zeroizing<Vec<u8>>,
122 previous_keys: Vec<Zeroizing<Vec<u8>>>,
123}
124
125impl fmt::Debug for Encrypter {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 f.debug_struct("Encrypter")
128 .field("cipher", &self.cipher)
129 .field("previous_keys", &self.previous_keys.len())
130 .finish_non_exhaustive()
131 }
132}
133
134impl Encrypter {
135 pub fn new(key: &[u8], cipher: Cipher) -> Result<Self> {
138 check_key_length(key, cipher)?;
139 Ok(Self {
140 cipher,
141 key: Zeroizing::new(key.to_vec()),
142 previous_keys: Vec::new(),
143 })
144 }
145
146 pub fn from_app_key(key: &str, cipher: Cipher) -> Result<Self> {
149 Self::new(&Zeroizing::new(parse_key(key)?), cipher)
150 }
151
152 pub fn generate_key(cipher: Cipher) -> Result<Vec<u8>> {
154 let mut key = vec![0u8; cipher.key_size()];
155 getrandom::fill(&mut key).map_err(|_| Error::Encrypt)?;
156 Ok(key)
157 }
158
159 pub fn with_previous_keys<I, K>(mut self, keys: I) -> Result<Self>
163 where
164 I: IntoIterator<Item = K>,
165 K: AsRef<[u8]>,
166 {
167 let mut previous = Vec::new();
168 for key in keys {
169 check_key_length(key.as_ref(), self.cipher)?;
170 previous.push(Zeroizing::new(key.as_ref().to_vec()));
171 }
172 self.previous_keys = previous;
173 Ok(self)
174 }
175
176 pub fn cipher(&self) -> Cipher {
178 self.cipher
179 }
180
181 pub fn key(&self) -> &[u8] {
183 &self.key
184 }
185
186 pub fn encrypt(&self, value: &Value) -> Result<String> {
189 self.encrypt_bytes(&php::serialize(value)?)
190 }
191
192 pub fn decrypt(&self, payload: &str) -> Result<Value> {
194 php::unserialize(&self.decrypt_bytes(payload)?)
195 }
196
197 pub fn encrypt_string(&self, plaintext: &str) -> Result<String> {
199 self.encrypt_bytes(plaintext.as_bytes())
200 }
201
202 pub fn decrypt_string(&self, payload: &str) -> Result<String> {
206 String::from_utf8(self.decrypt_bytes(payload)?).map_err(|_| Error::InvalidUtf8)
207 }
208
209 pub fn encrypt_bytes(&self, plaintext: &[u8]) -> Result<String> {
212 let mut iv = vec![0u8; self.cipher.iv_len()];
213 getrandom::fill(&mut iv).map_err(|_| Error::Encrypt)?;
214
215 let (value, tag) = match self.cipher {
216 Cipher::Aes128Cbc => (
217 cbc::Encryptor::<Aes128>::new_from_slices(&self.key, &iv)
218 .map_err(|_| Error::Encrypt)?
219 .encrypt_padded_vec_mut::<Pkcs7>(plaintext),
220 Vec::new(),
221 ),
222 Cipher::Aes256Cbc => (
223 cbc::Encryptor::<Aes256>::new_from_slices(&self.key, &iv)
224 .map_err(|_| Error::Encrypt)?
225 .encrypt_padded_vec_mut::<Pkcs7>(plaintext),
226 Vec::new(),
227 ),
228 Cipher::Aes128Gcm => gcm_encrypt::<Aes128Gcm>(&self.key, &iv, plaintext)?,
229 Cipher::Aes256Gcm => gcm_encrypt::<Aes256Gcm>(&self.key, &iv, plaintext)?,
230 };
231
232 let iv = STANDARD.encode(iv);
233 let value = STANDARD.encode(value);
234 let tag = STANDARD.encode(tag);
235 let mac = if self.cipher.is_aead() {
236 String::new()
237 } else {
238 hex(&hash(&iv, &value, &self.key))
239 };
240
241 let json = format!(r#"{{"iv":"{iv}","value":"{value}","mac":"{mac}","tag":"{tag}"}}"#);
244 Ok(STANDARD.encode(json))
245 }
246
247 pub fn decrypt_bytes(&self, payload: &str) -> Result<Vec<u8>> {
249 let p = self.parse_payload(payload)?;
250
251 let keys = std::iter::once(&self.key).chain(&self.previous_keys);
253
254 if self.cipher.is_aead() {
255 let tag = p.tag.as_deref().ok_or(Error::Decrypt)?;
256 if tag.len() != GCM_TAG_LEN {
257 return Err(Error::Decrypt);
258 }
259 for key in keys {
260 if let Some(plain) = self.gcm_decrypt(key, &p.iv, &p.value, tag) {
261 return Ok(plain);
262 }
263 }
264 return Err(Error::Decrypt);
265 }
266
267 if p.tag.is_some() {
269 return Err(Error::Decrypt);
270 }
271 let key = keys
272 .into_iter()
273 .find(|key| {
274 let expected = hex(&hash(&p.iv_b64, &p.value_b64, key));
275 bool::from(expected.as_bytes().ct_eq(p.mac.as_bytes()))
276 })
277 .ok_or(Error::InvalidMac)?;
278 self.cbc_decrypt(key, &p.iv, &p.value)
279 }
280
281 pub fn appears_encrypted(value: &str) -> bool {
284 let Some(decoded) = php_base64_decode(value, true) else {
285 return false;
286 };
287 match serde_json::from_slice::<serde_json::Value>(&decoded) {
288 Ok(serde_json::Value::Object(o)) => ["iv", "value", "mac"]
289 .iter()
290 .all(|k| o.get(*k).is_some_and(|v| !v.is_null())),
291 _ => false,
292 }
293 }
294
295 fn parse_payload(&self, payload: &str) -> Result<Payload> {
296 let json = php_base64_decode(payload, false).ok_or(Error::InvalidPayload)?;
298 let json: serde_json::Value =
299 serde_json::from_slice(&json).map_err(|_| Error::InvalidPayload)?;
300 let obj = json.as_object().ok_or(Error::InvalidPayload)?;
301
302 let field = |name: &str| -> Result<String> {
303 match obj.get(name) {
304 Some(serde_json::Value::String(s)) => Ok(s.clone()),
305 _ => Err(Error::InvalidPayload),
306 }
307 };
308 let iv_b64 = field("iv")?;
309 let value_b64 = field("value")?;
310 let mac = field("mac")?;
311 let tag_b64 = match obj.get("tag") {
312 None | Some(serde_json::Value::Null) => String::new(),
313 Some(serde_json::Value::String(s)) => s.clone(),
314 Some(_) => return Err(Error::InvalidPayload),
315 };
316
317 let iv = php_base64_decode(&iv_b64, true)
318 .filter(|iv| iv.len() == self.cipher.iv_len())
319 .ok_or(Error::InvalidPayload)?;
320 let value = php_base64_decode(&value_b64, false).ok_or(Error::InvalidPayload)?;
322 let tag = if tag_b64.is_empty() || tag_b64 == "0" {
324 None
325 } else {
326 php_base64_decode(&tag_b64, false)
327 };
328
329 Ok(Payload {
330 iv_b64,
331 value_b64,
332 mac,
333 iv,
334 value,
335 tag,
336 })
337 }
338
339 fn cbc_decrypt(&self, key: &[u8], iv: &[u8], value: &[u8]) -> Result<Vec<u8>> {
340 match self.cipher {
341 Cipher::Aes128Cbc => cbc::Decryptor::<Aes128>::new_from_slices(key, iv)
342 .map_err(|_| Error::Decrypt)?
343 .decrypt_padded_vec_mut::<Pkcs7>(value)
344 .map_err(|_| Error::Decrypt),
345 _ => cbc::Decryptor::<Aes256>::new_from_slices(key, iv)
346 .map_err(|_| Error::Decrypt)?
347 .decrypt_padded_vec_mut::<Pkcs7>(value)
348 .map_err(|_| Error::Decrypt),
349 }
350 }
351
352 fn gcm_decrypt(&self, key: &[u8], iv: &[u8], value: &[u8], tag: &[u8]) -> Option<Vec<u8>> {
353 match self.cipher {
354 Cipher::Aes128Gcm => gcm_decrypt::<Aes128Gcm>(key, iv, value, tag),
355 _ => gcm_decrypt::<Aes256Gcm>(key, iv, value, tag),
356 }
357 }
358}
359
360struct Payload {
361 iv_b64: String,
363 value_b64: String,
364 mac: String,
365 iv: Vec<u8>,
366 value: Vec<u8>,
367 tag: Option<Vec<u8>>,
368}
369
370fn php_base64_decode(input: &str, strict: bool) -> Option<Vec<u8>> {
377 let mut out = Vec::with_capacity(input.len() / 4 * 3 + 3);
378 let (mut acc, mut count, mut padding) = (0u32, 0usize, 0usize);
379
380 for &c in input.as_bytes() {
381 if c == b'=' {
382 padding += 1;
383 continue;
384 }
385 let v = match c {
386 b'A'..=b'Z' => c - b'A',
387 b'a'..=b'z' => c - b'a' + 26,
388 b'0'..=b'9' => c - b'0' + 52,
389 b'+' => 62,
390 b'/' => 63,
391 b'\t' | b'\n' | b'\r' | b' ' => continue,
392 _ if strict => return None,
393 _ => continue,
394 };
395 if strict && padding > 0 {
396 return None;
397 }
398 acc = (acc << 6) | u32::from(v);
399 count += 1;
400 if count % 4 == 0 {
401 out.extend_from_slice(&[(acc >> 16) as u8, (acc >> 8) as u8, acc as u8]);
402 acc = 0;
403 }
404 }
405
406 match count % 4 {
408 2 => out.push((acc >> 4) as u8),
409 3 => out.extend_from_slice(&[(acc >> 10) as u8, (acc >> 2) as u8]),
410 _ => {}
411 }
412 if strict {
413 if count % 4 == 1 {
414 return None;
415 }
416 if padding > 0 && (padding > 2 || (count + padding) % 4 != 0) {
417 return None;
418 }
419 }
420 Some(out)
421}
422
423fn check_key_length(key: &[u8], cipher: Cipher) -> Result<()> {
424 if key.len() == cipher.key_size() {
425 Ok(())
426 } else {
427 Err(Error::InvalidKeyLength {
428 expected: cipher.key_size(),
429 actual: key.len(),
430 })
431 }
432}
433
434fn hash(iv_b64: &str, value_b64: &str, key: &[u8]) -> Vec<u8> {
436 let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(key).expect("HMAC accepts any key length");
438 mac.update(iv_b64.as_bytes());
439 mac.update(value_b64.as_bytes());
440 mac.finalize().into_bytes().to_vec()
441}
442
443fn hex(bytes: &[u8]) -> String {
444 const DIGITS: &[u8; 16] = b"0123456789abcdef";
445 let mut out = String::with_capacity(bytes.len() * 2);
446 for b in bytes {
447 out.push(DIGITS[usize::from(b >> 4)] as char);
448 out.push(DIGITS[usize::from(b & 0x0f)] as char);
449 }
450 out
451}
452
453fn gcm_encrypt<C: AeadInPlace + KeyInit>(
454 key: &[u8],
455 iv: &[u8],
456 plaintext: &[u8],
457) -> Result<(Vec<u8>, Vec<u8>)> {
458 let cipher = C::new_from_slice(key).map_err(|_| Error::Encrypt)?;
459 let mut buf = plaintext.to_vec();
460 let tag = cipher
461 .encrypt_in_place_detached(Nonce::from_slice(iv), b"", &mut buf)
462 .map_err(|_| Error::Encrypt)?;
463 Ok((buf, tag.to_vec()))
464}
465
466fn gcm_decrypt<C: AeadInPlace + KeyInit>(
467 key: &[u8],
468 iv: &[u8],
469 value: &[u8],
470 tag: &[u8],
471) -> Option<Vec<u8>> {
472 let cipher = C::new_from_slice(key).ok()?;
473 let mut buf = value.to_vec();
474 cipher
475 .decrypt_in_place_detached(Nonce::from_slice(iv), b"", &mut buf, Tag::from_slice(tag))
476 .ok()?;
477 Some(buf)
478}
479
480#[cfg(test)]
481mod tests {
482 use super::*;
483
484 #[test]
486 fn base64_decoding_matches_php() {
487 type Case<'a> = (&'a str, Option<&'a [u8]>, &'a [u8]);
489 let cases: [Case; 24] = [
490 ("", Some(b""), b""),
491 ("A", None, b""),
492 ("AA", Some(b"\x00"), b"\x00"),
493 ("AAAA", Some(b"\x00\x00\x00"), b"\x00\x00\x00"),
494 ("QQ==", Some(b"A"), b"A"),
495 ("QQ=", None, b"A"),
496 ("QQ", Some(b"A"), b"A"),
497 ("Q", None, b""),
498 ("QUJD", Some(b"ABC"), b"ABC"),
499 ("QU JD", Some(b"ABC"), b"ABC"),
500 ("QUJD=", None, b"ABC"),
501 ("QUJD====", None, b"ABC"),
502 ("QQ==QQ==", None, b"A\x04\x10"),
503 ("QQ=Q", None, b"A\x04"),
504 ("Q=Q=", None, b"A"),
505 ("QR==", Some(b"A"), b"A"),
506 ("QUJ*", None, b"AB"),
507 ("!!", None, b""),
508 ("A=", None, b""),
509 ("AA=", None, b"\x00"),
510 ("AAA==", None, b"\x00\x00"),
511 ("====", None, b""),
512 ("QUI=\n", Some(b"AB"), b"AB"),
513 ("Zm9v\nYmFy", Some(b"foobar"), b"foobar"),
514 ];
515 for (input, strict, loose) in cases {
516 assert_eq!(
517 php_base64_decode(input, true).as_deref(),
518 strict,
519 "strict {input:?}"
520 );
521 assert_eq!(
522 php_base64_decode(input, false).as_deref(),
523 Some(loose),
524 "loose {input:?}"
525 );
526 }
527 }
528
529 #[test]
530 fn base64_decoding_agrees_with_the_base64_crate_on_canonical_input() {
531 for len in 0..40 {
532 let data: Vec<u8> = (0..len).map(|i| (i * 37 + 11) as u8).collect();
533 let encoded = STANDARD.encode(&data);
534 assert_eq!(php_base64_decode(&encoded, true), Some(data.clone()));
535 assert_eq!(php_base64_decode(&encoded, false), Some(data));
536 }
537 }
538}