laminapdf-cos 0.9.0

Read PDF files in Rust, broken ones included: the cross-reference table with repair, object streams, decryption and the page tree, plus an overlay that records edits.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! The standard security handler on the reading side (ISO 32000-2 §7.6; research ch. 04 §7):
//! parses `/Encrypt`, authenticates the password and decrypts strings and streams as objects
//! are loaded. Read only: writing encrypted files is full-editor E11.

use std::collections::BTreeMap;
use std::ops::BitAnd;

use laminapdf_syntax::crypt::{self, Cipher, Entropy, FileKey, Handler, PasswordKind, Permissions, StandardSecurity};
use laminapdf_syntax::{Dict, Object, PdfString, Stream};

use crate::error::{Error, Result};

/// What a document's encryption is, from its `/Encrypt` dictionary
/// ([`Document::encryption`](crate::Document::encryption)).
///
/// Added in 0.2.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Encryption {
    /// `/V`: the algorithm version (1, 2, 4 or 5).
    pub version: u8,
    /// `/R`: the standard security handler revision (2–6). R5 is Adobe Extension Level 3's
    /// handler, never standardised and read only.
    pub revision: u8,
    /// The cipher strings use (`/StrF`; RC4 for V1/V2).
    pub string_cipher: Cipher,
    /// The default cipher streams use (`/StmF`; RC4 for V1/V2).
    pub stream_cipher: Cipher,
    /// The cipher embedded-file streams use (`/EFF`, default `/StmF`).
    pub embedded_file_cipher: Cipher,
    /// The file key length in bits (40–128 for R2–R4, 256 for R5/R6).
    pub key_bits: u16,
    /// `/EncryptMetadata` (V4+; always true before V4): whether the XMP metadata stream is
    /// encrypted.
    pub encrypt_metadata: bool,
}

/// The password a handler is unlocked with: the one an open was given (user or owner, the empty
/// user password when none), or one given as the owner password only.
#[derive(Debug, Clone, Copy)]
pub(crate) enum Password<'a> {
    /// As [`crypt::authenticate`] tries it.
    Any(Option<&'a [u8]>),
    /// As [`crypt::authenticate_owner`] tries it.
    Owner(&'a [u8]),
}

/// An authenticated standard security handler.
#[derive(Debug, Clone)]
pub(crate) struct Security {
    key: FileKey,
    info: Encryption,
    permissions: Permissions,
    matched: PasswordKind,
    perms_valid: Option<bool>,
    /// Named crypt filters from `/CF`, for per-stream `/Crypt` filters.
    filters: NamedFilters,
    /// The object number of an indirect `/Encrypt` dictionary, which is never decrypted.
    encrypt_object: Option<u32>,
    /// The `/Encrypt` dictionary as stored (references resolved), which a save that keeps the
    /// protection writes again.
    dict: Dict,
    /// The `/ID[0]` the handler was unlocked with: empty when the file has no `/ID` array that
    /// starts with a string.
    id0: Vec<u8>,
}

pub(crate) fn invalid(message: &'static str) -> Error {
    Error::InvalidStructure {
        kind: "encryption dictionary",
        message,
    }
}

fn string<'d>(dict: &'d Dict, key: &str) -> Option<&'d [u8]> {
    match dict.get(key) {
        Some(Object::String(s)) => Some(&s.bytes),
        _ => None,
    }
}

/// The cipher of a `/CF` entry's `/CFM` (ISO 32000-2 Table 25).
fn cipher_of(filter: &Dict) -> Result<Cipher> {
    match filter.get_name("CFM") {
        None | Some(b"None") => Ok(Cipher::Identity),
        Some(b"V2") => Ok(Cipher::Rc4),
        Some(b"AESV2") => Ok(Cipher::Aes128),
        Some(b"AESV3") => Ok(Cipher::Aes256),
        Some(other) => Err(Error::UnsupportedSecurityHandler {
            filter: format!("Standard /CFM /{}", String::from_utf8_lossy(other)),
            version: None,
            revision: None,
        }),
    }
}

