1use crate::hash::FastMap;
25use crate::object::{Dict, Name, ObjRef, Object};
26
27const PAD: [u8; 32] = [
29 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
30 0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80, 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A,
31];
32
33#[derive(Clone, Copy, PartialEq, Debug)]
35enum Cipher {
36 Identity,
39 Rc4,
41 Aesv2,
43 Aesv3,
45}
46
47#[derive(Clone)]
49pub struct Decryptor {
50 key: Vec<u8>,
52 filters: CryptFilters,
54 encrypt_metadata: bool,
58}
59
60#[derive(Clone)]
65struct CryptFilters {
66 named: Vec<(String, Cipher)>,
70 stream: Cipher,
72 string: Cipher,
74 embedded_file: Cipher,
76}
77
78impl CryptFilters {
79 fn uniform(cipher: Cipher) -> CryptFilters {
81 CryptFilters {
82 named: Vec::new(),
83 stream: cipher,
84 string: cipher,
85 embedded_file: cipher,
86 }
87 }
88
89 fn parse(enc: &Dict) -> Option<CryptFilters> {
98 let named: Vec<(String, Cipher)> = enc
99 .get_dict("CF")
100 .into_iter()
101 .flat_map(Dict::iter)
102 .filter(|(name, _)| name.0 != "Identity")
103 .filter_map(|(name, filter)| Some((name.0.clone(), cipher_method(filter.as_dict()?)?)))
104 .collect();
105 let filters = CryptFilters {
106 named,
107 stream: Cipher::Identity,
108 string: Cipher::Identity,
109 embedded_file: Cipher::Identity,
110 };
111 let pick = |key: &str, default: Cipher| match enc.get_name(key) {
112 None => Some(default),
113 Some(n) => filters.named(&n.0),
114 };
115 let stream = pick("StmF", Cipher::Identity)?;
116 let string = pick("StrF", Cipher::Identity)?;
117 let embedded_file = pick("EFF", stream)?;
118 Some(CryptFilters {
119 stream,
120 string,
121 embedded_file,
122 ..filters
123 })
124 }
125
126 fn named(&self, name: &str) -> Option<Cipher> {
130 if name == "Identity" {
131 return Some(Cipher::Identity);
132 }
133 self.named
134 .iter()
135 .find(|(n, _)| n == name)
136 .map(|(_, cipher)| *cipher)
137 }
138}
139
140fn stream_crypt_filter(dict: &Dict, resolve: &dyn Fn(ObjRef) -> Option<Object>) -> Option<String> {
150 let filter = followed(dict.get("Filter")?, resolve)?;
151 let first = match &filter {
152 Object::Name(n) => n.clone(),
153 Object::Array(items) => followed(items.first()?, resolve)?.as_name()?.clone(),
154 _ => return None,
155 };
156 if first.0 != "Crypt" {
157 return None;
158 }
159 let parms = match dict.get("DecodeParms").and_then(|p| followed(p, resolve)) {
160 Some(Object::Dict(d)) => Some(d),
161 Some(Object::Array(items)) => items
162 .first()
163 .and_then(|p| followed(p, resolve))
164 .and_then(|p| p.as_dict().cloned()),
165 _ => None,
166 };
167 let name = parms
168 .and_then(|p| p.get("Name").and_then(|n| followed(n, resolve)))
169 .and_then(|n| n.as_name().map(|n| n.0.clone()))
170 .unwrap_or_else(|| "Identity".to_string());
171 Some(name)
172}
173
174const MAX_REFERENCE_HOPS: usize = 8;
175
176fn followed(obj: &Object, resolve: &dyn Fn(ObjRef) -> Option<Object>) -> Option<Object> {
179 let mut current = obj.clone();
180 for _ in 0..MAX_REFERENCE_HOPS {
181 let Object::Ref(r) = current else {
182 return Some(current);
183 };
184 current = resolve(r)?;
185 }
186 None
187}
188
189pub fn pending_filter_refs(obj: &Object, known: &FastMap<ObjRef, Object>) -> Vec<ObjRef> {
196 let Object::Stream(stream) = obj else {
197 return Vec::new();
198 };
199 let lookup = |r: ObjRef| known.get(&r).cloned();
200 let mut pending = Vec::new();
201 let mut visit = |value: Option<&Object>| -> Option<Object> {
202 let mut current = value?.clone();
203 for _ in 0..MAX_REFERENCE_HOPS {
204 let Object::Ref(r) = current else {
205 return Some(current);
206 };
207 match lookup(r) {
208 Some(next) => current = next,
209 None => {
210 pending.push(r);
211 return None;
212 }
213 }
214 }
215 None
216 };
217 let filter = visit(stream.dict.get("Filter"));
218 let first = match &filter {
219 Some(Object::Array(items)) => visit(items.first()),
220 other => other.clone(),
221 };
222 if first
223 .as_ref()
224 .and_then(Object::as_name)
225 .map(|n| n.0.as_str())
226 != Some("Crypt")
227 {
228 return pending;
229 }
230 let parms = visit(stream.dict.get("DecodeParms"));
231 let parms = match &parms {
232 Some(Object::Array(items)) => visit(items.first()),
233 other => other.clone(),
234 };
235 if let Some(Object::Dict(d)) = &parms {
236 visit(d.get("Name"));
237 }
238 pending
239}
240
241pub fn crypt_filter_refs(enc: &Dict) -> Vec<ObjRef> {
259 match enc.get("CF") {
260 Some(Object::Ref(r)) => vec![*r],
261 Some(Object::Dict(cf)) => cf.iter().filter_map(|(_, v)| v.as_ref()).collect(),
262 _ => Vec::new(),
263 }
264}
265
266pub fn direct_crypt_filters(enc: &Dict, mut lookup: impl FnMut(ObjRef) -> Option<Object>) -> Dict {
281 let mut out = enc.clone();
282 let cf = match out.get("CF") {
283 Some(Object::Ref(r)) => lookup(*r),
284 Some(Object::Dict(cf)) => Some(Object::Dict(cf.clone())),
285 _ => None,
286 };
287 let Some(Object::Dict(mut cf)) = cf else {
288 return out;
289 };
290 for value in cf.values_mut() {
291 if let Object::Ref(r) = *value {
292 if let Some(direct) = lookup(r) {
293 *value = direct;
294 }
295 }
296 }
297 out.insert(Name("CF".to_string()), Object::Dict(cf));
298 out
299}
300
301fn cipher_method(filter: &Dict) -> Option<Cipher> {
307 match filter.get_name("CFM")?.0.as_str() {
308 "V2" => Some(Cipher::Rc4),
309 "AESV2" => Some(Cipher::Aesv2),
310 "AESV3" => Some(Cipher::Aesv3),
311 _ => None,
312 }
313}
314
315fn v4_key_length(enc: &Dict) -> usize {
322 let filter_length = ["StmF", "StrF"].iter().find_map(|key| {
323 let name = enc.get_name(key)?;
324 enc.get_dict("CF")?.get_dict(&name.0)?.get_int("Length")
325 });
326 let bytes = match (enc.get_int("Length"), filter_length) {
327 (Some(bits), _) => bits / 8,
328 (None, Some(len)) if len >= 40 => len / 8,
329 (None, Some(len)) => len,
330 (None, None) => 16,
331 };
332 bytes.clamp(5, 16) as usize
333}
334
335fn encrypt_metadata_flag(enc: &Dict) -> bool {
340 enc.get("EncryptMetadata")
341 .and_then(Object::as_bool)
342 .unwrap_or(true)
343}
344
345impl Decryptor {
346 pub fn from_standard(enc: &Dict, id0: &[u8]) -> Option<Decryptor> {
364 Decryptor::from_standard_with_password(enc, id0, b"")
365 }
366
367 pub fn from_standard_with_password_str(
372 enc: &Dict,
373 id0: &[u8],
374 password: &str,
375 ) -> Option<Decryptor> {
376 let dec = Decryptor::from_standard_with_password(enc, id0, password.as_bytes());
377 if dec.is_some() || password.is_ascii() || password.chars().any(|c| (c as u32) > 255) {
378 return dec;
379 }
380 let latin1: Vec<u8> = password.chars().map(|c| c as u8).collect();
381 Decryptor::from_standard_with_password(enc, id0, &latin1)
382 }
383
384 pub fn from_standard_with_password(
392 enc: &Dict,
393 id0: &[u8],
394 password: &[u8],
395 ) -> Option<Decryptor> {
396 if enc.get_name("Filter").map(|n| n.0.as_str()) != Some("Standard") {
397 return None;
398 }
399 let v = enc.get_int("V").unwrap_or(0);
400 let r = enc.get_int("R").unwrap_or(0);
401 let encrypt_metadata = encrypt_metadata_flag(enc);
402 let (key, filters) = match (v, r) {
403 (1 | 2, 2 | 3) => {
405 let n = if v == 1 {
406 5
407 } else {
408 (enc.get_int("Length").unwrap_or(40) / 8).clamp(5, 16) as usize
409 };
410 let key = rc4_family_key(enc, id0, r, n, password)?;
411 (key, CryptFilters::uniform(Cipher::Rc4))
412 }
413 (4, 4) => {
416 let filters = CryptFilters::parse(enc)?;
417 let key = rc4_family_key(enc, id0, r, v4_key_length(enc), password)?;
418 (key, filters)
419 }
420 (5, 5 | 6) => {
423 let filters = CryptFilters::parse(enc)?;
424 let key = aesv3_key(enc, r, password)?;
425 (key, filters)
426 }
427 _ => return None,
428 };
429 Some(Decryptor {
430 key,
431 filters,
432 encrypt_metadata,
433 })
434 }
435
436 pub fn decrypt_object(&self, obj: &mut Object, num: u32, gen: u16) {
453 self.decrypt_in_place(obj, num, gen, &|_| None);
454 }
455
456 pub fn decrypt_object_with(
460 &self,
461 obj: &mut Object,
462 num: u32,
463 gen: u16,
464 resolve: &dyn Fn(ObjRef) -> Option<Object>,
465 ) {
466 self.decrypt_in_place(obj, num, gen, resolve);
467 }
468
469 fn decrypt_in_place(
482 &self,
483 obj: &mut Object,
484 num: u32,
485 gen: u16,
486 resolve: &dyn Fn(ObjRef) -> Option<Object>,
487 ) {
488 match obj {
489 Object::String(bytes) => self.apply(self.filters.string, num, gen, bytes),
490 Object::Array(items) => items
491 .iter_mut()
492 .for_each(|it| self.decrypt_in_place(it, num, gen, resolve)),
493 Object::Dict(dict) => dict
494 .values_mut()
495 .for_each(|v| self.decrypt_in_place(v, num, gen, resolve)),
496 Object::Stream(stream) => {
497 stream
498 .dict
499 .values_mut()
500 .for_each(|v| self.decrypt_in_place(v, num, gen, resolve));
501 if !self.encrypt_metadata && is_metadata_stream(&stream.dict) {
502 return;
503 }
504 if let Some(name) = stream_crypt_filter(&stream.dict, resolve) {
505 match self.filters.named(&name) {
506 Some(Cipher::Identity) | None => {}
507 Some(cipher) => {
508 stream.data = decrypt_bytes(cipher, &self.key, &stream.data)
509 }
510 }
511 return;
512 }
513 let cipher = if is_embedded_file_stream(&stream.dict) {
514 self.filters.embedded_file
515 } else {
516 self.filters.stream
517 };
518 self.apply(cipher, num, gen, &mut stream.data);
519 }
520 _ => {}
521 }
522 }
523
524 fn apply(&self, cipher: Cipher, num: u32, gen: u16, data: &mut Vec<u8>) {
528 let key = match cipher {
529 Cipher::Identity => return,
530 Cipher::Aesv3 => self.key.clone(), Cipher::Rc4 | Cipher::Aesv2 => self.object_key(cipher, num, gen),
532 };
533 *data = decrypt_bytes(cipher, &key, data);
534 }
535
536 fn object_key(&self, cipher: Cipher, num: u32, gen: u16) -> Vec<u8> {
543 let mut input = Vec::with_capacity(self.key.len() + 9);
544 input.extend_from_slice(&self.key);
545 input.extend_from_slice(&num.to_le_bytes()[..3]);
546 input.extend_from_slice(&gen.to_le_bytes()[..2]);
547 if cipher == Cipher::Aesv2 {
548 input.extend_from_slice(b"sAlT");
549 }
550 let digest = md5(&input);
551 let n = match cipher {
552 Cipher::Aesv2 => 16,
553 _ => (self.key.len() + 5).min(16),
554 };
555 digest[..n].to_vec()
556 }
557}
558
559fn is_metadata_stream(dict: &Dict) -> bool {
561 dict.get_name("Type").map(|n| n.0.as_str()) == Some("Metadata")
562}
563
564fn is_embedded_file_stream(dict: &Dict) -> bool {
566 dict.get_name("Type").map(|n| n.0.as_str()) == Some("EmbeddedFile")
567}
568
569fn decrypt_bytes(cipher: Cipher, key: &[u8], data: &[u8]) -> Vec<u8> {
571 match cipher {
572 Cipher::Identity => data.to_vec(),
573 Cipher::Rc4 => rc4(key, data),
574 Cipher::Aesv2 | Cipher::Aesv3 => aes_cbc_decrypt(key, data),
575 }
576}
577
578fn pad_password(password: &[u8]) -> [u8; 32] {
584 let mut out = [0u8; 32];
585 let n = password.len().min(32);
586 out[..n].copy_from_slice(&password[..n]);
587 out[n..].copy_from_slice(&PAD[..32 - n]);
588 out
589}
590
591fn rc4_family_key(enc: &Dict, id0: &[u8], r: i64, n: usize, password: &[u8]) -> Option<Vec<u8>> {
598 let u = enc.get("U").and_then(Object::as_str_bytes)?;
599 if let Some(key) = md5_file_key(enc, id0, r, n, &pad_password(password)) {
600 if verify_user_password(&key, r, id0, u) {
601 return Some(key);
602 }
603 }
604 let o = enc.get("O").and_then(Object::as_str_bytes)?;
608 if o.len() < 32 {
609 return None;
610 }
611 let mut d = md5(&pad_password(password));
612 if r >= 3 {
613 for _ in 0..50 {
614 d = md5(&d[..n]);
615 }
616 }
617 let okey = &d[..n];
618 let recovered = if r == 2 {
619 rc4(okey, &o[..32])
620 } else {
621 let mut x = o[..32].to_vec();
622 for i in (1u8..=19).rev() {
623 let keyed: Vec<u8> = okey.iter().map(|b| b ^ i).collect();
624 x = rc4(&keyed, &x);
625 }
626 rc4(okey, &x)
627 };
628 let padded: [u8; 32] = recovered.get(..32)?.try_into().ok()?;
629 let key = md5_file_key(enc, id0, r, n, &padded)?;
630 verify_user_password(&key, r, id0, u).then_some(key)
631}
632
633fn md5_file_key(enc: &Dict, id0: &[u8], r: i64, n: usize, padded: &[u8; 32]) -> Option<Vec<u8>> {
637 let o = enc.get("O").and_then(Object::as_str_bytes)?;
638 if o.len() < 32 {
639 return None;
640 }
641 let p = enc.get_int("P")?;
642 let mut input = Vec::with_capacity(32 + 32 + 4 + id0.len() + 4);
643 input.extend_from_slice(padded);
644 input.extend_from_slice(&o[..32]);
645 input.extend_from_slice(&(p as i32 as u32).to_le_bytes()); input.extend_from_slice(id0);
647 if r >= 4 && !encrypt_metadata_flag(enc) {
649 input.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]);
650 }
651 let mut digest = md5(&input);
652 if r >= 3 {
653 for _ in 0..50 {
654 digest = md5(&digest[..n]);
655 }
656 }
657 Some(digest[..n].to_vec())
658}
659
660fn verify_user_password(key: &[u8], r: i64, id0: &[u8], u: &[u8]) -> bool {
664 if r == 2 {
665 let computed = rc4(key, &PAD);
667 u.len() >= 32 && computed == u[..32]
668 } else {
669 let mut input = Vec::with_capacity(32 + id0.len());
671 input.extend_from_slice(&PAD);
672 input.extend_from_slice(id0);
673 let mut x = md5(&input).to_vec();
674 x = rc4(key, &x);
675 for i in 1u8..=19 {
676 let keyed: Vec<u8> = key.iter().map(|b| b ^ i).collect();
677 x = rc4(&keyed, &x);
678 }
679 u.len() >= 16 && x[..16] == u[..16]
681 }
682}
683
684fn rc4(key: &[u8], data: &[u8]) -> Vec<u8> {
686 debug_assert!(!key.is_empty());
687 let mut s: [u8; 256] = core::array::from_fn(|i| i as u8);
688 let mut j = 0u8;
689 for i in 0..256 {
690 j = j.wrapping_add(s[i]).wrapping_add(key[i % key.len()]);
691 s.swap(i, j as usize);
692 }
693 let mut out = Vec::with_capacity(data.len());
694 let (mut i, mut j) = (0u8, 0u8);
695 for &byte in data {
696 i = i.wrapping_add(1);
697 j = j.wrapping_add(s[i as usize]);
698 s.swap(i as usize, j as usize);
699 let k = s[s[i as usize].wrapping_add(s[j as usize]) as usize];
700 out.push(byte ^ k);
701 }
702 out
703}
704
705#[rustfmt::skip]
709const AES_SBOX: [u8; 256] = [
710 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
711 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
712 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
713 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
714 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
715 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
716 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
717 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
718 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
719 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
720 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
721 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
722 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
723 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
724 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
725 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16,
726];
727
728const AES_RCON: [u8; 11] = [
730 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
731];
732
733fn aes_inv_sbox() -> [u8; 256] {
735 let mut inv = [0u8; 256];
736 for (i, &s) in AES_SBOX.iter().enumerate() {
737 inv[s as usize] = i as u8;
738 }
739 inv
740}
741
742fn gmul(mut a: u8, mut b: u8) -> u8 {
744 let mut p = 0u8;
745 for _ in 0..8 {
746 if b & 1 != 0 {
747 p ^= a;
748 }
749 let hi = a & 0x80;
750 a <<= 1;
751 if hi != 0 {
752 a ^= 0x1b;
753 }
754 b >>= 1;
755 }
756 p
757}
758
759fn aes_expand_key(key: &[u8]) -> Vec<[u8; 16]> {
762 let nk = key.len() / 4; let nr = nk + 6;
764 let total = 4 * (nr + 1);
765 let mut w: Vec<[u8; 4]> = Vec::with_capacity(total);
766 for i in 0..nk {
767 w.push([key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]]);
768 }
769 for i in nk..total {
770 let mut t = w[i - 1];
771 if i.is_multiple_of(nk) {
772 t = [t[1], t[2], t[3], t[0]]; for b in &mut t {
774 *b = AES_SBOX[*b as usize]; }
776 t[0] ^= AES_RCON[i / nk];
777 } else if nk > 6 && i % nk == 4 {
778 for b in &mut t {
779 *b = AES_SBOX[*b as usize];
780 }
781 }
782 let prev = w[i - nk];
783 w.push([
784 prev[0] ^ t[0],
785 prev[1] ^ t[1],
786 prev[2] ^ t[2],
787 prev[3] ^ t[3],
788 ]);
789 }
790 (0..=nr)
791 .map(|round| {
792 let mut rk = [0u8; 16];
793 for c in 0..4 {
794 rk[4 * c..4 * c + 4].copy_from_slice(&w[4 * round + c]);
795 }
796 rk
797 })
798 .collect()
799}
800
801fn add_round_key(s: &mut [u8; 16], rk: &[u8; 16]) {
802 for (b, k) in s.iter_mut().zip(rk) {
803 *b ^= k;
804 }
805}
806
807fn shift_rows(s: &mut [u8; 16]) {
808 let o = *s;
809 for r in 1..4 {
810 for c in 0..4 {
811 s[r + 4 * c] = o[r + 4 * ((c + r) % 4)];
812 }
813 }
814}
815
816fn inv_shift_rows(s: &mut [u8; 16]) {
817 let o = *s;
818 for r in 1..4 {
819 for c in 0..4 {
820 s[r + 4 * c] = o[r + 4 * ((c + 4 - r) % 4)];
821 }
822 }
823}
824
825fn mix_columns(s: &mut [u8; 16]) {
826 for c in 0..4 {
827 let i = 4 * c;
828 let (a0, a1, a2, a3) = (s[i], s[i + 1], s[i + 2], s[i + 3]);
829 s[i] = gmul(a0, 2) ^ gmul(a1, 3) ^ a2 ^ a3;
830 s[i + 1] = a0 ^ gmul(a1, 2) ^ gmul(a2, 3) ^ a3;
831 s[i + 2] = a0 ^ a1 ^ gmul(a2, 2) ^ gmul(a3, 3);
832 s[i + 3] = gmul(a0, 3) ^ a1 ^ a2 ^ gmul(a3, 2);
833 }
834}
835
836fn inv_mix_columns(s: &mut [u8; 16]) {
837 for c in 0..4 {
838 let i = 4 * c;
839 let (a0, a1, a2, a3) = (s[i], s[i + 1], s[i + 2], s[i + 3]);
840 s[i] = gmul(a0, 14) ^ gmul(a1, 11) ^ gmul(a2, 13) ^ gmul(a3, 9);
841 s[i + 1] = gmul(a0, 9) ^ gmul(a1, 14) ^ gmul(a2, 11) ^ gmul(a3, 13);
842 s[i + 2] = gmul(a0, 13) ^ gmul(a1, 9) ^ gmul(a2, 14) ^ gmul(a3, 11);
843 s[i + 3] = gmul(a0, 11) ^ gmul(a1, 13) ^ gmul(a2, 9) ^ gmul(a3, 14);
844 }
845}
846
847fn aes_encrypt_block(s: &mut [u8; 16], rks: &[[u8; 16]]) {
848 #[cfg(target_arch = "aarch64")]
849 if std::arch::is_aarch64_feature_detected!("aes") {
850 unsafe { aes_hw::encrypt_block(s, rks) };
852 return;
853 }
854 #[cfg(target_arch = "x86_64")]
855 if std::arch::is_x86_feature_detected!("aes") {
856 unsafe { aes_hw::encrypt_block(s, rks) };
858 return;
859 }
860 aes_encrypt_block_soft(s, rks);
861}
862
863fn aes_encrypt_block_soft(s: &mut [u8; 16], rks: &[[u8; 16]]) {
865 let nr = rks.len() - 1;
866 add_round_key(s, &rks[0]);
867 for rk in &rks[1..nr] {
868 s.iter_mut().for_each(|b| *b = AES_SBOX[*b as usize]);
869 shift_rows(s);
870 mix_columns(s);
871 add_round_key(s, rk);
872 }
873 s.iter_mut().for_each(|b| *b = AES_SBOX[*b as usize]);
874 shift_rows(s);
875 add_round_key(s, &rks[nr]);
876}
877
878fn aes_decrypt_block(s: &mut [u8; 16], rks: &[[u8; 16]], inv_sbox: &[u8; 256]) {
879 #[cfg(target_arch = "aarch64")]
880 if std::arch::is_aarch64_feature_detected!("aes") {
881 unsafe { aes_hw::decrypt_block(s, rks) };
883 return;
884 }
885 #[cfg(target_arch = "x86_64")]
886 if std::arch::is_x86_feature_detected!("aes") {
887 unsafe { aes_hw::decrypt_block(s, rks) };
889 return;
890 }
891 aes_decrypt_block_soft(s, rks, inv_sbox);
892}
893
894fn aes_decrypt_block_soft(s: &mut [u8; 16], rks: &[[u8; 16]], inv_sbox: &[u8; 256]) {
896 let nr = rks.len() - 1;
897 add_round_key(s, &rks[nr]);
898 for rk in rks[1..nr].iter().rev() {
899 inv_shift_rows(s);
900 s.iter_mut().for_each(|b| *b = inv_sbox[*b as usize]);
901 add_round_key(s, rk);
902 inv_mix_columns(s);
903 }
904 inv_shift_rows(s);
905 s.iter_mut().for_each(|b| *b = inv_sbox[*b as usize]);
906 add_round_key(s, &rks[0]);
907}
908
909#[cfg(target_arch = "aarch64")]
917mod aes_hw {
918 use core::arch::aarch64::{
919 vaesdq_u8, vaeseq_u8, vaesimcq_u8, vaesmcq_u8, veorq_u8, vld1q_u8, vmovq_n_u8, vst1q_u8,
920 };
921
922 #[target_feature(enable = "aes")]
925 pub unsafe fn encrypt_block(s: &mut [u8; 16], rks: &[[u8; 16]]) {
926 let nr = rks.len() - 1;
927 let mut x = vld1q_u8(s.as_ptr());
931 for rk in &rks[..nr - 1] {
932 x = vaesmcq_u8(vaeseq_u8(x, vld1q_u8(rk.as_ptr())));
933 }
934 x = vaeseq_u8(x, vld1q_u8(rks[nr - 1].as_ptr()));
935 x = veorq_u8(x, vld1q_u8(rks[nr].as_ptr()));
936 vst1q_u8(s.as_mut_ptr(), x);
937 }
938
939 #[target_feature(enable = "aes")]
942 pub unsafe fn decrypt_block(s: &mut [u8; 16], rks: &[[u8; 16]]) {
943 let nr = rks.len() - 1;
944 let zero = vmovq_n_u8(0);
948 let mut x = vld1q_u8(s.as_ptr());
949 x = veorq_u8(x, vld1q_u8(rks[nr].as_ptr()));
950 for rk in rks[1..nr].iter().rev() {
951 x = vaesdq_u8(x, zero);
952 x = veorq_u8(x, vld1q_u8(rk.as_ptr()));
953 x = vaesimcq_u8(x);
954 }
955 x = vaesdq_u8(x, zero);
956 x = veorq_u8(x, vld1q_u8(rks[0].as_ptr()));
957 vst1q_u8(s.as_mut_ptr(), x);
958 }
959}
960
961#[cfg(target_arch = "x86_64")]
963mod aes_hw {
964 use core::arch::x86_64::{
965 __m128i, _mm_aesdec_si128, _mm_aesdeclast_si128, _mm_aesenc_si128, _mm_aesenclast_si128,
966 _mm_aesimc_si128, _mm_loadu_si128, _mm_storeu_si128, _mm_xor_si128,
967 };
968
969 #[target_feature(enable = "aes")]
972 pub unsafe fn encrypt_block(s: &mut [u8; 16], rks: &[[u8; 16]]) {
973 let nr = rks.len() - 1;
974 let mut x = _mm_loadu_si128(s.as_ptr().cast::<__m128i>());
975 x = _mm_xor_si128(x, _mm_loadu_si128(rks[0].as_ptr().cast::<__m128i>()));
976 for rk in &rks[1..nr] {
977 x = _mm_aesenc_si128(x, _mm_loadu_si128(rk.as_ptr().cast::<__m128i>()));
978 }
979 x = _mm_aesenclast_si128(x, _mm_loadu_si128(rks[nr].as_ptr().cast::<__m128i>()));
980 _mm_storeu_si128(s.as_mut_ptr().cast::<__m128i>(), x);
981 }
982
983 #[target_feature(enable = "aes")]
986 pub unsafe fn decrypt_block(s: &mut [u8; 16], rks: &[[u8; 16]]) {
987 let nr = rks.len() - 1;
988 let mut x = _mm_loadu_si128(s.as_ptr().cast::<__m128i>());
991 x = _mm_xor_si128(x, _mm_loadu_si128(rks[nr].as_ptr().cast::<__m128i>()));
992 for rk in rks[1..nr].iter().rev() {
993 let dk = _mm_aesimc_si128(_mm_loadu_si128(rk.as_ptr().cast::<__m128i>()));
994 x = _mm_aesdec_si128(x, dk);
995 }
996 x = _mm_aesdeclast_si128(x, _mm_loadu_si128(rks[0].as_ptr().cast::<__m128i>()));
997 _mm_storeu_si128(s.as_mut_ptr().cast::<__m128i>(), x);
998 }
999}
1000
1001fn aes_cbc_decrypt_blocks(key: &[u8], iv: &[u8], data: &[u8]) -> Vec<u8> {
1004 if !matches!(key.len(), 16 | 32) {
1007 return Vec::new();
1008 }
1009 if data.is_empty() || !data.len().is_multiple_of(16) || iv.len() < 16 {
1010 return Vec::new();
1011 }
1012 let rks = aes_expand_key(key);
1013 let inv_sbox = aes_inv_sbox();
1014 let mut prev = [0u8; 16];
1015 prev.copy_from_slice(&iv[..16]);
1016 let mut out = Vec::with_capacity(data.len());
1017 for chunk in data.as_chunks::<16>().0 {
1018 let mut block = [0u8; 16];
1019 block.copy_from_slice(chunk);
1020 let cipher = block;
1021 aes_decrypt_block(&mut block, &rks, &inv_sbox);
1022 for (b, p) in block.iter_mut().zip(&prev) {
1023 *b ^= p;
1024 }
1025 out.extend_from_slice(&block);
1026 prev = cipher;
1027 }
1028 out
1029}
1030
1031fn aes_cbc_encrypt_blocks(key: &[u8], iv: &[u8], data: &[u8]) -> Vec<u8> {
1034 let rks = aes_expand_key(key);
1035 let mut prev = [0u8; 16];
1036 prev.copy_from_slice(&iv[..16]);
1037 let mut out = Vec::with_capacity(data.len());
1038 for chunk in data.as_chunks::<16>().0 {
1039 let mut block = [0u8; 16];
1040 for ((b, c), p) in block.iter_mut().zip(chunk).zip(&prev) {
1041 *b = c ^ p;
1042 }
1043 aes_encrypt_block(&mut block, &rks);
1044 out.extend_from_slice(&block);
1045 prev = block;
1046 }
1047 out
1048}
1049
1050fn aes_cbc_decrypt(key: &[u8], data: &[u8]) -> Vec<u8> {
1054 if data.len() < 16 {
1055 return Vec::new();
1056 }
1057 let (iv, ct) = data.split_at(16);
1058 let mut out = aes_cbc_decrypt_blocks(key, iv, ct);
1059 strip_pkcs7(&mut out);
1060 out
1061}
1062
1063fn strip_pkcs7(data: &mut Vec<u8>) {
1065 let Some(&pad) = data.last() else {
1066 return;
1067 };
1068 let pad = pad as usize;
1069 if (1..=16).contains(&pad) && pad <= data.len() {
1070 let start = data.len() - pad;
1071 if data[start..].iter().all(|&b| b as usize == pad) {
1072 data.truncate(start);
1073 }
1074 }
1075}
1076
1077fn pkcs7_pad(data: &[u8]) -> Vec<u8> {
1081 let pad = 16 - data.len() % 16;
1082 let mut out = data.to_vec();
1083 out.resize(data.len() + pad, pad as u8);
1084 out
1085}
1086
1087fn aes_cbc_encrypt(
1091 key: &[u8],
1092 rng: &mut dyn FnMut(&mut [u8]) -> crate::error::Result<()>,
1093 data: &[u8],
1094) -> crate::error::Result<Vec<u8>> {
1095 let mut iv = [0u8; 16];
1096 rng(&mut iv)?;
1097 let mut out = iv.to_vec();
1098 out.extend_from_slice(&aes_cbc_encrypt_blocks(key, &iv, &pkcs7_pad(data)));
1099 Ok(out)
1100}
1101
1102#[rustfmt::skip]
1105const SHA256_K: [u32; 64] = [
1106 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
1107 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
1108 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
1109 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
1110 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
1111 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
1112 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
1113 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
1114];
1115
1116#[derive(Debug, Clone)]
1121pub struct Sha256 {
1122 h: [u32; 8],
1123 tail: [u8; 64],
1124 tail_len: usize,
1125 total: u64,
1126}
1127
1128impl Default for Sha256 {
1129 fn default() -> Sha256 {
1130 Sha256::new()
1131 }
1132}
1133
1134impl Sha256 {
1135 pub fn new() -> Sha256 {
1137 Sha256 {
1138 h: [
1139 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
1140 0x5be0cd19,
1141 ],
1142 tail: [0u8; 64],
1143 tail_len: 0,
1144 total: 0,
1145 }
1146 }
1147
1148 pub fn update(&mut self, input: &[u8]) {
1153 self.total = self.total.wrapping_add(input.len() as u64);
1154 let mut input = input;
1155 if self.tail_len > 0 {
1156 let take = input.len().min(64 - self.tail_len);
1157 self.tail[self.tail_len..self.tail_len + take].copy_from_slice(&input[..take]);
1158 self.tail_len += take;
1159 input = &input[take..];
1160 if self.tail_len < 64 {
1161 return;
1162 }
1163 let block = self.tail;
1164 sha256_compress(&mut self.h, &block);
1165 self.tail_len = 0;
1166 }
1167 let (blocks, rest) = input.as_chunks::<64>();
1168 for block in blocks {
1169 sha256_compress(&mut self.h, block);
1170 }
1171 self.tail[..rest.len()].copy_from_slice(rest);
1172 self.tail_len = rest.len();
1173 }
1174
1175 pub fn finalize(mut self) -> [u8; 32] {
1177 let mut pad = [0u8; 128];
1180 pad[..self.tail_len].copy_from_slice(&self.tail[..self.tail_len]);
1181 pad[self.tail_len] = 0x80;
1182 let padded = if self.tail_len < 56 { 64 } else { 128 };
1183 let bitlen = self.total.wrapping_mul(8);
1184 pad[padded - 8..padded].copy_from_slice(&bitlen.to_be_bytes());
1185 for block in pad[..padded].as_chunks::<64>().0 {
1186 sha256_compress(&mut self.h, block);
1187 }
1188 let mut out = [0u8; 32];
1189 for (i, word) in self.h.iter().enumerate() {
1190 out[4 * i..4 * i + 4].copy_from_slice(&word.to_be_bytes());
1191 }
1192 out
1193 }
1194}
1195
1196pub fn sha256(input: &[u8]) -> [u8; 32] {
1198 let mut hasher = Sha256::new();
1199 hasher.update(input);
1200 hasher.finalize()
1201}
1202
1203fn sha256_compress(h: &mut [u32; 8], block: &[u8; 64]) {
1204 #[cfg(target_arch = "aarch64")]
1205 if std::arch::is_aarch64_feature_detected!("sha2") {
1206 unsafe { sha_hw::compress256(h, block) };
1208 return;
1209 }
1210 sha256_compress_soft(h, block);
1211}
1212
1213fn sha256_compress_soft(h: &mut [u32; 8], block: &[u8; 64]) {
1215 let mut w = [0u32; 64];
1216 for (word, bytes) in w.iter_mut().zip(block.as_chunks::<4>().0) {
1217 *word = u32::from_be_bytes(*bytes);
1218 }
1219 for i in 16..64 {
1220 let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
1221 let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
1222 w[i] = w[i - 16]
1223 .wrapping_add(s0)
1224 .wrapping_add(w[i - 7])
1225 .wrapping_add(s1);
1226 }
1227 let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = *h;
1228 for (k, wi) in SHA256_K.iter().zip(&w) {
1229 let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
1230 let ch = (e & f) ^ ((!e) & g);
1231 let t1 = hh
1232 .wrapping_add(s1)
1233 .wrapping_add(ch)
1234 .wrapping_add(*k)
1235 .wrapping_add(*wi);
1236 let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
1237 let maj = (a & b) ^ (a & c) ^ (b & c);
1238 let t2 = s0.wrapping_add(maj);
1239 hh = g;
1240 g = f;
1241 f = e;
1242 e = d.wrapping_add(t1);
1243 d = c;
1244 c = b;
1245 b = a;
1246 a = t1.wrapping_add(t2);
1247 }
1248 for (hv, v) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) {
1249 *hv = hv.wrapping_add(v);
1250 }
1251}
1252
1253#[rustfmt::skip]
1254const SHA512_K: [u64; 80] = [
1255 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,
1256 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,
1257 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
1258 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694,
1259 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
1260 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,
1261 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4,
1262 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70,
1263 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,
1264 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
1265 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30,
1266 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8,
1267 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8,
1268 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3,
1269 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
1270 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b,
1271 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178,
1272 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b,
1273 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c,
1274 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817,
1275];
1276
1277fn sha512_core(input: &[u8], mut h: [u64; 8]) -> [u64; 8] {
1278 let (blocks, tail) = input.as_chunks::<128>();
1279 for block in blocks {
1280 sha512_compress(&mut h, block);
1281 }
1282 let mut pad = [0u8; 256];
1286 pad[..tail.len()].copy_from_slice(tail);
1287 pad[tail.len()] = 0x80;
1288 let padded = if tail.len() < 112 { 128 } else { 256 };
1289 let bitlen = (input.len() as u128).wrapping_mul(8);
1290 pad[padded - 16..padded].copy_from_slice(&bitlen.to_be_bytes());
1291 for block in pad[..padded].as_chunks::<128>().0 {
1292 sha512_compress(&mut h, block);
1293 }
1294 h
1295}
1296
1297fn sha512_compress(h: &mut [u64; 8], block: &[u8; 128]) {
1298 #[cfg(target_arch = "aarch64")]
1299 if std::arch::is_aarch64_feature_detected!("sha3") {
1300 unsafe { sha_hw::compress512(h, block) };
1303 return;
1304 }
1305 sha512_compress_soft(h, block);
1306}
1307
1308fn sha512_compress_soft(h: &mut [u64; 8], block: &[u8; 128]) {
1310 let mut w = [0u64; 80];
1311 for (word, bytes) in w.iter_mut().zip(block.as_chunks::<8>().0) {
1312 *word = u64::from_be_bytes(*bytes);
1313 }
1314 for i in 16..80 {
1315 let s0 = w[i - 15].rotate_right(1) ^ w[i - 15].rotate_right(8) ^ (w[i - 15] >> 7);
1316 let s1 = w[i - 2].rotate_right(19) ^ w[i - 2].rotate_right(61) ^ (w[i - 2] >> 6);
1317 w[i] = w[i - 16]
1318 .wrapping_add(s0)
1319 .wrapping_add(w[i - 7])
1320 .wrapping_add(s1);
1321 }
1322 let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = *h;
1323 for (k, wi) in SHA512_K.iter().zip(&w) {
1324 let s1 = e.rotate_right(14) ^ e.rotate_right(18) ^ e.rotate_right(41);
1325 let ch = (e & f) ^ ((!e) & g);
1326 let t1 = hh
1327 .wrapping_add(s1)
1328 .wrapping_add(ch)
1329 .wrapping_add(*k)
1330 .wrapping_add(*wi);
1331 let s0 = a.rotate_right(28) ^ a.rotate_right(34) ^ a.rotate_right(39);
1332 let maj = (a & b) ^ (a & c) ^ (b & c);
1333 let t2 = s0.wrapping_add(maj);
1334 hh = g;
1335 g = f;
1336 f = e;
1337 e = d.wrapping_add(t1);
1338 d = c;
1339 c = b;
1340 b = a;
1341 a = t1.wrapping_add(t2);
1342 }
1343 for (hv, v) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) {
1344 *hv = hv.wrapping_add(v);
1345 }
1346}
1347
1348#[cfg(target_arch = "aarch64")]
1357mod sha_hw {
1358 use core::arch::aarch64::{
1359 uint32x4_t, uint64x2_t, vaddq_u32, vaddq_u64, vextq_u64, vld1q_u32, vld1q_u64, vld1q_u8,
1360 vreinterpretq_u32_u8, vreinterpretq_u64_u8, vrev32q_u8, vrev64q_u8, vsha256h2q_u32,
1361 vsha256hq_u32, vsha256su0q_u32, vsha256su1q_u32, vsha512h2q_u64, vsha512hq_u64,
1362 vsha512su0q_u64, vsha512su1q_u64, vst1q_u32,
1363 };
1364
1365 use super::{SHA256_K, SHA512_K};
1366
1367 #[target_feature(enable = "sha2")]
1370 pub unsafe fn compress256(h: &mut [u32; 8], block: &[u8; 64]) {
1371 let mut abcd = vld1q_u32(h.as_ptr());
1372 let mut efgh = vld1q_u32(h.as_ptr().add(4));
1373 let saved = (abcd, efgh);
1374 let mut w: [uint32x4_t; 4] = [
1375 vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(block.as_ptr()))),
1376 vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(block.as_ptr().add(16)))),
1377 vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(block.as_ptr().add(32)))),
1378 vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(block.as_ptr().add(48)))),
1379 ];
1380 for step in 0..16 {
1381 let wk = vaddq_u32(w[step % 4], vld1q_u32(SHA256_K.as_ptr().add(4 * step)));
1382 if step < 12 {
1384 w[step % 4] = vsha256su1q_u32(
1385 vsha256su0q_u32(w[step % 4], w[(step + 1) % 4]),
1386 w[(step + 2) % 4],
1387 w[(step + 3) % 4],
1388 );
1389 }
1390 let prev = abcd;
1391 abcd = vsha256hq_u32(abcd, efgh, wk);
1392 efgh = vsha256h2q_u32(efgh, prev, wk);
1393 }
1394 vst1q_u32(h.as_mut_ptr(), vaddq_u32(abcd, saved.0));
1395 vst1q_u32(h.as_mut_ptr().add(4), vaddq_u32(efgh, saved.1));
1396 }
1397
1398 #[target_feature(enable = "sha2,sha3")]
1401 pub unsafe fn compress512(h: &mut [u64; 8], block: &[u8; 128]) {
1402 let mut s: [uint64x2_t; 4] = [
1406 vld1q_u64(h.as_ptr()),
1407 vld1q_u64(h.as_ptr().add(2)),
1408 vld1q_u64(h.as_ptr().add(4)),
1409 vld1q_u64(h.as_ptr().add(6)),
1410 ];
1411 let saved = s;
1412 let mut w: [uint64x2_t; 8] = [core::mem::zeroed(); 8];
1413 for (pair, bytes) in w.iter_mut().zip(block.as_chunks::<16>().0) {
1414 *pair = vreinterpretq_u64_u8(vrev64q_u8(vld1q_u8(bytes.as_ptr())));
1415 }
1416 for step in 0..40 {
1417 let r = 3 - (step % 4);
1418 let wk = vaddq_u64(w[step % 8], vld1q_u64(SHA512_K.as_ptr().add(2 * step)));
1419 let sum = vaddq_u64(vextq_u64::<1>(wk, wk), s[r]);
1420 let im = vsha512hq_u64(
1421 sum,
1422 vextq_u64::<1>(s[(r + 3) % 4], s[r]),
1423 vextq_u64::<1>(s[(r + 2) % 4], s[(r + 3) % 4]),
1424 );
1425 let updated = vsha512h2q_u64(im, s[(r + 2) % 4], s[(r + 1) % 4]);
1426 s[(r + 2) % 4] = vaddq_u64(s[(r + 2) % 4], im);
1427 s[r] = updated;
1428 if step < 32 {
1430 let i = step % 8;
1431 w[i] = vsha512su1q_u64(
1432 vsha512su0q_u64(w[i], w[(i + 1) % 8]),
1433 w[(i + 7) % 8],
1434 vextq_u64::<1>(w[(i + 4) % 8], w[(i + 5) % 8]),
1435 );
1436 }
1437 }
1438 for (i, (out, kept)) in s.iter().zip(saved).enumerate() {
1439 let summed = vaddq_u64(*out, kept);
1440 core::arch::aarch64::vst1q_u64(h.as_mut_ptr().add(2 * i), summed);
1441 }
1442 }
1443}
1444
1445fn sha512(input: &[u8]) -> Vec<u8> {
1446 let h = sha512_core(
1447 input,
1448 [
1449 0x6a09e667f3bcc908,
1450 0xbb67ae8584caa73b,
1451 0x3c6ef372fe94f82b,
1452 0xa54ff53a5f1d36f1,
1453 0x510e527fade682d1,
1454 0x9b05688c2b3e6c1f,
1455 0x1f83d9abfb41bd6b,
1456 0x5be0cd19137e2179,
1457 ],
1458 );
1459 h.iter().flat_map(|w| w.to_be_bytes()).collect()
1460}
1461
1462fn sha384(input: &[u8]) -> Vec<u8> {
1463 let h = sha512_core(
1464 input,
1465 [
1466 0xcbbb9d5dc1059ed8,
1467 0x629a292a367cd507,
1468 0x9159015a3070dd17,
1469 0x152fecd8f70e5939,
1470 0x67332667ffc00b31,
1471 0x8eb44a8768581511,
1472 0xdb0c2e0d64f98fa7,
1473 0x47b5481dbefa4fa4,
1474 ],
1475 );
1476 h.iter().take(6).flat_map(|w| w.to_be_bytes()).collect()
1477}
1478
1479fn aesv3_key(enc: &Dict, r: i64, password: &[u8]) -> Option<Vec<u8>> {
1485 let pw = &password[..password.len().min(127)];
1486 let u = enc.get("U").and_then(Object::as_str_bytes)?;
1487 if u.len() < 48 {
1488 return None;
1489 }
1490 let perms = enc.get("Perms").and_then(Object::as_str_bytes);
1498 let o = enc.get("O").and_then(Object::as_str_bytes);
1499 if let Some(perms) = perms.filter(|p| p.len() >= 16) {
1500 if let Some(ue) = enc.get("UE").and_then(Object::as_str_bytes) {
1501 if ue.len() >= 32 {
1502 let intermediate = hash_2b(r, pw, &u[40..48], &[]);
1503 let file_key = aes_cbc_decrypt_blocks(&intermediate, &[0u8; 16], &ue[..32]);
1504 if file_key.len() == 32 && perms_marker_valid(&file_key, perms) {
1505 return Some(file_key);
1506 }
1507 }
1508 }
1509 if let (Some(o), Some(oe)) = (o, enc.get("OE").and_then(Object::as_str_bytes)) {
1510 if o.len() >= 48 && oe.len() >= 32 {
1511 let intermediate = hash_2b(r, pw, &o[40..48], &u[..48]);
1512 let file_key = aes_cbc_decrypt_blocks(&intermediate, &[0u8; 16], &oe[..32]);
1513 if file_key.len() == 32 && perms_marker_valid(&file_key, perms) {
1514 return Some(file_key);
1515 }
1516 }
1517 }
1518 }
1519 if let Some(ue) = enc.get("UE").and_then(Object::as_str_bytes) {
1520 if ue.len() >= 32 && hash_2b(r, pw, &u[32..40], &[])[..32] == u[..32] {
1521 let intermediate = hash_2b(r, pw, &u[40..48], &[]);
1522 let file_key = aes_cbc_decrypt_blocks(&intermediate, &[0u8; 16], &ue[..32]);
1523 if file_key.len() == 32 {
1524 return Some(file_key);
1525 }
1526 }
1527 }
1528 let o = o?;
1529 let oe = enc.get("OE").and_then(Object::as_str_bytes)?;
1530 if o.len() < 48 || oe.len() < 32 {
1531 return None;
1532 }
1533 if hash_2b(r, pw, &o[32..40], &u[..48])[..32] != o[..32] {
1534 return None;
1535 }
1536 let intermediate = hash_2b(r, pw, &o[40..48], &u[..48]);
1537 let file_key = aes_cbc_decrypt_blocks(&intermediate, &[0u8; 16], &oe[..32]);
1538 (file_key.len() == 32).then_some(file_key)
1539}
1540
1541fn perms_marker_valid(file_key: &[u8], perms: &[u8]) -> bool {
1544 let rks = aes_expand_key(file_key);
1545 let inv_sbox = aes_inv_sbox();
1546 let mut block = [0u8; 16];
1547 block.copy_from_slice(&perms[..16]);
1548 aes_decrypt_block(&mut block, &rks, &inv_sbox);
1549 &block[9..12] == b"adb"
1550}
1551
1552fn hash_2b(r: i64, password: &[u8], salt: &[u8], udata: &[u8]) -> Vec<u8> {
1555 let mut seed = Vec::with_capacity(password.len() + salt.len() + udata.len());
1556 seed.extend_from_slice(password);
1557 seed.extend_from_slice(salt);
1558 seed.extend_from_slice(udata);
1559 let mut k = sha256(&seed).to_vec();
1560 if r < 6 {
1561 return k; }
1563 let mut round = 0usize;
1564 let mut k1 = Vec::with_capacity(64 * (password.len() + 64 + udata.len()));
1565 loop {
1566 k1.clear();
1567 for _ in 0..64 {
1568 k1.extend_from_slice(password);
1569 k1.extend_from_slice(&k);
1570 k1.extend_from_slice(udata);
1571 }
1572 let e = aes_cbc_encrypt_blocks(&k[..16], &k[16..32], &k1);
1573 let modulus = e[..16].iter().map(|&b| u32::from(b)).sum::<u32>() % 3;
1574 k = match modulus {
1575 0 => sha256(&e).to_vec(),
1576 1 => sha384(&e),
1577 _ => sha512(&e),
1578 };
1579 round += 1;
1580 if round >= 64
1581 && e.last()
1582 .is_some_and(|&last| usize::from(last) <= round - 32)
1583 {
1584 break;
1585 }
1586 }
1587 k.truncate(32);
1588 k
1589}
1590
1591pub(crate) struct KeyMaterial {
1595 file_key: [u8; 32],
1596 u: Vec<u8>,
1597 ue: Vec<u8>,
1598 o: Vec<u8>,
1599 oe: Vec<u8>,
1600 perms: Vec<u8>,
1601}
1602
1603pub(crate) fn r6_key_material<E>(
1610 user_pw: &[u8],
1611 owner_pw: &[u8],
1612 p: i32,
1613 encrypt_metadata: bool,
1614 rng: &mut dyn FnMut(&mut [u8]) -> std::result::Result<(), E>,
1615) -> std::result::Result<KeyMaterial, E> {
1616 let user_pw = &user_pw[..user_pw.len().min(127)];
1617 let owner_pw = &owner_pw[..owner_pw.len().min(127)];
1618
1619 let mut file_key = [0u8; 32];
1620 rng(&mut file_key)?;
1621
1622 let mut user_salt = [0u8; 16];
1625 rng(&mut user_salt)?;
1626 let mut u = hash_2b(6, user_pw, &user_salt[..8], &[]);
1627 u.extend_from_slice(&user_salt);
1628 let user_intermediate = hash_2b(6, user_pw, &user_salt[8..], &[]);
1629 let ue = aes_cbc_encrypt_blocks(&user_intermediate, &[0u8; 16], &file_key);
1630
1631 let mut owner_salt = [0u8; 16];
1634 rng(&mut owner_salt)?;
1635 let mut o = hash_2b(6, owner_pw, &owner_salt[..8], &u[..48]);
1636 o.extend_from_slice(&owner_salt);
1637 let owner_intermediate = hash_2b(6, owner_pw, &owner_salt[8..], &u[..48]);
1638 let oe = aes_cbc_encrypt_blocks(&owner_intermediate, &[0u8; 16], &file_key);
1639
1640 let mut perms_block = [0u8; 16];
1643 perms_block[..4].copy_from_slice(&p.to_le_bytes());
1644 perms_block[4..8].copy_from_slice(&[0xff; 4]);
1645 perms_block[8] = if encrypt_metadata { b'T' } else { b'F' };
1646 perms_block[9..12].copy_from_slice(b"adb");
1647 rng(&mut perms_block[12..])?;
1648 aes_encrypt_block(&mut perms_block, &aes_expand_key(&file_key));
1649
1650 Ok(KeyMaterial {
1651 file_key,
1652 u,
1653 ue,
1654 o,
1655 oe,
1656 perms: perms_block.to_vec(),
1657 })
1658}
1659
1660#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
1665pub(crate) fn fill_os_random(buf: &mut [u8]) -> crate::error::Result<()> {
1666 getrandom::fill(buf).map_err(|e| crate::error::Error::RandomUnavailable(e.to_string()))
1667}
1668
1669#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1674pub struct Permissions {
1675 pub print: bool,
1678 pub modify: bool,
1681 pub copy: bool,
1683 pub annotate: bool,
1686 pub fill_forms: bool,
1689 pub accessibility: bool,
1691 pub assemble: bool,
1694 pub print_hires: bool,
1697}
1698
1699pub const PERMISSION_NAMES: [&str; 8] = [
1704 "print",
1705 "modify",
1706 "copy",
1707 "annotate",
1708 "fill-forms",
1709 "accessibility",
1710 "assemble",
1711 "print-hires",
1712];
1713
1714impl Permissions {
1715 pub fn all() -> Permissions {
1717 Permissions {
1718 print: true,
1719 modify: true,
1720 copy: true,
1721 annotate: true,
1722 fill_forms: true,
1723 accessibility: true,
1724 assemble: true,
1725 print_hires: true,
1726 }
1727 }
1728
1729 pub fn from_names<'a>(names: impl IntoIterator<Item = &'a str>) -> Result<Permissions, String> {
1734 let mut permissions = Permissions {
1735 print: false,
1736 modify: false,
1737 copy: false,
1738 annotate: false,
1739 fill_forms: false,
1740 accessibility: false,
1741 assemble: false,
1742 print_hires: false,
1743 };
1744 for name in names {
1745 match name {
1746 "print" => permissions.print = true,
1747 "modify" => permissions.modify = true,
1748 "copy" => permissions.copy = true,
1749 "annotate" => permissions.annotate = true,
1750 "fill-forms" => permissions.fill_forms = true,
1751 "accessibility" => permissions.accessibility = true,
1752 "assemble" => permissions.assemble = true,
1753 "print-hires" => permissions.print_hires = true,
1754 other => return Err(other.to_string()),
1755 }
1756 }
1757 Ok(permissions)
1758 }
1759
1760 pub(crate) fn p_value(&self) -> i32 {
1767 let flags: [(u32, bool); 8] = [
1768 (3, self.print),
1769 (4, self.modify),
1770 (5, self.copy),
1771 (6, self.annotate),
1772 (9, self.fill_forms),
1773 (10, self.accessibility),
1774 (11, self.assemble),
1775 (12, self.print_hires),
1776 ];
1777 let mut bits: u32 = !0b11; for (bit, granted) in flags {
1779 if !granted {
1780 bits &= !(1u32 << (bit - 1));
1781 }
1782 }
1783 bits as i32
1784 }
1785}
1786
1787impl Default for Permissions {
1788 fn default() -> Permissions {
1790 Permissions::all()
1791 }
1792}
1793
1794fn aes256_encrypt_dict(material: &KeyMaterial, p: i32) -> Dict {
1800 let mut std_cf = Dict::new();
1801 std_cf.insert(
1802 Name("CFM".to_string()),
1803 Object::Name(Name("AESV3".to_string())),
1804 );
1805 std_cf.insert(Name("Length".to_string()), Object::Int(32));
1806 let mut cf = Dict::new();
1807 cf.insert(Name("StdCF".to_string()), Object::Dict(std_cf));
1808
1809 let mut dict = Dict::new();
1810 dict.insert(
1811 Name("Filter".to_string()),
1812 Object::Name(Name("Standard".to_string())),
1813 );
1814 dict.insert(Name("V".to_string()), Object::Int(5));
1815 dict.insert(Name("R".to_string()), Object::Int(6));
1816 dict.insert(Name("Length".to_string()), Object::Int(256));
1817 dict.insert(Name("CF".to_string()), Object::Dict(cf));
1818 dict.insert(
1819 Name("StmF".to_string()),
1820 Object::Name(Name("StdCF".to_string())),
1821 );
1822 dict.insert(
1823 Name("StrF".to_string()),
1824 Object::Name(Name("StdCF".to_string())),
1825 );
1826 dict.insert(Name("P".to_string()), Object::Int(i64::from(p)));
1827 dict.insert(Name("U".to_string()), Object::String(material.u.clone()));
1828 dict.insert(Name("UE".to_string()), Object::String(material.ue.clone()));
1829 dict.insert(Name("O".to_string()), Object::String(material.o.clone()));
1830 dict.insert(Name("OE".to_string()), Object::String(material.oe.clone()));
1831 dict.insert(
1832 Name("Perms".to_string()),
1833 Object::String(material.perms.clone()),
1834 );
1835 dict
1836}
1837
1838#[allow(
1843 clippy::type_complexity,
1844 reason = "Box<dyn FnMut(&mut [u8]) -> Result<()> + Send> names the one random-byte source the write path takes; a type alias would only rename it"
1845)]
1846pub struct Encryptor {
1847 file_key: [u8; 32],
1848 rng: Box<dyn FnMut(&mut [u8]) -> crate::error::Result<()> + Send>,
1849}
1850
1851impl Encryptor {
1852 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
1864 pub fn aes256(
1865 user_password: &str,
1866 owner_password: &str,
1867 permissions: Permissions,
1868 ) -> crate::error::Result<(Encryptor, Dict)> {
1869 let mut rng = |buf: &mut [u8]| fill_os_random(buf);
1870 let p = permissions.p_value();
1871 let material = r6_key_material(
1872 user_password.as_bytes(),
1873 owner_password.as_bytes(),
1874 p,
1875 true,
1876 &mut rng,
1877 )?;
1878 let dict = aes256_encrypt_dict(&material, p);
1879 let encryptor = Encryptor {
1880 file_key: material.file_key,
1881 rng: Box::new(|buf: &mut [u8]| fill_os_random(buf)),
1882 };
1883 Ok((encryptor, dict))
1884 }
1885
1886 #[allow(clippy::type_complexity, reason = "see Encryptor's rng field")]
1889 pub fn aes256_with_rng(
1890 user_password: &str,
1891 owner_password: &str,
1892 permissions: Permissions,
1893 rng: Box<dyn FnMut(&mut [u8]) + Send>,
1894 ) -> (Encryptor, Dict) {
1895 let mut rng = rng;
1896 let p = permissions.p_value();
1897 let material = match r6_key_material(
1898 user_password.as_bytes(),
1899 owner_password.as_bytes(),
1900 p,
1901 true,
1902 &mut |buf: &mut [u8]| -> std::result::Result<(), std::convert::Infallible> {
1903 rng(buf);
1904 Ok(())
1905 },
1906 ) {
1907 Ok(material) => material,
1908 Err(never) => match never {},
1909 };
1910 let dict = aes256_encrypt_dict(&material, p);
1911 let encryptor = Encryptor {
1912 file_key: material.file_key,
1913 rng: Box::new(move |buf: &mut [u8]| {
1914 rng(buf);
1915 Ok(())
1916 }),
1917 };
1918 (encryptor, dict)
1919 }
1920
1921 pub fn encrypt_object(
1930 &mut self,
1931 obj: &mut Object,
1932 num: u32,
1933 gen: u16,
1934 ) -> crate::error::Result<()> {
1935 let _ = (num, gen);
1936 encrypt_in_place(obj, &self.file_key, &mut *self.rng)
1937 }
1938}
1939
1940fn encrypt_in_place(
1945 obj: &mut Object,
1946 key: &[u8],
1947 rng: &mut dyn FnMut(&mut [u8]) -> crate::error::Result<()>,
1948) -> crate::error::Result<()> {
1949 match obj {
1950 Object::String(bytes) => *bytes = aes_cbc_encrypt(key, rng, bytes)?,
1951 Object::Array(items) => {
1952 for it in items {
1953 encrypt_in_place(it, key, &mut *rng)?;
1954 }
1955 }
1956 Object::Dict(dict) => {
1957 for v in dict.values_mut() {
1958 encrypt_in_place(v, key, &mut *rng)?;
1959 }
1960 }
1961 Object::Stream(stream) => {
1962 for v in stream.dict.values_mut() {
1963 encrypt_in_place(v, key, &mut *rng)?;
1964 }
1965 if stream_crypt_filter(&stream.dict, &|_| None).as_deref() == Some("Identity") {
1969 return Ok(());
1970 }
1971 stream.data = aes_cbc_encrypt(key, rng, &stream.data)?;
1972 }
1973 _ => {}
1974 }
1975 Ok(())
1976}
1977
1978#[rustfmt::skip]
1980const MD5_S: [u32; 64] = [
1981 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
1982 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
1983 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
1984 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
1985];
1986
1987#[rustfmt::skip]
1989const MD5_K: [u32; 64] = [
1990 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
1991 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
1992 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
1993 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
1994 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
1995 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
1996 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
1997 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
1998];
1999
2000fn md5(input: &[u8]) -> [u8; 16] {
2003 let (mut a0, mut b0, mut c0, mut d0) = (
2004 0x6745_2301u32,
2005 0xefcd_ab89u32,
2006 0x98ba_dcfeu32,
2007 0x1032_5476u32,
2008 );
2009
2010 let mut msg = input.to_vec();
2011 let bitlen = (input.len() as u64).wrapping_mul(8);
2012 msg.push(0x80);
2013 while msg.len() % 64 != 56 {
2014 msg.push(0);
2015 }
2016 msg.extend_from_slice(&bitlen.to_le_bytes());
2017
2018 for chunk in msg.as_chunks::<64>().0 {
2019 let mut m = [0u32; 16];
2020 for (word, bytes) in m.iter_mut().zip(chunk.as_chunks::<4>().0) {
2021 *word = u32::from_le_bytes(*bytes);
2022 }
2023 let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0);
2024 for i in 0..64 {
2025 let (f, g) = match i {
2026 0..=15 => ((b & c) | (!b & d), i),
2027 16..=31 => ((d & b) | (!d & c), (5 * i + 1) % 16),
2028 32..=47 => (b ^ c ^ d, (3 * i + 5) % 16),
2029 _ => (c ^ (b | !d), (7 * i) % 16),
2030 };
2031 let f = f.wrapping_add(a).wrapping_add(MD5_K[i]).wrapping_add(m[g]);
2032 a = d;
2033 d = c;
2034 c = b;
2035 b = b.wrapping_add(f.rotate_left(MD5_S[i]));
2036 }
2037 a0 = a0.wrapping_add(a);
2038 b0 = b0.wrapping_add(b);
2039 c0 = c0.wrapping_add(c);
2040 d0 = d0.wrapping_add(d);
2041 }
2042
2043 let mut out = [0u8; 16];
2044 out[0..4].copy_from_slice(&a0.to_le_bytes());
2045 out[4..8].copy_from_slice(&b0.to_le_bytes());
2046 out[8..12].copy_from_slice(&c0.to_le_bytes());
2047 out[12..16].copy_from_slice(&d0.to_le_bytes());
2048 out
2049}
2050
2051#[cfg(test)]
2052mod tests {
2053 use super::*;
2054 use crate::object::Name;
2055
2056 fn hex(bytes: &[u8]) -> String {
2057 bytes.iter().map(|b| format!("{b:02x}")).collect()
2058 }
2059
2060 #[test]
2061 fn md5_known_vectors() {
2062 assert_eq!(hex(&md5(b"")), "d41d8cd98f00b204e9800998ecf8427e");
2063 assert_eq!(hex(&md5(b"abc")), "900150983cd24fb0d6963f7d28e17f72");
2064 assert_eq!(
2065 hex(&md5(b"The quick brown fox jumps over the lazy dog")),
2066 "9e107d9d372bb6826bd81d3542a419d6"
2067 );
2068 }
2069
2070 #[test]
2071 fn md5_spans_block_boundary() {
2072 let input = [b'a'; 56];
2074 assert_eq!(hex(&md5(&input)), "3b0c8ac703f828b04c6c197006d17218");
2075 }
2076
2077 #[test]
2082 fn aes_block_known_vectors() {
2083 let plain: [u8; 16] = core::array::from_fn(|i| (i as u8) * 0x11);
2084 let key128: [u8; 16] = core::array::from_fn(|i| i as u8);
2085 let key256: [u8; 32] = core::array::from_fn(|i| i as u8);
2086
2087 type Encrypt = fn(&mut [u8; 16], &[[u8; 16]]);
2088 type Decrypt = fn(&mut [u8; 16], &[[u8; 16]], &[u8; 256]);
2089 let paths: [(Encrypt, Decrypt); 2] = [
2090 (aes_encrypt_block, aes_decrypt_block),
2091 (aes_encrypt_block_soft, aes_decrypt_block_soft),
2092 ];
2093 for (encrypt, decrypt) in paths {
2094 let mut s = plain;
2095 encrypt(&mut s, &aes_expand_key(&key128));
2096 assert_eq!(hex(&s), "69c4e0d86a7b0430d8cdb78070b4c55a");
2097 decrypt(&mut s, &aes_expand_key(&key128), &aes_inv_sbox());
2098 assert_eq!(s, plain);
2099
2100 let mut s = plain;
2101 encrypt(&mut s, &aes_expand_key(&key256));
2102 assert_eq!(hex(&s), "8ea2b7ca516745bfeafc49904b496089");
2103 decrypt(&mut s, &aes_expand_key(&key256), &aes_inv_sbox());
2104 assert_eq!(s, plain);
2105 }
2106 }
2107
2108 #[test]
2111 fn aes_cbc_round_trips_multiple_blocks() {
2112 let key: [u8; 16] = core::array::from_fn(|i| (i as u8).wrapping_mul(7));
2113 let iv: [u8; 16] = core::array::from_fn(|i| 0xa5 ^ (i as u8));
2114 let data: Vec<u8> = (0..64u8).collect();
2115 let ct = aes_cbc_encrypt_blocks(&key, &iv, &data);
2116 assert_eq!(ct.len(), data.len());
2117 assert_ne!(ct, data);
2118 assert_eq!(aes_cbc_decrypt_blocks(&key, &iv, &ct), data);
2119 }
2120
2121 #[test]
2125 fn sha2_known_vectors() {
2126 assert_eq!(
2127 hex(&sha256(b"")),
2128 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
2129 );
2130 assert_eq!(
2131 hex(&sha256(b"abc")),
2132 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
2133 );
2134 assert_eq!(
2135 hex(&sha256(&[b'a'; 200])),
2136 "c2a908d98f5df987ade41b5fce213067efbcc21ef2240212a41e54b5e7c28ae5"
2137 );
2138 assert_eq!(
2139 hex(&sha384(b"abc")),
2140 "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed\
2141 8086072ba1e7cc2358baeca134c825a7"
2142 );
2143 assert_eq!(
2144 hex(&sha512(b"abc")),
2145 "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a\
2146 2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"
2147 );
2148 assert_eq!(
2149 hex(&sha512(&[b'a'; 300])),
2150 "a6a77010dd9696c23831e6549de51724df332c2075039b75fcfe6c2e6de42fbd\
2151 3c80ed4073267e00c8c320712c3cdd9d65a96f90a3fe4a58a6b70a103be08e83"
2152 );
2153 }
2154
2155 #[test]
2159 fn sha2_soft_compressions_match_the_dispatch() {
2160 let block64: [u8; 64] = core::array::from_fn(|i| (i as u8).wrapping_mul(31));
2161 let mut via_dispatch = [0x6a09e667u32; 8];
2162 let mut via_soft = via_dispatch;
2163 sha256_compress(&mut via_dispatch, &block64);
2164 sha256_compress_soft(&mut via_soft, &block64);
2165 assert_eq!(via_dispatch, via_soft);
2166
2167 let block128: [u8; 128] = core::array::from_fn(|i| (i as u8).wrapping_mul(29));
2168 let mut via_dispatch = [0x6a09e667f3bcc908u64; 8];
2169 let mut via_soft = via_dispatch;
2170 sha512_compress(&mut via_dispatch, &block128);
2171 sha512_compress_soft(&mut via_soft, &block128);
2172 assert_eq!(via_dispatch, via_soft);
2173 }
2174
2175 #[test]
2178 fn incremental_sha256_matches_the_one_shot() {
2179 let input: Vec<u8> = (0..300u16).map(|i| (i % 251) as u8).collect();
2180 for splits in [
2181 vec![0, 1, 3, 7, 60, 63, 64, 65, 37],
2182 vec![300],
2183 vec![128, 128, 44],
2184 vec![55, 9, 236],
2185 ] {
2186 let mut hasher = Sha256::new();
2187 let mut fed = 0usize;
2188 for len in splits {
2189 hasher.update(&input[fed..fed + len]);
2190 fed += len;
2191 }
2192 hasher.update(&input[fed..]);
2193 assert_eq!(hasher.finalize(), sha256(&input));
2194 }
2195 assert_eq!(Sha256::new().finalize(), sha256(b""));
2196 assert_eq!(Sha256::default().finalize(), sha256(b""));
2197 }
2198
2199 #[test]
2200 fn rc4_known_vector() {
2201 let ct = rc4(b"Key", b"Plaintext");
2203 assert_eq!(hex(&ct), "bbf316e8d940af0ad3");
2204 assert_eq!(rc4(b"Key", &ct), b"Plaintext");
2206 }
2207
2208 const N: usize = 16; const P: i32 = -44;
2215 const ID0: &[u8] = b"0123456789abcdef";
2216
2217 fn owner_entry(owner_pw: &[u8], user_pw: &[u8]) -> Vec<u8> {
2219 owner_entry_with(N, owner_pw, user_pw)
2220 }
2221
2222 fn owner_entry_with(n: usize, owner_pw: &[u8], user_pw: &[u8]) -> Vec<u8> {
2224 let mut d = md5(&pad_password(owner_pw));
2225 for _ in 0..50 {
2226 d = md5(&d[..n]);
2227 }
2228 let rc4key = d[..n].to_vec();
2229 let mut o = rc4(&rc4key, &pad_password(user_pw));
2230 for i in 1u8..=19 {
2231 let k: Vec<u8> = rc4key.iter().map(|b| b ^ i).collect();
2232 o = rc4(&k, &o);
2233 }
2234 o
2235 }
2236
2237 fn file_key(o: &[u8], user_pw: &[u8]) -> Vec<u8> {
2239 file_key_with(N, o, user_pw)
2240 }
2241
2242 fn file_key_with(n: usize, o: &[u8], user_pw: &[u8]) -> Vec<u8> {
2244 let mut input = Vec::new();
2245 input.extend_from_slice(&pad_password(user_pw));
2246 input.extend_from_slice(o);
2247 input.extend_from_slice(&(P as u32).to_le_bytes());
2248 input.extend_from_slice(ID0);
2249 let mut d = md5(&input);
2250 for _ in 0..50 {
2251 d = md5(&d[..n]);
2252 }
2253 d[..n].to_vec()
2254 }
2255
2256 fn msg_of(doc: &crate::Document, num: u32) -> Vec<u8> {
2258 use crate::object::ObjRef;
2259 let obj = doc.get(ObjRef { num, gen: 0 }).unwrap();
2260 obj.as_dict()
2261 .unwrap()
2262 .get("Msg")
2263 .unwrap()
2264 .as_str_bytes()
2265 .unwrap()
2266 .to_vec()
2267 }
2268
2269 fn body_of(doc: &crate::Document, num: u32) -> Vec<u8> {
2271 use crate::object::ObjRef;
2272 let obj = doc.get(ObjRef { num, gen: 0 }).unwrap();
2273 doc.stream_data(obj.as_stream().unwrap()).unwrap()
2274 }
2275
2276 fn user_entry(key: &[u8]) -> Vec<u8> {
2278 let mut input = Vec::new();
2279 input.extend_from_slice(&PAD);
2280 input.extend_from_slice(ID0);
2281 let mut x = md5(&input).to_vec();
2282 x = rc4(key, &x);
2283 for i in 1u8..=19 {
2284 let k: Vec<u8> = key.iter().map(|b| b ^ i).collect();
2285 x = rc4(&k, &x);
2286 }
2287 x.resize(32, 0); x
2289 }
2290
2291 fn obj_key(key: &[u8], num: u32, gen: u16) -> Vec<u8> {
2292 let mut input = key.to_vec();
2293 input.extend_from_slice(&num.to_le_bytes()[..3]);
2294 input.extend_from_slice(&gen.to_le_bytes()[..2]);
2295 md5(&input)[..(key.len() + 5).min(16)].to_vec()
2296 }
2297
2298 fn hexstr(b: &[u8]) -> String {
2299 let mut s = String::from("<");
2300 for x in b {
2301 s.push_str(&format!("{x:02x}"));
2302 }
2303 s.push('>');
2304 s
2305 }
2306
2307 fn encrypted_fixture(u_override: Option<Vec<u8>>) -> Vec<u8> {
2308 encrypted_fixture_with(b"", b"", u_override)
2309 }
2310
2311 fn encrypted_fixture_with(
2312 user_pw: &[u8],
2313 owner_pw: &[u8],
2314 u_override: Option<Vec<u8>>,
2315 ) -> Vec<u8> {
2316 use pdfboss_testkit::PdfBuilder;
2317 let o = owner_entry(owner_pw, user_pw);
2318 let key = file_key(&o, user_pw);
2319 let u = u_override.unwrap_or_else(|| user_entry(&key));
2320
2321 let msg = rc4(&obj_key(&key, 3, 0), b"Top secret message");
2322 let stream = rc4(&obj_key(&key, 4, 0), b"decrypted stream body");
2323
2324 let mut b = PdfBuilder::new().version(1, 4);
2325 b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
2326 b.object(2, "<< /Type /Pages /Kids [] /Count 0 >>");
2327 b.object(3, &format!("<< /Msg {} >>", hexstr(&msg)));
2328 b.stream(4, "", &stream);
2329 b.object(
2330 9,
2331 &format!(
2332 "<< /Filter /Standard /V 2 /R 3 /Length 128 /P {P} /O {} /U {} >>",
2333 hexstr(&o),
2334 hexstr(&u)
2335 ),
2336 );
2337 let trailer = format!("/Encrypt 9 0 R /ID [{}{}]", hexstr(ID0), hexstr(ID0));
2338 b.trailer_extra(&trailer).build(1)
2339 }
2340
2341 #[test]
2343 fn document_load_decrypts_standard_rc4() {
2344 use crate::object::ObjRef;
2345 use crate::Document;
2346
2347 let doc = Document::load(encrypted_fixture(None)).expect("empty password opens the file");
2348
2349 let obj3 = doc.get(ObjRef { num: 3, gen: 0 }).unwrap();
2350 let msg = obj3
2351 .as_dict()
2352 .unwrap()
2353 .get("Msg")
2354 .unwrap()
2355 .as_str_bytes()
2356 .unwrap();
2357 assert_eq!(msg, b"Top secret message", "string decrypted");
2358
2359 let obj4 = doc.get(ObjRef { num: 4, gen: 0 }).unwrap();
2360 let data = doc.stream_data(obj4.as_stream().unwrap()).unwrap();
2361 assert_eq!(data, b"decrypted stream body", "stream decrypted");
2362 }
2363
2364 #[test]
2366 fn document_load_rejects_when_password_does_not_verify() {
2367 use crate::error::Error;
2368 use crate::Document;
2369
2370 let bad_u = vec![0u8; 32];
2373 let err = Document::load(encrypted_fixture(Some(bad_u)));
2374 assert!(matches!(err, Err(Error::Encrypted)));
2375 }
2376
2377 #[test]
2379 fn real_user_password_opens_an_rc4_file() {
2380 use crate::error::Error;
2381 use crate::object::ObjRef;
2382 use crate::Document;
2383
2384 let bytes = encrypted_fixture_with(b"hunter2", b"owner-secret", None);
2385 assert!(
2386 matches!(Document::load(bytes.clone()), Err(Error::Encrypted)),
2387 "without the password the file stays closed"
2388 );
2389 let doc = Document::load_with_password(bytes, "hunter2").expect("user password opens");
2390 let obj3 = doc.get(ObjRef { num: 3, gen: 0 }).unwrap();
2391 let msg = obj3.as_dict().unwrap().get("Msg").unwrap();
2392 assert_eq!(msg.as_str_bytes().unwrap(), b"Top secret message");
2393 }
2394
2395 #[test]
2397 fn owner_password_opens_an_rc4_file() {
2398 use crate::object::ObjRef;
2399 use crate::Document;
2400
2401 let bytes = encrypted_fixture_with(b"hunter2", b"owner-secret", None);
2402 let doc =
2403 Document::load_with_password(bytes, "owner-secret").expect("owner password opens");
2404 let obj3 = doc.get(ObjRef { num: 3, gen: 0 }).unwrap();
2405 let msg = obj3.as_dict().unwrap().get("Msg").unwrap();
2406 assert_eq!(msg.as_str_bytes().unwrap(), b"Top secret message");
2407 }
2408
2409 #[test]
2411 fn wrong_password_stays_encrypted() {
2412 use crate::error::Error;
2413 use crate::Document;
2414
2415 let bytes = encrypted_fixture_with(b"hunter2", b"owner-secret", None);
2416 let err = Document::load_with_password(bytes, "letmein");
2417 assert!(matches!(err, Err(Error::Encrypted)));
2418 }
2419
2420 #[test]
2422 fn real_passwords_open_an_aes256_r6_file() {
2423 use crate::error::Error;
2424 use crate::object::ObjRef;
2425 use crate::Document;
2426
2427 let bytes = encrypted_fixture_aesv3_with(6, "pässword".as_bytes(), b"owner-secret");
2428 assert!(
2429 matches!(Document::load(bytes.clone()), Err(Error::Encrypted)),
2430 "without the password the file stays closed"
2431 );
2432 for pw in ["pässword", "owner-secret"] {
2433 let doc = Document::load_with_password(bytes.clone(), pw)
2434 .unwrap_or_else(|_| panic!("{pw:?} opens the file"));
2435 let obj3 = doc.get(ObjRef { num: 3, gen: 0 }).unwrap();
2436 let msg = obj3.as_dict().unwrap().get("Msg").unwrap();
2437 assert_eq!(msg.as_str_bytes().unwrap(), b"AES-256 secret");
2438 }
2439 assert!(matches!(
2440 Document::load_with_password(bytes, "letmein"),
2441 Err(Error::Encrypted)
2442 ));
2443 }
2444
2445 #[test]
2447 fn empty_password_files_still_open_through_the_password_api() {
2448 use crate::object::ObjRef;
2449 use crate::Document;
2450
2451 let doc = Document::load_with_password(encrypted_fixture(None), "")
2455 .expect("the empty password opens through the password API too");
2456 let obj3 = doc.get(ObjRef { num: 3, gen: 0 }).unwrap();
2457 let msg = obj3.as_dict().unwrap().get("Msg").unwrap();
2458 assert_eq!(msg.as_str_bytes().unwrap(), b"Top secret message");
2459 }
2460
2461 #[test]
2463 fn unsupported_handler_is_declined() {
2464 let mut enc = Dict::new();
2467 enc.insert(Name("Filter".into()), Object::Name(Name("Standard".into())));
2468 enc.insert(Name("V".into()), Object::Int(6));
2469 enc.insert(Name("R".into()), Object::Int(7));
2470 enc.insert(Name("O".into()), Object::String(vec![0; 48]));
2471 enc.insert(Name("U".into()), Object::String(vec![0; 48]));
2472 enc.insert(Name("P".into()), Object::Int(-4));
2473 assert!(Decryptor::from_standard(&enc, ID0).is_none());
2474 }
2475
2476 #[test]
2479 fn aes_fips197_block_vectors() {
2480 let pt: [u8; 16] = [
2482 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
2483 0xee, 0xff,
2484 ];
2485 let key128: Vec<u8> = (0u8..16).collect();
2486 let rks = aes_expand_key(&key128);
2487 let mut b = pt;
2488 aes_encrypt_block(&mut b, &rks);
2489 assert_eq!(hex(&b), "69c4e0d86a7b0430d8cdb78070b4c55a");
2490 aes_decrypt_block(&mut b, &rks, &aes_inv_sbox());
2491 assert_eq!(b, pt, "AES-128 decrypt inverts encrypt");
2492
2493 let key256: Vec<u8> = (0u8..32).collect();
2494 let rks = aes_expand_key(&key256);
2495 let mut b = pt;
2496 aes_encrypt_block(&mut b, &rks);
2497 assert_eq!(hex(&b), "8ea2b7ca516745bfeafc49904b496089");
2498 }
2499
2500 #[test]
2501 fn sha2_vectors() {
2502 assert_eq!(
2503 hex(&sha256(b"abc")),
2504 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
2505 );
2506 assert_eq!(
2507 hex(&sha512(b"abc")),
2508 "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a\
2509 2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"
2510 );
2511 assert_eq!(
2512 hex(&sha384(b"abc")),
2513 "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed\
2514 8086072ba1e7cc2358baeca134c825a7"
2515 );
2516 }
2517
2518 #[test]
2519 fn aes_cbc_roundtrip() {
2520 let key: Vec<u8> = (0u8..16).collect();
2521 let iv = [0x24u8; 16];
2522 let pt = b"a message spanning several AES blocks exactly?!!";
2523 let ct = aes_cbc_encrypt_blocks(&key, &iv, &pkcs7_pad(pt));
2524 let mut val = iv.to_vec(); val.extend_from_slice(&ct);
2526 assert_eq!(aes_cbc_decrypt(&key, &val), pt);
2527 }
2528
2529 fn obj_key_aes(key: &[u8], num: u32, gen: u16) -> Vec<u8> {
2532 let mut input = key.to_vec();
2533 input.extend_from_slice(&num.to_le_bytes()[..3]);
2534 input.extend_from_slice(&gen.to_le_bytes()[..2]);
2535 input.extend_from_slice(b"sAlT");
2536 md5(&input)[..(key.len() + 5).min(16)].to_vec()
2537 }
2538
2539 fn aes_encrypt_pdf(key: &[u8], pt: &[u8], iv: &[u8; 16]) -> Vec<u8> {
2542 let mut out = iv.to_vec();
2543 out.extend_from_slice(&aes_cbc_encrypt_blocks(key, iv, &pkcs7_pad(pt)));
2544 out
2545 }
2546
2547 fn encrypted_fixture_aesv2() -> Vec<u8> {
2548 use pdfboss_testkit::PdfBuilder;
2549 let o = owner_entry(b"", b"");
2550 let key = file_key(&o, b""); let u = user_entry(&key);
2552 let iv = [0x11u8; 16];
2553 let msg = aes_encrypt_pdf(&obj_key_aes(&key, 3, 0), b"Top secret message", &iv);
2554 let stream = aes_encrypt_pdf(&obj_key_aes(&key, 4, 0), b"decrypted stream body", &iv);
2555
2556 let mut b = PdfBuilder::new().version(1, 5);
2557 b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
2558 b.object(2, "<< /Type /Pages /Kids [] /Count 0 >>");
2559 b.object(3, &format!("<< /Msg {} >>", hexstr(&msg)));
2560 b.stream(4, "", &stream);
2561 b.object(
2562 9,
2563 &format!(
2564 "<< /Filter /Standard /V 4 /R 4 /Length 128 /P {P} /O {} /U {} \
2565 /CF << /StdCF << /CFM /AESV2 /Length 16 >> >> /StmF /StdCF /StrF /StdCF >>",
2566 hexstr(&o),
2567 hexstr(&u)
2568 ),
2569 );
2570 let trailer = format!("/Encrypt 9 0 R /ID [{}{}]", hexstr(ID0), hexstr(ID0));
2571 b.trailer_extra(&trailer).build(1)
2572 }
2573
2574 #[test]
2576 fn document_load_decrypts_aesv2() {
2577 use crate::object::ObjRef;
2578 use crate::Document;
2579 let doc = Document::load(encrypted_fixture_aesv2()).expect("AESV2 empty password opens");
2580 let obj3 = doc.get(ObjRef { num: 3, gen: 0 }).unwrap();
2581 let msg = obj3
2582 .as_dict()
2583 .unwrap()
2584 .get("Msg")
2585 .unwrap()
2586 .as_str_bytes()
2587 .unwrap();
2588 assert_eq!(msg, b"Top secret message");
2589 let obj4 = doc.get(ObjRef { num: 4, gen: 0 }).unwrap();
2590 assert_eq!(
2591 doc.stream_data(obj4.as_stream().unwrap()).unwrap(),
2592 b"decrypted stream body"
2593 );
2594 }
2595
2596 fn v4_fixture(
2604 n: usize,
2605 encrypt_entries: &str,
2606 body: impl FnOnce(&mut pdfboss_testkit::PdfBuilder, &[u8]),
2607 ) -> Vec<u8> {
2608 use pdfboss_testkit::PdfBuilder;
2609 let o = owner_entry_with(n, b"", b"");
2610 let key = file_key_with(n, &o, b"");
2611 let u = user_entry(&key);
2612 let mut b = PdfBuilder::new().version(1, 5);
2613 b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
2614 b.object(2, "<< /Type /Pages /Kids [] /Count 0 >>");
2615 body(&mut b, &key);
2616 b.object(
2617 9,
2618 &format!(
2619 "<< /Filter /Standard /V 4 /R 4 /P {P} /O {} /U {} {encrypt_entries} >>",
2620 hexstr(&o),
2621 hexstr(&u)
2622 ),
2623 );
2624 let trailer = format!("/Encrypt 9 0 R /ID [{}{}]", hexstr(ID0), hexstr(ID0));
2625 b.trailer_extra(&trailer).build(1)
2626 }
2627
2628 const AESV2_CF: &str = "/CF << /StdCF << /CFM /AESV2 /Length 16 >> >>";
2629 const TWO_CF: &str =
2630 "/CF << /StdCF << /CFM /AESV2 /Length 16 >> /RcCF << /CFM /V2 /Length 16 >> >>";
2631 const IV: [u8; 16] = [0x11; 16];
2632
2633 #[test]
2637 fn identity_stream_filter_leaves_streams_as_stored() {
2638 use crate::Document;
2639 let data = v4_fixture(
2640 16,
2641 &format!("/Length 128 {AESV2_CF} /StmF /Identity /StrF /StdCF"),
2642 |b, key| {
2643 let msg = aes_encrypt_pdf(&obj_key_aes(key, 3, 0), b"Top secret message", &IV);
2644 b.object(3, &format!("<< /Msg {} >>", hexstr(&msg)));
2645 b.stream(4, "", b"stored in the clear");
2646 },
2647 );
2648 let doc = Document::load(data).expect("an Identity stream filter is a valid V4 file");
2649 assert_eq!(msg_of(&doc, 3), b"Top secret message");
2650 assert_eq!(body_of(&doc, 4), b"stored in the clear");
2651 }
2652
2653 #[test]
2656 fn string_filter_is_chosen_independently_of_the_stream_filter() {
2657 use crate::Document;
2658 let data = v4_fixture(
2659 16,
2660 &format!("/Length 128 {TWO_CF} /StmF /StdCF /StrF /RcCF"),
2661 |b, key| {
2662 let msg = rc4(&obj_key(key, 3, 0), b"Top secret message");
2663 b.object(3, &format!("<< /Msg {} >>", hexstr(&msg)));
2664 let stream =
2665 aes_encrypt_pdf(&obj_key_aes(key, 4, 0), b"decrypted stream body", &IV);
2666 b.stream(4, "", &stream);
2667 },
2668 );
2669 let doc = Document::load(data).expect("two crypt filters open");
2670 assert_eq!(msg_of(&doc, 3), b"Top secret message");
2671 assert_eq!(body_of(&doc, 4), b"decrypted stream body");
2672 }
2673
2674 #[test]
2677 fn embedded_file_filter_applies_to_embedded_file_streams() {
2678 use crate::Document;
2679 let data = v4_fixture(
2680 16,
2681 &format!("/Length 128 {TWO_CF} /StmF /StdCF /StrF /StdCF /EFF /RcCF"),
2682 |b, key| {
2683 let attached = rc4(&obj_key(key, 4, 0), b"attached file bytes");
2684 b.stream(4, "/Type /EmbeddedFile", &attached);
2685 let stream =
2686 aes_encrypt_pdf(&obj_key_aes(key, 5, 0), b"decrypted stream body", &IV);
2687 b.stream(5, "", &stream);
2688 },
2689 );
2690 let doc = Document::load(data).expect("an /EFF entry opens");
2691 assert_eq!(body_of(&doc, 4), b"attached file bytes");
2692 assert_eq!(body_of(&doc, 5), b"decrypted stream body");
2693 }
2694
2695 #[test]
2699 fn crypt_filter_length_sets_the_key_size() {
2700 use crate::Document;
2701 let data = v4_fixture(
2702 5,
2703 "/CF << /StdCF << /CFM /V2 /Length 5 >> >> /StmF /StdCF /StrF /StdCF",
2704 |b, key| {
2705 let msg = rc4(&obj_key(key, 3, 0), b"Top secret message");
2706 b.object(3, &format!("<< /Msg {} >>", hexstr(&msg)));
2707 b.stream(4, "", &rc4(&obj_key(key, 4, 0), b"decrypted stream body"));
2708 },
2709 );
2710 let doc = Document::load(data).expect("a 40-bit V4 file opens");
2711 assert_eq!(msg_of(&doc, 3), b"Top secret message");
2712 assert_eq!(body_of(&doc, 4), b"decrypted stream body");
2713 }
2714
2715 #[test]
2719 fn aesv2_always_derives_a_16_byte_object_key() {
2720 use crate::Document;
2721 let object_key = |key: &[u8], num: u32| {
2722 let mut input = key.to_vec();
2723 input.extend_from_slice(&num.to_le_bytes()[..3]);
2724 input.extend_from_slice(&[0, 0]);
2725 input.extend_from_slice(b"sAlT");
2726 md5(&input).to_vec()
2727 };
2728 let data = v4_fixture(
2729 5,
2730 "/Length 40 /CF << /StdCF << /CFM /AESV2 /Length 5 >> >> /StmF /StdCF /StrF /StdCF",
2731 |b, key| {
2732 let msg = aes_encrypt_pdf(&object_key(key, 3), b"Top secret message", &IV);
2733 b.object(3, &format!("<< /Msg {} >>", hexstr(&msg)));
2734 let stream = aes_encrypt_pdf(&object_key(key, 4), b"decrypted stream body", &IV);
2735 b.stream(4, "", &stream);
2736 },
2737 );
2738 let doc = Document::load(data).expect("a 40-bit AESV2 file opens");
2739 assert_eq!(msg_of(&doc, 3), b"Top secret message");
2740 assert_eq!(body_of(&doc, 4), b"decrypted stream body");
2741 }
2742
2743 #[test]
2748 fn a_stream_crypt_filter_naming_identity_is_left_as_stored() {
2749 use crate::Document;
2750 let data = v4_fixture(
2751 16,
2752 &format!("/Length 128 {AESV2_CF} /StmF /StdCF /StrF /StdCF"),
2753 |b, key| {
2754 b.stream(
2755 4,
2756 "/Filter /Crypt /DecodeParms << /Type /CryptFilterDecodeParms /Name /Identity >>",
2757 b"stored in the clear",
2758 );
2759 let stream =
2760 aes_encrypt_pdf(&obj_key_aes(key, 5, 0), b"decrypted stream body", &IV);
2761 b.stream(5, "", &stream);
2762 },
2763 );
2764 let doc = Document::load(data).expect("opens");
2765 assert_eq!(body_of(&doc, 4), b"stored in the clear");
2766 assert_eq!(body_of(&doc, 5), b"decrypted stream body");
2767 }
2768
2769 #[test]
2772 fn a_stream_crypt_filter_without_a_name_means_identity() {
2773 use crate::Document;
2774 let data = v4_fixture(
2775 16,
2776 &format!("/Length 128 {AESV2_CF} /StmF /StdCF /StrF /StdCF"),
2777 |b, _| {
2778 b.stream(
2779 4,
2780 "/Filter [/Crypt /ASCIIHexDecode]",
2781 b"73746F72656420617320686578>",
2782 );
2783 },
2784 );
2785 let doc = Document::load(data).expect("opens");
2786 assert_eq!(body_of(&doc, 4), b"stored as hex");
2787 }
2788
2789 #[test]
2793 fn a_stream_crypt_filter_naming_a_cf_entry_uses_the_file_key_as_is() {
2794 use crate::Document;
2795 let data = v4_fixture(
2796 16,
2797 &format!("/Length 128 {TWO_CF} /StmF /StdCF /StrF /StdCF"),
2798 |b, key| {
2799 b.stream(
2800 4,
2801 "/Filter /Crypt /DecodeParms << /Name /RcCF >>",
2802 &rc4(key, b"under the file key"),
2803 );
2804 },
2805 );
2806 let doc = Document::load(data).expect("opens");
2807 assert_eq!(body_of(&doc, 4), b"under the file key");
2808 }
2809
2810 fn indirect_crypt_fixture(
2813 stream_entries: &str,
2814 extra: &'static [(u32, &'static str)],
2815 ) -> Vec<u8> {
2816 v4_fixture(
2817 16,
2818 &format!("/Length 128 {TWO_CF} /StmF /StdCF /StrF /StdCF"),
2819 |b, key| {
2820 for (num, body) in extra {
2821 b.object(*num, body);
2822 }
2823 b.stream(4, stream_entries, &rc4(key, b"under the file key"));
2824 },
2825 )
2826 }
2827
2828 #[test]
2829 fn an_indirect_filter_naming_crypt_selects_the_named_crypt_filter() {
2830 use crate::Document;
2831 let data = indirect_crypt_fixture(
2832 "/Filter 6 0 R /DecodeParms << /Name /RcCF >>",
2833 &[(6, "/Crypt")],
2834 );
2835 let doc = Document::load(data).expect("opens");
2836 assert_eq!(body_of(&doc, 4), b"under the file key");
2837 }
2838
2839 #[test]
2840 fn an_indirect_filter_array_entry_naming_crypt_selects_the_named_crypt_filter() {
2841 use crate::Document;
2842 let data = indirect_crypt_fixture(
2843 "/Filter [6 0 R] /DecodeParms [<< /Name /RcCF >>]",
2844 &[(6, "/Crypt")],
2845 );
2846 let doc = Document::load(data).expect("opens");
2847 assert_eq!(body_of(&doc, 4), b"under the file key");
2848 }
2849
2850 #[test]
2851 fn an_indirect_filter_array_naming_crypt_selects_the_named_crypt_filter() {
2852 use crate::Document;
2853 let data = indirect_crypt_fixture(
2854 "/Filter 6 0 R /DecodeParms << /Name /RcCF >>",
2855 &[(6, "[/Crypt]")],
2856 );
2857 let doc = Document::load(data).expect("opens");
2858 assert_eq!(body_of(&doc, 4), b"under the file key");
2859 }
2860
2861 #[test]
2862 fn an_indirect_decode_parms_dictionary_selects_the_named_crypt_filter() {
2863 use crate::Document;
2864 let data = indirect_crypt_fixture(
2865 "/Filter /Crypt /DecodeParms 6 0 R",
2866 &[(6, "<< /Name /RcCF >>")],
2867 );
2868 let doc = Document::load(data).expect("opens");
2869 assert_eq!(body_of(&doc, 4), b"under the file key");
2870 }
2871
2872 #[test]
2873 fn an_indirect_name_inside_decode_parms_selects_the_named_crypt_filter() {
2874 use crate::Document;
2875 let data = indirect_crypt_fixture(
2876 "/Filter /Crypt /DecodeParms << /Name 6 0 R >>",
2877 &[(6, "/RcCF")],
2878 );
2879 let doc = Document::load(data).expect("opens");
2880 assert_eq!(body_of(&doc, 4), b"under the file key");
2881 }
2882
2883 #[test]
2884 fn an_indirect_filter_with_indirect_identity_parms_leaves_the_data_as_stored() {
2885 use crate::Document;
2886 let data = v4_fixture(
2887 16,
2888 &format!("/Length 128 {AESV2_CF} /StmF /StdCF /StrF /StdCF"),
2889 |b, _| {
2890 b.object(6, "/Crypt");
2891 b.object(7, "<< /Name /Identity >>");
2892 b.stream(
2893 4,
2894 "/Filter 6 0 R /DecodeParms 7 0 R",
2895 b"stored in the clear",
2896 );
2897 },
2898 );
2899 let doc = Document::load(data).expect("opens");
2900 assert_eq!(body_of(&doc, 4), b"stored in the clear");
2901 }
2902
2903 fn encrypted_fixture_aesv3(r: i64) -> Vec<u8> {
2906 encrypted_fixture_aesv3_with(r, b"", b"")
2907 }
2908
2909 fn encrypted_fixture_aesv3_with(r: i64, user_pw: &[u8], owner_pw: &[u8]) -> Vec<u8> {
2910 encrypted_fixture_aesv3_with_metadata(r, user_pw, owner_pw, true, None)
2911 }
2912
2913 fn encrypted_fixture_aesv3_with_metadata(
2919 r: i64,
2920 user_pw: &[u8],
2921 owner_pw: &[u8],
2922 encrypt_metadata: bool,
2923 metadata: Option<&[u8]>,
2924 ) -> Vec<u8> {
2925 use pdfboss_testkit::PdfBuilder;
2926 let key = aesv3_file_key();
2927 let iv = [0x22u8; 16];
2928 let msg = aes_encrypt_pdf(&key, b"AES-256 secret", &iv);
2929 let stream = aes_encrypt_pdf(&key, b"AES-256 stream body", &iv);
2930
2931 let mut b = PdfBuilder::new().version(1, 7);
2932 let catalog = match metadata {
2933 Some(_) => "<< /Type /Catalog /Pages 2 0 R /Metadata 5 0 R >>",
2934 None => "<< /Type /Catalog /Pages 2 0 R >>",
2935 };
2936 b.object(1, catalog);
2937 b.object(2, "<< /Type /Pages /Kids [] /Count 0 >>");
2938 b.object(3, &format!("<< /Msg {} >>", hexstr(&msg)));
2939 b.stream(4, "", &stream);
2940 if let Some(metadata) = metadata {
2941 b.stream(5, "<< /Type /Metadata /Subtype /XML >>", metadata);
2942 }
2943 let encrypt_metadata_entry = if encrypt_metadata {
2944 ""
2945 } else {
2946 " /EncryptMetadata false"
2947 };
2948 b.object(
2949 9,
2950 &format!(
2951 "<< /Filter /Standard /V 5 /R {r} /Length 256 /P {P} {}{encrypt_metadata_entry} \
2952 /CF << /StdCF << /CFM /AESV3 /Length 32 >> >> /StmF /StdCF /StrF /StdCF >>",
2953 aesv3_password_entries(r, user_pw, owner_pw, &key),
2954 ),
2955 );
2956 let trailer = format!("/Encrypt 9 0 R /ID [{}{}]", hexstr(ID0), hexstr(ID0));
2957 b.trailer_extra(&trailer).build(1)
2958 }
2959
2960 fn aesv3_file_key() -> Vec<u8> {
2962 (0u8..32).map(|i| i ^ 0x5a).collect()
2963 }
2964
2965 fn aesv3_password_entries(r: i64, user_pw: &[u8], owner_pw: &[u8], key: &[u8]) -> String {
2968 let vsalt: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
2969 let ksalt: [u8; 8] = [9, 10, 11, 12, 13, 14, 15, 16];
2970 let mut u = hash_2b(r, user_pw, &vsalt, &[]); u.extend_from_slice(&vsalt);
2972 u.extend_from_slice(&ksalt);
2973 let intermediate = hash_2b(r, user_pw, &ksalt, &[]);
2974 let ue = aes_cbc_encrypt_blocks(&intermediate, &[0u8; 16], key);
2975 let ovsalt: [u8; 8] = [21, 22, 23, 24, 25, 26, 27, 28];
2977 let oksalt: [u8; 8] = [31, 32, 33, 34, 35, 36, 37, 38];
2978 let mut o = hash_2b(r, owner_pw, &ovsalt, &u[..48]);
2979 o.extend_from_slice(&ovsalt);
2980 o.extend_from_slice(&oksalt);
2981 let ointermediate = hash_2b(r, owner_pw, &oksalt, &u[..48]);
2982 let oe = aes_cbc_encrypt_blocks(&ointermediate, &[0u8; 16], key);
2983 format!(
2984 "/U {} /UE {} /O {} /OE {}",
2985 hexstr(&u),
2986 hexstr(&ue),
2987 hexstr(&o),
2988 hexstr(&oe)
2989 )
2990 }
2991
2992 #[test]
2996 fn an_indirect_cf_dictionary_is_followed() {
2997 use crate::Document;
2998 use pdfboss_testkit::PdfBuilder;
2999 let key = aesv3_file_key();
3000 let stream = aes_encrypt_pdf(&key, b"AES-256 stream body", &[0x22u8; 16]);
3001 let mut b = PdfBuilder::new().version(1, 7);
3002 b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
3003 b.object(2, "<< /Type /Pages /Kids [] /Count 0 >>");
3004 b.stream(4, "", &stream);
3005 b.object(8, "<< /StdCF << /CFM /AESV3 /Length 32 >> >>");
3006 b.object(
3007 9,
3008 &format!(
3009 "<< /Filter /Standard /V 5 /R 6 /Length 256 /P {P} {} \
3010 /CF 8 0 R /StmF /StdCF /StrF /StdCF >>",
3011 aesv3_password_entries(6, b"", b"", &key),
3012 ),
3013 );
3014 let trailer = format!("/Encrypt 9 0 R /ID [{}{}]", hexstr(ID0), hexstr(ID0));
3015 let doc = Document::load(b.trailer_extra(&trailer).build(1))
3016 .expect("an indirect /CF still names the filters");
3017 assert_eq!(body_of(&doc, 4), b"AES-256 stream body");
3018 }
3019
3020 #[test]
3023 fn aesv3_identity_string_filter_leaves_strings_as_stored() {
3024 use crate::Document;
3025 use pdfboss_testkit::PdfBuilder;
3026 let key = aesv3_file_key();
3027 let stream = aes_encrypt_pdf(&key, b"AES-256 stream body", &[0x22u8; 16]);
3028 let mut b = PdfBuilder::new().version(1, 7);
3029 b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
3030 b.object(2, "<< /Type /Pages /Kids [] /Count 0 >>");
3031 b.object(3, "<< /Msg (stored in the clear) >>");
3032 b.stream(4, "", &stream);
3033 b.object(
3034 9,
3035 &format!(
3036 "<< /Filter /Standard /V 5 /R 6 /Length 256 /P {P} {} \
3037 /CF << /StdCF << /CFM /AESV3 /Length 32 >> >> /StmF /StdCF /StrF /Identity >>",
3038 aesv3_password_entries(6, b"", b"", &key),
3039 ),
3040 );
3041 let trailer = format!("/Encrypt 9 0 R /ID [{}{}]", hexstr(ID0), hexstr(ID0));
3042 let doc = Document::load(b.trailer_extra(&trailer).build(1))
3043 .expect("an Identity string filter is a valid V5 file");
3044 assert_eq!(msg_of(&doc, 3), b"stored in the clear");
3045 assert_eq!(body_of(&doc, 4), b"AES-256 stream body");
3046 }
3047
3048 fn assert_aesv3_decrypts(r: i64) {
3049 use crate::object::ObjRef;
3050 use crate::Document;
3051 let doc = Document::load(encrypted_fixture_aesv3(r)).expect("AESV3 empty password opens");
3052 let obj3 = doc.get(ObjRef { num: 3, gen: 0 }).unwrap();
3053 let msg = obj3
3054 .as_dict()
3055 .unwrap()
3056 .get("Msg")
3057 .unwrap()
3058 .as_str_bytes()
3059 .unwrap();
3060 assert_eq!(msg, b"AES-256 secret", "R{r} string");
3061 let obj4 = doc.get(ObjRef { num: 4, gen: 0 }).unwrap();
3062 assert_eq!(
3063 doc.stream_data(obj4.as_stream().unwrap()).unwrap(),
3064 b"AES-256 stream body",
3065 "R{r} stream"
3066 );
3067 }
3068
3069 #[test]
3071 fn document_load_decrypts_aesv3_r5() {
3072 assert_aesv3_decrypts(5);
3073 }
3074
3075 #[test]
3077 fn document_load_decrypts_aesv3_r6() {
3078 assert_aesv3_decrypts(6); }
3080
3081 #[test]
3083 fn encrypt_metadata_false_leaves_the_metadata_stream_plaintext() {
3084 use crate::object::ObjRef;
3085 use crate::Document;
3086
3087 const XMP: &[u8] = b"<?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?>\
3088 <x:xmpmeta xmlns:x='adobe:ns:meta/'><rdf:RDF \
3089 xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'><rdf:Description \
3090 xmlns:dc='http://purl.org/dc/elements/1.1/'><dc:title>XMP Secret \
3091 Title</dc:title></rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end='w'?>";
3092
3093 let bytes =
3094 encrypted_fixture_aesv3_with_metadata(6, b"user-pw", b"owner-pw", false, Some(XMP));
3095 let doc = Document::load_with_password(bytes, "user-pw").expect("user password opens");
3096
3097 let obj3 = doc.get(ObjRef { num: 3, gen: 0 }).unwrap();
3098 let msg = obj3.as_dict().unwrap().get("Msg").unwrap();
3099 assert_eq!(
3100 msg.as_str_bytes().unwrap(),
3101 b"AES-256 secret",
3102 "an ordinary string still decrypts under EncryptMetadata false"
3103 );
3104
3105 let obj5 = doc.get(ObjRef { num: 5, gen: 0 }).unwrap();
3106 let metadata = doc.stream_data(obj5.as_stream().unwrap()).unwrap();
3107 assert_eq!(
3108 metadata, XMP,
3109 "the metadata stream was stored in plaintext and must not be decrypted"
3110 );
3111 }
3112
3113 #[test]
3117 fn encrypt_in_place_reports_an_unavailable_random_source() {
3118 let mut obj = Object::String(b"secret".to_vec());
3119 let mut failing = |_: &mut [u8]| -> crate::error::Result<()> {
3120 Err(crate::error::Error::RandomUnavailable(
3121 "exhausted".to_owned(),
3122 ))
3123 };
3124 let result = encrypt_in_place(&mut obj, &[0u8; 32], &mut failing);
3125 assert!(matches!(
3126 result,
3127 Err(crate::error::Error::RandomUnavailable(_))
3128 ));
3129 }
3130
3131 #[test]
3139 fn r6_key_material_opens_under_aesv3_key() {
3140 let mut c = 0u8;
3141 let mut rng = |b: &mut [u8]| -> std::result::Result<(), std::convert::Infallible> {
3142 for x in b {
3143 c = c.wrapping_add(1);
3144 *x = c;
3145 }
3146 Ok(())
3147 };
3148 let material = match r6_key_material(b"user-pw", b"owner-pw", P, true, &mut rng) {
3149 Ok(material) => material,
3150 Err(never) => match never {},
3151 };
3152 let dict = aes256_encrypt_dict(&material, P);
3153
3154 let user_key = aesv3_key(&dict, 6, b"user-pw").expect("user password opens");
3155 assert_eq!(user_key, material.file_key.to_vec());
3156
3157 let owner_key = aesv3_key(&dict, 6, b"owner-pw").expect("owner password opens");
3158 assert_eq!(owner_key, material.file_key.to_vec());
3159
3160 assert!(aesv3_key(&dict, 6, b"wrong-pw").is_none());
3161
3162 assert!(perms_marker_valid(&material.file_key, &material.perms));
3163
3164 let mut without_perms = dict.clone();
3169 without_perms.remove("Perms");
3170 assert_eq!(
3171 aesv3_key(&without_perms, 6, b"user-pw"),
3172 Some(material.file_key.to_vec())
3173 );
3174 assert_eq!(
3175 aesv3_key(&without_perms, 6, b"owner-pw"),
3176 Some(material.file_key.to_vec())
3177 );
3178 }
3179
3180 #[test]
3183 fn permissions_all_grants_every_bit() {
3184 assert_eq!(Permissions::all().p_value(), -4);
3186 assert_eq!(Permissions::default().p_value(), -4);
3187 }
3188
3189 #[test]
3190 fn permissions_p_value_clears_exactly_its_own_bit() {
3191 let base = Permissions::all().p_value();
3192 assert_eq!(
3193 Permissions {
3194 print: false,
3195 ..Permissions::all()
3196 }
3197 .p_value(),
3198 base & !(1 << 2), );
3200 assert_eq!(
3201 Permissions {
3202 modify: false,
3203 ..Permissions::all()
3204 }
3205 .p_value(),
3206 base & !(1 << 3), );
3208 assert_eq!(
3209 Permissions {
3210 copy: false,
3211 ..Permissions::all()
3212 }
3213 .p_value(),
3214 base & !(1 << 4), );
3216 assert_eq!(
3217 Permissions {
3218 annotate: false,
3219 ..Permissions::all()
3220 }
3221 .p_value(),
3222 base & !(1 << 5), );
3224 assert_eq!(
3225 Permissions {
3226 fill_forms: false,
3227 ..Permissions::all()
3228 }
3229 .p_value(),
3230 base & !(1 << 8), );
3232 assert_eq!(
3233 Permissions {
3234 accessibility: false,
3235 ..Permissions::all()
3236 }
3237 .p_value(),
3238 base & !(1 << 9), );
3240 assert_eq!(
3241 Permissions {
3242 assemble: false,
3243 ..Permissions::all()
3244 }
3245 .p_value(),
3246 base & !(1 << 10), );
3248 assert_eq!(
3249 Permissions {
3250 print_hires: false,
3251 ..Permissions::all()
3252 }
3253 .p_value(),
3254 base & !(1 << 11), );
3256 }
3257
3258 #[allow(clippy::type_complexity, reason = "see Encryptor's rng field")]
3264 fn counter_rng() -> Box<dyn FnMut(&mut [u8]) + Send> {
3265 let mut c = 0u8;
3266 Box::new(move |buf: &mut [u8]| {
3267 for b in buf {
3268 c = c.wrapping_add(1);
3269 *b = c;
3270 }
3271 })
3272 }
3273
3274 fn decryptor_for(dict: &Dict, password: &[u8]) -> Decryptor {
3279 let key = aesv3_key(dict, 6, password).expect("password opens the produced dict");
3280 Decryptor {
3281 key,
3282 filters: CryptFilters::uniform(Cipher::Aesv3),
3283 encrypt_metadata: true,
3284 }
3285 }
3286
3287 #[test]
3288 fn encrypt_object_round_trips_dict_array_and_leaves_other_types_untouched() {
3289 use crate::object::ObjRef;
3290
3291 let (mut enc, dict) =
3292 Encryptor::aes256_with_rng("user-pw", "owner-pw", Permissions::all(), counter_rng());
3293
3294 let mut d = Dict::new();
3295 d.insert(
3296 Name("Msg".to_string()),
3297 Object::String(b"Top secret message".to_vec()),
3298 );
3299 d.insert(
3300 Name("List".to_string()),
3301 Object::Array(vec![
3302 Object::String(b"first".to_vec()),
3303 Object::String(b"second".to_vec()),
3304 ]),
3305 );
3306 d.insert(
3307 Name("Ref".to_string()),
3308 Object::Ref(ObjRef { num: 7, gen: 0 }),
3309 );
3310 d.insert(
3311 Name("Kind".to_string()),
3312 Object::Name(Name("Example".to_string())),
3313 );
3314 d.insert(Name("Count".to_string()), Object::Int(42));
3315 d.insert(Name("Scale".to_string()), Object::Real(1.5));
3316 d.insert(Name("On".to_string()), Object::Bool(true));
3317 d.insert(Name("Missing".to_string()), Object::Null);
3318 let original = Object::Dict(d);
3319
3320 let mut obj = original.clone();
3321 enc.encrypt_object(&mut obj, 3, 0).unwrap();
3322 assert_ne!(obj, original, "encryption must change the strings");
3323
3324 let (enc_dict, orig_dict) = (obj.as_dict().unwrap(), original.as_dict().unwrap());
3327 for key in ["Ref", "Kind", "Count", "Scale", "On", "Missing"] {
3328 assert_eq!(
3329 enc_dict.get(key),
3330 orig_dict.get(key),
3331 "{key} passes through untouched"
3332 );
3333 }
3334
3335 let decryptor = decryptor_for(&dict, b"user-pw");
3336 let mut roundtripped = obj.clone();
3337 decryptor.decrypt_object(&mut roundtripped, 3, 0);
3338 assert_eq!(roundtripped, original);
3339
3340 let owner_decryptor = decryptor_for(&dict, b"owner-pw");
3342 let mut via_owner = obj;
3343 owner_decryptor.decrypt_object(&mut via_owner, 3, 0);
3344 assert_eq!(via_owner, original);
3345 }
3346
3347 #[test]
3348 fn encrypt_object_round_trips_a_stream_and_its_dict() {
3349 use crate::object::Stream;
3350
3351 let (mut enc, dict) =
3352 Encryptor::aes256_with_rng("", "owner-pw", Permissions::all(), counter_rng());
3353
3354 let mut stream_dict = Dict::new();
3355 stream_dict.insert(
3356 Name("Producer".to_string()),
3357 Object::String(b"pdfboss".to_vec()),
3358 );
3359 let original = Object::Stream(Stream {
3360 dict: stream_dict,
3361 data: b"decrypted stream body".to_vec(),
3362 });
3363 let mut obj = original.clone();
3364 enc.encrypt_object(&mut obj, 4, 0).unwrap();
3365 let encrypted = obj.as_stream().unwrap();
3366 assert_ne!(encrypted.data, original.as_stream().unwrap().data);
3367 assert_ne!(
3368 encrypted.dict.get("Producer"),
3369 original.as_stream().unwrap().dict.get("Producer"),
3370 "the stream dict's own strings are encrypted too"
3371 );
3372
3373 let decryptor = decryptor_for(&dict, b"");
3374 let mut roundtripped = obj;
3375 decryptor.decrypt_object(&mut roundtripped, 4, 0);
3376 assert_eq!(roundtripped, original);
3377 }
3378
3379 #[test]
3383 fn encrypt_object_leaves_an_identity_crypt_stream_as_stored() {
3384 use crate::object::Stream;
3385
3386 let (mut enc, dict) =
3387 Encryptor::aes256_with_rng("", "owner-pw", Permissions::all(), counter_rng());
3388 let mut stream_dict = Dict::new();
3389 stream_dict.insert(
3390 Name("Filter".to_string()),
3391 Object::Name(Name("Crypt".to_string())),
3392 );
3393 let mut parms = Dict::new();
3394 parms.insert(
3395 Name("Name".to_string()),
3396 Object::Name(Name("Identity".to_string())),
3397 );
3398 stream_dict.insert(Name("DecodeParms".to_string()), Object::Dict(parms));
3399 let original = Object::Stream(Stream {
3400 dict: stream_dict,
3401 data: b"<?xpacket?> metadata in the clear".to_vec(),
3402 });
3403
3404 let mut obj = original.clone();
3405 enc.encrypt_object(&mut obj, 6, 0).unwrap();
3406 assert_eq!(obj, original, "an Identity stream is written as stored");
3407
3408 let decryptor = decryptor_for(&dict, b"");
3409 decryptor.decrypt_object(&mut obj, 6, 0);
3410 assert_eq!(obj, original, "and read back as stored");
3411 }
3412
3413 #[test]
3414 fn encrypt_object_round_trips_padding_edge_lengths() {
3415 let (mut enc, dict) =
3416 Encryptor::aes256_with_rng("pw", "owner", Permissions::all(), counter_rng());
3417 let decryptor = decryptor_for(&dict, b"pw");
3418
3419 for plaintext in [Vec::new(), vec![0x41], vec![0x42; 16]] {
3420 let original = Object::String(plaintext.clone());
3421 let mut obj = original.clone();
3422 enc.encrypt_object(&mut obj, 1, 0).unwrap();
3423 let mut roundtripped = obj;
3424 decryptor.decrypt_object(&mut roundtripped, 1, 0);
3425 assert_eq!(roundtripped, original, "{} bytes", plaintext.len());
3426 }
3427 }
3428}