/// `/V` and `/R` of a standard security handler Lamina PDF can read: V1/V2 with R2/R3, V4 with R4,
/// V5 with R5/R6.
fn handler_revision(encrypt: &Dict) -> Result<(i64, u8)> {
    let version = encrypt.get_int("V").unwrap_or(0);
    let revision = encrypt.get_int("R");
    let unsupported = |filter: String| Error::UnsupportedSecurityHandler {
        filter,
        version: Some(version),
        revision,
    };
    match encrypt.get_name("Filter") {
        Some(b"Standard") => {}
        Some(other) => return Err(unsupported(String::from_utf8_lossy(other).into_owned())),
        None => return Err(unsupported(String::new())),
    }
    let ((1 | 2, Some(r @ (2 | 3))) | (4, Some(r @ 4)) | (5, Some(r @ (5 | 6)))) = (version, revision) else {
        return Err(unsupported("Standard".to_owned()));
    };
    let r = u8::try_from(r).map_err(|_| unsupported("Standard".to_owned()))?;
    Ok((version, r))
}

/// Crypt filters by name (`/CF`).
type NamedFilters = BTreeMap<Vec<u8>, Cipher>;

/// Named crypt filters (`/CF`) and the string, stream and embedded-file ciphers (`/StrF`, `/StmF`,
/// `/EFF`; default `/Identity`, `/EFF` defaulting to `/StmF`). Before V4 everything is RC4.
fn crypt_filters(encrypt: &Dict, version: i64) -> Result<(NamedFilters, Cipher, Cipher, Cipher)> {
    let mut filters = BTreeMap::new();
    if version < 4 {
        return Ok((filters, Cipher::Rc4, Cipher::Rc4, Cipher::Rc4));
    }
    if let Some(Object::Dict(cf)) = encrypt.get("CF") {
        for (name, filter) in cf.iter() {
            if let Object::Dict(filter) = filter {
                filters.insert(name.as_bytes().to_vec(), cipher_of(filter)?);
            }
        }
    }
    let pick = |key: &str, default: Cipher| -> Result<Cipher> {
        match encrypt.get_name(key) {
            None => Ok(default),
            Some(b"Identity") => Ok(Cipher::Identity),
            Some(name) => filters
                .get(name)
                .copied()
                .ok_or_else(|| invalid("crypt filter not in /CF")),
        }
    };
    let stream = pick("StmF", Cipher::Identity)?;
    let string = pick("StrF", Cipher::Identity)?;
    let embedded = pick("EFF", stream)?;
    Ok((filters, string, stream, embedded))
}

/// A key length in bytes from a `/Length` value: bits (40–128, a multiple of 8; Table 20), or
/// bytes for the few writers (and the standard handler's crypt filters, Table 25 in practice)
/// that store bytes.
fn length_in_bytes(length: i64) -> Option<usize> {
    match length {
        bits @ 40..=128 if bits % 8 == 0 => usize::try_from(bits / 8).ok(),
        bytes @ 5..=16 => usize::try_from(bytes).ok(),
        _ => None,
    }
}

/// The R2–R4 file key length in bytes. V1: 40 bits. V2/V3: `/Length`, default 40 bits
/// (Table 20). V4: `/Length` of the crypt filter streams use (else strings use) in `/CF`,
/// default 128 bits, as pdf.js and pypdf read it (Table 25; qpdf 12 reads the top-level
/// `/Length` instead, which Table 20 defines for V2/V3 only, and is used here as a fallback).
fn key_length(encrypt: &Dict, version: i64) -> usize {
    let length = if version >= 4 {
        let cf = match encrypt.get("CF") {
            Some(Object::Dict(cf)) => Some(cf),
            _ => None,
        };
        ["StmF", "StrF"]
            .iter()
            .filter_map(|key| encrypt.get_name(key))
            .find(|name| *name != b"Identity")
            .and_then(|name| cf?.iter().find(|(k, _)| k.as_bytes() == name))
            .and_then(|(_, filter)| filter.as_dict()?.get_int("Length"))
            .or_else(|| encrypt.get_int("Length"))
    } else if version >= 2 {
        encrypt.get_int("Length")
    } else {
        None
    };
    length
        .and_then(length_in_bytes)
        .unwrap_or(if version >= 4 { 16 } else { 5 })
}

impl Security {
    /// Parses `encrypt` (references already resolved) and authenticates `password`, or the
    /// empty password when none is given (ISO 32000-2 §7.6.4.4).
    ///
    /// # Errors
    /// [`Error::UnsupportedSecurityHandler`] for a handler other than `/Standard`, an unknown
    /// `/V`/`/R` or crypt filter method; [`Error::InvalidStructure`] for missing or malformed
    /// entries; [`Error::PasswordRequired`] when no password was given and the empty one does not
    /// open the file; [`Error::WrongPassword`] when the given one is neither the user nor the
    /// owner password.
    pub(crate) fn unlock(
        encrypt: &Dict,
        encrypt_object: Option<u32>,
        id0: &[u8],
        password: Password<'_>,
        known: Option<&Security>,
    ) -> Result<Self> {
        let (password, owner_only) = match password {
            Password::Any(password) => (password, false),
            Password::Owner(password) => (Some(password), true),
        };
        let (version, r) = handler_revision(encrypt)?;
        let modern = r >= 5;

        let key_length = if modern { 32 } else { key_length(encrypt, version) };
        let need = if modern { 48 } else { 32 };
        let owner = string(encrypt, "O")
            .filter(|o| o.len() >= need)
            .ok_or_else(|| invalid("bad /O"))?;
        let user = string(encrypt, "U")
            .filter(|u| u.len() >= need)
            .ok_or_else(|| invalid("bad /U"))?;
        // R5/R6: the user password unwraps the file key from `/UE`, the owner password from
        // `/OE` (Algorithm 2.A), so a missing or short one only matters when no password
        // opens the file without it, as in pdf.js and PDFium.
        let wrapped_key = |key: &str| string(encrypt, key).filter(|v| v.len() >= 32);
        let (owner_encryption, user_encryption) = if modern {
            (wrapped_key("OE"), wrapped_key("UE"))
        } else {
            (Some(&[][..]), Some(&[][..]))
        };
        let p = encrypt.get_int("P").ok_or_else(|| invalid("missing /P"))?;
        let permissions = Permissions::new(p, r);
        let encrypt_metadata = version < 4 || !matches!(encrypt.get("EncryptMetadata"), Some(Object::Bool(false)));

        let (filters, string_cipher, stream_cipher, embedded_file_cipher) = crypt_filters(encrypt, version)?;

        let sec = StandardSecurity {
            revision: r,
            key_length,
            owner,
            user,
            owner_encryption: owner_encryption.unwrap_or_default(),
            user_encryption: user_encryption.unwrap_or_default(),
            perms: string(encrypt, "Perms"),
            permissions: permissions.raw(),
            id0,
            encrypt_metadata,
        };
        // A save's own output opens with the key the writer encrypted it under, and keeps what
        // that key's handler already established: who opened it, its permissions and whether
        // `/Perms` agreed. Read from the output again, an edited `/P` kept through the save would
        // pass for a new, unchecked one.
        let (key, matched, perms_valid) = if let Some(known) = known {
            (known.key.clone(), known.matched, known.perms_valid)
        } else {
            let authenticate = if owner_only {
                crypt::authenticate_owner
            } else {
                crypt::authenticate
            };
            let auth = authenticate(&sec, password.unwrap_or_default()).ok_or_else(|| {
                if user_encryption.is_none() {
                    invalid("bad /UE")
                } else if owner_encryption.is_none() {
                    invalid("bad /OE")
                } else if password.is_some() {
                    Error::WrongPassword
                } else {
                    Error::PasswordRequired
                }
            })?;
            (auth.key, auth.matched, auth.perms_valid)
        };
        let key_bits = u16::try_from(key.bits()).unwrap_or(u16::MAX);
        Ok(Self {
            key,
            info: Encryption {
                version: u8::try_from(version).unwrap_or_default(),
                revision: r,
                string_cipher,
                stream_cipher,
                embedded_file_cipher,
                key_bits,
                encrypt_metadata,
            },
            permissions: known.map_or(permissions, |k| k.permissions),
            matched,
            perms_valid,
            filters,
            encrypt_object,
            dict: encrypt.clone(),
            id0: id0.to_vec(),
        })
    }

    /// This handler unlocked again from the `/Encrypt` dictionary and `/ID[0]` it was unlocked
    /// with, by `password` as the owner password only: nothing is read from the file again, so
    /// no warning is raised and a repaired trailer can't change the answer.
    ///
    /// # Errors
    /// As [`Security::unlock`]: [`Error::WrongPassword`] when `password` isn't the owner's.
    pub(crate) fn unlock_owner(&self, password: &[u8]) -> Result<Self> {
        Self::unlock(
            &self.dict,
            self.encrypt_object,
            &self.id0,
            Password::Owner(password),
            None,
        )
    }

    pub(crate) const fn info(&self) -> &Encryption {
        &self.info
    }

    pub(crate) const fn permissions(&self) -> Permissions {
        self.permissions
    }

    pub(crate) const fn matched(&self) -> PasswordKind {
        self.matched
    }

    /// False when R5/R6 `/Perms` did not match `/P` (raised as `perms-mismatch`).
    pub(crate) fn perms_valid(&self) -> bool {
        self.perms_valid != Some(false)
    }

    /// Whether whoever opened the file may change or remove its protection (E11 plan §2.2): it
    /// was opened with the owner password, or with a user password whose `/P` grants every
    /// defined permission and, for R5/R6, a `/Perms` entry that is present and agrees with that
    /// `/P` (ISO 32000-2 §7.6.4.4 requires it for R6). This stops a `/P` edited by hand; it can't
    /// stop a holder of the user password, who has the file key and can forge a matching
    /// `/Perms` (research 04 §7.5).
    pub(crate) fn may_change(&self) -> bool {
        let everything = Permissions::new(-1, self.info.revision).bits();
        self.granted(|p| p.bits() == everything)
    }

    /// Whether whoever opened the file may copy its content into any other document: the
    /// owner, or a user whose `/P` grants copying (bit 5, [`Permissions::extract`]) under the
    /// rules of [`Security::granted`]. Fixed to bit 5, so no caller can ask for a weaker one.
    pub(crate) fn may_copy_out(&self) -> bool {
        self.granted(Permissions::extract)
    }

    /// Whether whoever opened the file holds what `granted` asks of the permissions: always
    /// with the owner password; with a user password only when `granted` holds for `/P` and,
    /// for R5/R6, `/Perms` is present and agrees with that `/P`. Fails closed otherwise.
    fn granted(&self, granted: impl FnOnce(&Permissions) -> bool) -> bool {
        match self.matched {
            PasswordKind::Owner => true,
            PasswordKind::User => {
                let perms_checked = self.info.revision < 5 || self.perms_valid == Some(true);
                perms_checked && granted(&self.permissions)
            }
        }
    }

    /// Records that `other`, the same handler unlocked again with another password, was
    /// unlocked with the owner password under the same file key: what an owner password given
    /// after opening proves. A user password, or an owner entry that unlocks a different key
    /// (a crafted file), changes nothing.
    ///
    /// # Errors
    /// [`Error::WrongPassword`] when `other` was unlocked with the user password;
    /// [`Error::InvalidStructure`] when its key differs.
    pub(crate) fn confirm_owner(&mut self, other: &Self) -> Result<()> {
        if other.matched != PasswordKind::Owner {
            return Err(Error::WrongPassword);
        }
        if other.key != self.key {
            return Err(invalid("the owner password unlocks a different file key"));
        }
        self.matched = PasswordKind::Owner;
        Ok(())
    }

    /// Decrypts object `num gen` in place: its strings, and for a stream its data (ISO 32000-2
    /// §7.6.2). `resolve` dereferences an indirect `/DecodeParms` of a `/Crypt` filter.
    ///
    /// Exempt (never decrypted): the `/Encrypt` dictionary itself, cross-reference streams, the
    /// XMP metadata stream when `/EncryptMetadata` is false, and a signature dictionary's
    /// `/Contents`. Members of object streams are not passed here at all: their container was
    /// decrypted as a whole. Returns false when some AES data was malformed (kept, see
    /// [`crypt::Decrypted::well_formed`]).
    pub(crate) fn decrypt_object(
        &self,
        obj: &mut Object,
        num: u32,
        gen_nr: u16,
        resolve: &mut dyn FnMut(&Object) -> Option<Object>,
    ) -> bool {
        if self.encrypt_object == Some(num) {
            return true;
        }
        match obj {
            Object::Stream(stream) => {
                if stream.dict.get_name("Type") == Some(b"XRef") {
                    return true;
                }
                let mut ok = self.decrypt_strings_in_dict(&mut stream.dict, num, gen_nr);
                let cipher = self.stream_cipher(stream, resolve);
                let out = crypt::decrypt(cipher, &self.key, num, gen_nr, &stream.data);
                ok &= out.well_formed;
                stream.data = out.data;
                ok
            }
            other => self.decrypt_strings(other, num, gen_nr),
        }
    }

    /// The cipher for `stream`: a leading `/Crypt` filter's `/Name` (default `/Identity`;
    /// ISO 32000-2 §7.4.10), else `/EFF` for embedded files, else `/StmF`; plaintext for XMP
    /// metadata when `/EncryptMetadata` is false. A `/Name` missing from `/CF` falls back to
    /// `/StmF`.
    fn stream_cipher(&self, stream: &Stream, resolve: &mut dyn FnMut(&Object) -> Option<Object>) -> Cipher {
        let dict = &stream.dict;
        if !self.info.encrypt_metadata && dict.get_name("Type") == Some(b"Metadata") {
            return Cipher::Identity;
        }
        let deref = |o: &Object, resolve: &mut dyn FnMut(&Object) -> Option<Object>| match o {
            Object::Ref(_) => resolve(o),
            other => Some(other.clone()),
        };
        let filter = dict.get("Filter").and_then(|f| deref(f, resolve));
        let first = match &filter {
            Some(Object::Name(n)) => Some(n.as_bytes()),
            Some(Object::Array(items)) => match items.first() {
                Some(Object::Name(n)) => Some(n.as_bytes()),
                _ => None,
            },
            _ => None,
        };
        if first == Some(b"Crypt") {
            let parms = dict.get("DecodeParms").and_then(|p| deref(p, resolve));
            let parms = match parms {
                Some(Object::Array(items)) => items.first().and_then(|p| deref(p, resolve)),
                other => other,
            };
            let name = match parms {
                Some(Object::Dict(d)) => d.get_name("Name").map(<[u8]>::to_vec),
                _ => None,
            };
            return match name.as_deref() {
                None | Some(b"Identity") => Cipher::Identity,
                Some(name) => self.filters.get(name).copied().unwrap_or(self.info.stream_cipher),
            };
        }
        if dict.get_name("Type") == Some(b"EmbeddedFile") {
            return self.info.embedded_file_cipher;
        }
        self.info.stream_cipher
    }

    fn decrypt_strings(&self, obj: &mut Object, num: u32, gen_nr: u16) -> bool {
        match obj {
            Object::String(s) => {
                let out = crypt::decrypt(self.info.string_cipher, &self.key, num, gen_nr, &s.bytes);
                s.bytes = out.data;
                out.well_formed
            }
            // Every item is decrypted (no short-circuit); the result says whether all were well-formed.
            Object::Array(items) => items
                .iter_mut()
                .map(|item| self.decrypt_strings(item, num, gen_nr))
                .fold(true, BitAnd::bitand),
            Object::Dict(dict) => self.decrypt_strings_in_dict(dict, num, gen_nr),
            Object::Stream(stream) => self.decrypt_strings_in_dict(&mut stream.dict, num, gen_nr),
            Object::Null
            | Object::Bool(_)
            | Object::Integer(_)
            | Object::Real(_)
            | Object::Name(_)
            | Object::Ref(_) => true,
        }
    }

    fn decrypt_strings_in_dict(&self, dict: &mut Dict, num: u32, gen_nr: u16) -> bool {
        let signature = is_signature(dict);
        dict.iter_mut()
            .filter(|(key, _)| !(signature && key.as_bytes() == b"Contents"))
            .map(|(_, value)| self.decrypt_strings(value, num, gen_nr))
            .fold(true, BitAnd::bitand)
    }
}

impl Security {
    /// Encrypts object `num gen` in place, the inverse of [`Security::decrypt_object`] and exempt
    /// the same way: the `/Encrypt` dictionary, cross-reference streams, the XMP metadata stream
    /// when `/EncryptMetadata` is false, and a signature dictionary's `/Contents`. `false` when
    /// some string or stream could not be encrypted (a key of the wrong length); the object
    /// is then partly changed and must not be written.
    fn encrypt_object(
        &self,
        obj: &mut Object,
        num: u32,
        gen_nr: u16,
        entropy: &mut dyn Entropy,
        resolve: &mut dyn FnMut(&Object) -> Option<Object>,
    ) -> bool {
        if self.encrypt_object == Some(num) {
            return true;
        }
        match obj {
            Object::Stream(stream) => {
                if stream.dict.get_name("Type") == Some(b"XRef") {
                    return true;
                }
                let mut ok = self.encrypt_strings_in_dict(&mut stream.dict, num, gen_nr, entropy);
                let cipher = self.stream_cipher(stream, resolve);
                match crypt::encrypt(cipher, &self.key, num, gen_nr, entropy, &stream.data) {
                    Some(data) => stream.data = data,
                    None => ok = false,
                }
                ok
            }
            other => self.encrypt_strings(other, num, gen_nr, entropy),
        }
    }

    fn encrypt_strings(&self, obj: &mut Object, num: u32, gen_nr: u16, entropy: &mut dyn Entropy) -> bool {
        match obj {
            Object::String(s) => {
                match crypt::encrypt(self.info.string_cipher, &self.key, num, gen_nr, entropy, &s.bytes) {
                    Some(bytes) => {
                        s.bytes = bytes;
                        true
                    }
                    None => false,
                }
            }
            Object::Array(items) => items
                .iter_mut()
                .map(|item| self.encrypt_strings(item, num, gen_nr, entropy))
                .fold(true, BitAnd::bitand),
            Object::Dict(dict) => self.encrypt_strings_in_dict(dict, num, gen_nr, entropy),
            Object::Stream(stream) => self.encrypt_strings_in_dict(&mut stream.dict, num, gen_nr, entropy),
            Object::Null
            | Object::Bool(_)
            | Object::Integer(_)
            | Object::Real(_)
            | Object::Name(_)
            | Object::Ref(_) => true,
        }
    }

    fn encrypt_strings_in_dict(&self, dict: &mut Dict, num: u32, gen_nr: u16, entropy: &mut dyn Entropy) -> bool {
        let signature = is_signature(dict);
        dict.iter_mut()
            .filter(|(key, _)| !(signature && key.as_bytes() == b"Contents"))
            .map(|(_, value)| self.encrypt_strings(value, num, gen_nr, entropy))
            .fold(true, BitAnd::bitand)
    }
}

/// How a save writes a document's strings and streams encrypted: the file key and the ciphers
/// of a security handler, and the `/Encrypt` dictionary that describes them. Made from a new
/// handler ([`Encryptor::new_r6`]) or from the handler an open document was unlocked with
/// ([`Document::encryptor`](crate::Document::encryptor)), which a save that keeps the
/// protection reuses without asking for the password again.
///
/// The key is never printed.
///
/// Added in 0.7.0.
#[derive(Debug, Clone)]
pub struct Encryptor {
    security: Security,
}

impl Encryptor {
    /// The encryptor for a new AES-256 handler (`/V 5 /R 6`, crypt filter `/StdCF` `AESV3` for
    /// strings and streams), as [`crypt::new_handler`] made it.
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub fn new_r6(handler: &Handler) -> Self {
        let p = i32::from_ne_bytes(handler.permissions.to_ne_bytes());
        let filter: Dict = [
            ("AuthEvent", Object::name("DocOpen")),
            ("CFM", Object::name("AESV3")),
            ("Length", Object::from(32)),
        ]
        .into_iter()
        .collect();
        let cf: Dict = [("StdCF", Object::Dict(filter))].into_iter().collect();
        let bytes = |data: &[u8]| Object::String(PdfString::hex(data.to_vec()));
        let mut dict = Dict::new();
        dict.insert("Filter", Object::name("Standard"));
        dict.insert("V", Object::from(5));
        dict.insert("R", Object::from(6));
        dict.insert("Length", Object::from(256));
        dict.insert("CF", Object::Dict(cf));
        dict.insert("StmF", Object::name("StdCF"));
        dict.insert("StrF", Object::name("StdCF"));
        dict.insert("O", bytes(&handler.owner));
        dict.insert("U", bytes(&handler.user));
        dict.insert("OE", bytes(&handler.owner_encryption));
        dict.insert("UE", bytes(&handler.user_encryption));
        dict.insert("P", Object::from(i64::from(p)));
        dict.insert("Perms", bytes(&handler.perms));
        dict.insert("EncryptMetadata", Object::Bool(handler.encrypt_metadata));
        Self {
            security: Security {
                key: handler.key.clone(),
                info: Encryption {
                    version: 5,
                    revision: 6,
                    string_cipher: Cipher::Aes256,
                    stream_cipher: Cipher::Aes256,
                    embedded_file_cipher: Cipher::Aes256,
                    key_bits: 256,
                    encrypt_metadata: handler.encrypt_metadata,
                },
                permissions: Permissions::new(i64::from(p), 6),
                matched: PasswordKind::Owner,
                perms_valid: Some(true),
                filters: BTreeMap::from([(b"StdCF".to_vec(), Cipher::Aes256)]),
                encrypt_object: None,
                dict,
                // R6 keys don't depend on `/ID`; the output's handler is read with it on rebase.
                id0: Vec::new(),
            },
        }
    }

    pub(crate) const fn security(&self) -> &Security {
        &self.security
    }

    pub(crate) fn keep(security: &Security) -> Self {
        let mut security = security.clone();
        // The base's `/Encrypt` number names whatever object the rewrite gives it.
        security.encrypt_object = None;
        Self { security }
    }

    /// The `/Encrypt` dictionary to write, for the trailer to point at. It is never encrypted
    /// itself: write it as an indirect object and tell the encryptor its number with
    /// [`Encryptor::with_encrypt_object`].
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub const fn dictionary(&self) -> &Dict {
        &self.security.dict
    }

    /// The `/ID[0]` a file written with this encryptor must carry, at R2–R4: the file key is
    /// derived from it (ISO 32000-1 Algorithm 2), so these are the bytes the handler was
    /// unlocked with, empty for a file that had no usable `/ID[0]`. `None` at R5/R6, whose key
    /// doesn't depend on `/ID`.
    ///
    /// Added in 0.9.0.
    #[must_use]
    pub fn key_id0(&self) -> Option<&[u8]> {
        (self.security.info.revision <= 4).then_some(self.security.id0.as_slice())
    }

    /// The same encryptor, told that object `num` holds the `/Encrypt` dictionary, which
    /// [`Encryptor::encrypt_object`] leaves as it is.
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub fn with_encrypt_object(mut self, num: u32) -> Self {
        self.security.encrypt_object = Some(num);
        self
    }

    /// What the handler is: `/V`, `/R`, the ciphers and the key length.
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub const fn encryption(&self) -> &Encryption {
        &self.security.info
    }

    /// Encrypts the strings and streams of object `num gen` in place, with a fresh IV from
    /// `entropy` for each. Not encrypted, as the standard says: the `/Encrypt` dictionary
    /// ([`Encryptor::with_encrypt_object`]), cross-reference streams, a signature's
    /// `/Contents`, and the XMP metadata stream when `/EncryptMetadata` is false. A stream whose
    /// leading filter is `/Crypt` follows that filter's named crypt filter.
    /// `resolve` dereferences an indirect `/Filter` or `/DecodeParms`.
    ///
    /// Returns `false` when something could not be encrypted; the object is then partly
    /// changed and the caller must not write it (`encryption-incomplete`).
    ///
    /// Added in 0.7.0.
    pub fn encrypt_object(
        &self,
        object: &mut Object,
        num: u32,
        gen_nr: u16,
        entropy: &mut dyn Entropy,
        resolve: &mut dyn FnMut(&Object) -> Option<Object>,
    ) -> bool {
        self.security.encrypt_object(object, num, gen_nr, entropy, resolve)
    }
}

/// A signature dictionary (ISO 32000-2 §12.8.1), whose `/Contents` is never encrypted:
/// `/Type /Sig` or `/DocTimeStamp`, or (since `/Type` is optional) `/ByteRange` with a string
/// `/Contents`.
fn is_signature(dict: &Dict) -> bool {
    matches!(dict.get_name("Type"), Some(b"Sig" | b"DocTimeStamp"))
        || (dict.contains_key("ByteRange") && matches!(dict.get("Contents"), Some(Object::String(_))))
}

/// Decrypts the stream object `num gen` for repair, before the key's document exists: direct
/// `/Crypt` parameters only. Returns false when some AES data was malformed.
pub(crate) fn decrypt_for_repair(security: &Security, stream: &mut Object, num: u32, gen_nr: u16) -> bool {
    security.decrypt_object(stream, num, gen_nr, &mut |_| None)
}

/// Removes a leading `/Crypt` filter (and its `/DecodeParms` entry) from `params`, which holds a
/// stream's resolved `/Filter` and `/DecodeParms`. Only for streams of an encrypted document,
/// which the reader decrypted when it loaded them (ISO 32000-2 §7.4.10: `/Crypt` comes first):
/// the decoder uses it, and `laminapdf-save` when it writes such a stream as plaintext.
///
/// Added in 0.2.0.
pub fn strip_crypt_filter(params: &mut Dict) {
    let is_crypt = |o: &Object| matches!(o, Object::Name(n) if n.as_bytes() == b"Crypt");
    match params.get_mut("Filter") {
        Some(Object::Array(filters)) if filters.first().is_some_and(is_crypt) => {
            filters.remove(0);
            match params.get_mut("DecodeParms") {
                Some(Object::Array(decode_parms)) if !decode_parms.is_empty() => {
                    decode_parms.remove(0);
                }
                Some(Object::Dict(_)) => {
                    params.remove("DecodeParms");
                }
                _ => {}
            }
        }
        Some(filter) if is_crypt(filter) => {
            params.remove("Filter");
            params.remove("DecodeParms");
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use laminapdf_syntax::PdfString;

    fn dict(entries: Vec<(&str, Object)>) -> Dict {
        entries.into_iter().collect()
    }

    #[test]
    fn unlock_rejects_a_public_key_handler() {
        let encrypt = dict(vec![
            ("Filter", Object::name("Adobe.PubSec")),
            ("V", 4.into()),
            ("R", 4.into()),
        ]);
        assert_eq!(
            Security::unlock(&encrypt, None, b"", Password::Any(None), None)
                .err()
                .map(|e| e.code()),
            Some("unsupported-security-handler")
        );
    }

    #[test]
    fn unlock_rejects_an_unknown_revision() {
        let encrypt = dict(vec![
            ("Filter", Object::name("Standard")),
            ("V", 5.into()),
            ("R", 7.into()),
        ]);
        assert!(matches!(
            Security::unlock(&encrypt, None, b"", Password::Any(None), None),
            Err(Error::UnsupportedSecurityHandler {
                version: Some(5),
                revision: Some(7),
                ..
            })
        ));
    }

    #[test]
    fn unlock_reports_missing_o_as_invalid_structure() {
        let encrypt = dict(vec![
            ("Filter", Object::name("Standard")),
            ("V", 2.into()),
            ("R", 3.into()),
        ]);
        assert_eq!(
            Security::unlock(&encrypt, None, b"", Password::Any(None), None)
                .err()
                .map(|e| e.code()),
            Some("invalid-structure")
        );
    }

    #[test]
    fn v4_key_length_comes_from_the_crypt_filter() {
        let cf: Dict = [(
            "StdCF",
            Object::Dict(
                [("CFM", Object::name("AESV2")), ("Length", 16.into())]
                    .into_iter()
                    .collect(),
            ),
        )]
        .into_iter()
        .collect();
        let encrypt = dict(vec![
            ("Length", 40.into()),
            ("CF", cf.into()),
            ("StmF", Object::name("StdCF")),
        ]);
        assert_eq!(key_length(&encrypt, 4), 16);
    }

    #[test]
    fn v4_key_length_defaults_to_128_bits() {
        assert_eq!(key_length(&Dict::new(), 4), 16);
    }

    #[test]
    fn v2_key_length_defaults_to_40_bits() {
        assert_eq!(key_length(&Dict::new(), 2), 5);
    }

    #[test]
    fn strip_crypt_filter_removes_the_leading_crypt_stage() {
        let mut params = dict(vec![
            (
                "Filter",
                vec![Object::name("Crypt"), Object::name("FlateDecode")].into(),
            ),
            ("DecodeParms", vec![Object::Dict(Dict::new()), Object::Null].into()),
        ]);
        strip_crypt_filter(&mut params);
        assert_eq!(
            params,
            dict(vec![
                ("Filter", vec![Object::name("FlateDecode")].into()),
                ("DecodeParms", vec![Object::Null].into()),
            ])
        );
    }

    #[test]
    fn signature_contents_detected_without_type() {
        let sig = dict(vec![
            ("ByteRange", vec![Object::from(0)].into()),
            ("Contents", Object::String(PdfString::hex(vec![1, 2]))),
        ]);
        assert!(is_signature(&sig));
    }
}