pdfcer-model 0.116.0

pdfcer COS model layer: objects, lexer, parser, filters, xref, object streams, recovery, Document/DocumentView, the full and incremental writer, standard-handler crypto, content parsing and the page tree. Depends on nothing else in the workspace; re-exported by pdfcer-core.
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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
//! `/R` 5 — the AES-256 password and key algorithms (Adobe Supplement to ISO
//! 32000, BaseVersion 1.7, ExtensionLevel 3, June 2008, §3.5, Algorithms 3.2a
//! and 3.8–3.13).
//!
//! # What this module is
//!
//! Everything that turns a **password** into the 32-byte **file encryption
//! key** at `/V` 5, plus the one integrity check PDF encryption has. It is the
//! `/R` 5 counterpart of [`standard`](super::standard)'s Algorithms 2, 3, 6 and
//! 7, and it shares *nothing* with them: no MD5, no padding string, no 50-round
//! loop, no `/ID[0]`, no per-object step. The supplement says so directly —
//! **"encrypt version 5 does not use MD5"** — and the key is decoupled from the
//! password entirely, generated by the producer's RNG and then *wrapped* under
//! a password-derived key. That decoupling is why one document has two
//! independent passwords that both recover the same key.
//!
//! # Sourcing, and why `/R` 6 is not here
//!
//! `license_basis: free_secondary_paraphrase`. Adobe's ExtensionLevel 3
//! supplement is freely downloadable and **all rights reserved**, so the
//! project's corpus paraphrases it into step form rather than quoting it; the
//! same posture it takes for Adobe TN #5004. Source file:
//! `D:\Dev\Rag-Specialized\PDF_Spec\security\security__aes256_r5_r6.md`.
//!
//! **`/R` 6 is refused, and this module is not a step towards implementing
//! it.** `/R` 6 uses the identical harness — same 48-byte `/O` and `/U`, same
//! two 8-byte salts, same zero-IV `/UE`/`/OE` unwrap, same 16-byte `/Perms` —
//! with **Algorithm 2.B substituted for `SHA-256(...)` at every position**.
//! Algorithm 2.B was sourced from the ISO 32000-2:2020 primary on 2026-08-12 —
//! its inner AES-128-CBC step, its SHA-256/384/512 selector, its round count
//! and its termination condition — and is implemented in [`super::r6`]. The
//! substitution point IS a pluggable seam ([`Hasher`], `Pass 5.4`): `/R` 5
//! passes [`Hasher::Sha256`] and `/R` 6 passes [`Hasher::R6`], and every
//! auth/key function below takes one. `enc-aes-256-r6.pdf` is now a
//! **decryption** fixture (it opens), and pdfcer's own `/R` 6 writer is
//! cross-checked against pypdf.
//!
//! # The layout everything depends on
//!
//! `/O` and `/U` are **48 bytes** at `/R` 5, three concatenated sections:
//!
//! ```text
//! byte  0 .. 31   32-byte hash          <- what a password is checked against
//! byte 32 .. 39    8-byte Validation Salt  <- salts the check
//! byte 40 .. 47    8-byte Key Salt         <- salts the key that unwraps UE/OE
//! ```
//!
//! Nothing marks this layout. A 32-byte `/U` means `/R` ≤ 4 and a 48-byte
//! `/U` means `/R` ≥ 5 — **length is the only discriminator there is**, and a
//! file claiming `/R` 5 with a 32-byte `/U` has no stated recovery. This module
//! takes fixed-size arrays so that question is answered once, at parse time,
//! by [`EncryptionConfig::parse`](super::standard::EncryptionConfig::parse).
//!
//! # The four traps
//!
//! - **T24 — no per-object key.** The recovered key is used *as-is* for every
//!   string and stream. Handled in
//!   [`FileKey::object_key`](super::standard::FileKey::object_key); named here
//!   because this module is where the key is born.
//! - **T25 — three AES modes.** See [`aes`](super::aes)'s module docs. This
//!   module uses two of them: zero-IV/no-padding CBC to unwrap, ECB for
//!   `/Perms`.
//! - **T26 — the owner algorithms concatenate the WHOLE 48-byte `/U`**, not
//!   its 32-byte hash. Both in [`authenticates_as_owner`] and in
//!   [`file_key_from_owner_password`]. Passing 32 bytes there is a one-line
//!   slip that fails only for owner passwords, i.e. in the branch that has no
//!   fixture unless somebody wrote one.
//! - **T27 — `/Perms` is a check, not a source of truth**, and the spec's
//!   verdict on a mismatch is `should`, not `shall`. See [`PermsCheck`].
//!
//! # A source-text defect this module deliberately does not follow
//!
//! Algorithm 3.12's own concluding sentence says the password it validated is
//! "the **user** password". It is the **owner** password — the algorithm's
//! title, its inputs and its position in 3.2a all say so, and the corpus
//! records the defect as ambiguity **A10** (verified 2026-07-31 against the
//! staged PDF). [`authenticates_as_owner`] implements the algorithm, not its
//! closing sentence.

use sha2::{Digest, Sha256};

use crate::crypto::aes::{KEY_LEN_256, decrypt_ecb_256_block, unwrap_key_cbc_256};

/// Length of `/O` and `/U` at `/R` 5 (Table 3.19). 32-byte hash + two 8-byte
/// salts.
pub const OU_LEN: usize = 48;

/// Length of `/OE` and `/UE` (Table 3.19) — one wrapped 32-byte file
/// encryption key, exactly two AES blocks, no padding.
pub const OE_UE_LEN: usize = KEY_LEN_256;

/// Length of `/Perms` (Table 3.19) — one AES block.
pub const PERMS_LEN: usize = 16;

/// Byte range of the 32-byte hash inside a 48-byte `/O` or `/U`.
const HASH: std::ops::Range<usize> = 0..32;
/// Byte range of the 8-byte Validation Salt inside a 48-byte `/O` or `/U`.
const VALIDATION_SALT: std::ops::Range<usize> = 32..40;
/// Byte range of the 8-byte Key Salt inside a 48-byte `/O` or `/U`.
const KEY_SALT: std::ops::Range<usize> = 40..48;

/// The maximum number of **bytes** of UTF-8 password `/R` 5 hashes.
///
/// Step 3 of the supplement's password preprocessing: "truncate to the first
/// 127 bytes if longer". Bytes, not characters — a 127-byte truncation can
/// land mid-sequence in UTF-8, and the algorithm does not care. Compare
/// [`pad_password`](super::standard::pad_password)'s 32 at `/R` ≤ 4, which
/// pads as well as truncates; there is no padding at all here.
pub const MAX_PASSWORD_LEN: usize = 127;

/// The `/R` 5 hash: plain SHA-256 over the concatenated parts.
///
/// **This function is Algorithm 2.B's substitution point.** At `/R` 6 every
/// call site below uses 2.B in place of this, with identical inputs and an
/// identical 32-byte output, and *nothing else* about `/R` 5 changes. The
/// corpus is explicit about that (`iso32000__delta__pdf20_encryption.md` §6),
/// and it is recorded here so a future session does not re-derive the shape of
/// the gap. 2.B's body is now sourced and implemented ([`super::r6`], `Pass 5.4`).
/// Which hash `/R` 5 and `/R` 6 use — the ONE thing that differs between the
/// two revisions (`Pass 5.4`). `/R` 5 is plain SHA-256; `/R` 6 is Algorithm
/// 2.B ([`super::r6`]). Every auth/key function below takes one of these and is
/// otherwise identical across the two revisions.
///
/// `input_parts` is the sequence `/R` 5 SHA-256s (e.g. `[password, salt]`);
/// `password` is repeated because 2.B needs it separately inside `K0`; `u` is
/// the 48-byte `/U` on the owner paths only. For [`Hasher::Sha256`] the
/// `password` argument is ignored (the password is already `input_parts[0]`)
/// and `u`, when present, is appended — reproducing the `/R` 5 concatenation
/// exactly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Hasher {
    /// `/R` 5 — plain SHA-256 over the concatenated parts (then `u`).
    Sha256,
    /// `/R` 6 — Algorithm 2.B, at the given [`super::r6::A13Reading`].
    R6(super::r6::A13Reading),
}

impl Hasher {
    /// The 32-byte hash this revision computes from the given inputs.
    #[must_use]
    pub fn hash(self, input_parts: &[&[u8]], password: &[u8], u: Option<&[u8]>) -> [u8; 32] {
        match self {
            Self::Sha256 => {
                let mut h = Sha256::new();
                for p in input_parts {
                    h.update(p);
                }
                if let Some(u) = u {
                    h.update(u);
                }
                h.finalize().into()
            }
            Self::R6(reading) => {
                // The full input concatenation is `input_parts ‖ u` — U is part
                // of the OWNER input string (Algorithm 2.A(c)/12), exactly as
                // SHA-256 appends it above. 2.B ADDITIONALLY feeds U into every
                // K0 (its step (a)), so `u` is passed on BOTH — proven against
                // pypdf's `/O`: U in the input string alone does not match, U in
                // both does.
                let mut input: Vec<u8> = input_parts.concat();
                if let Some(u) = u {
                    input.extend_from_slice(u);
                }
                super::r6::hash_2b(&input, password, u, reading)
            }
        }
    }
}

/// A password prepared for `/R` 5 hashing, and an honest note about how far
/// the preparation got.
///
/// # The preprocessing the supplement asks for, and what pdfcer does
///
/// Three steps:
///
/// 1. Apply the **SASLprep** profile (RFC 4013) of **stringprep** (RFC 3454),
///    with the Normalize and BIDI options.
/// 2. Convert to **UTF-8**.
/// 3. **Truncate to the first 127 bytes.**
///
/// pdfcer implements steps 2 and 3 exactly. It does **not** implement step 1,
/// and does not pretend to: neither RFC is staged in the project's spec
/// corpus, and a stringprep dependency is not being taken for a read-only
/// increment.
///
/// **For an all-ASCII password SASLprep is the identity function**, so for
/// every password a person can type on an unshifted keyboard, steps 2 and 3
/// *are* the whole algorithm and the result is exact. That covers the fixtures
/// and, on any realistic prior, the overwhelming majority of real documents.
///
/// # Why a non-ASCII password is attempted rather than refused
///
/// The tempting alternative is to refuse a non-ASCII password by name. It was
/// rejected, because it is *worse* on both sides of the coin:
///
/// - SASLprep is the identity for far more than ASCII — an already-normalised,
///   direction-neutral string passes through unchanged — so refusing rejects
///   passwords that would have worked, with no way for the operator to
///   discover that they would have.
/// - Getting normalisation wrong here **cannot** produce a silently wrong
///   result. Authentication is self-verifying: the SHA-256 either equals
///   `/U[0..32]` or it does not. A mis-normalised password fails to
///   authenticate; it never opens a document with a wrong key. This is the
///   opposite of the usual fuzzy-never-sneaky hazard, where an inference gets
///   *used*.
///
/// So the only harm a missing SASLprep can do is a **false "wrong password"**,
/// and the fix for that is a diagnostic, not a refusal. [`needs_saslprep`]
/// reports whether this password could have been changed by step 1;
/// `document.rs` turns a failed authentication on such a password into a
/// distinct error that says so, instead of the flat "supply the password"
/// every wrong guess produces. Rule 4 is satisfied by disclosure, not by
/// declining to try.
///
/// [`needs_saslprep`]: Self::needs_saslprep
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreparedPassword {
    /// The UTF-8 bytes, truncated to [`MAX_PASSWORD_LEN`].
    bytes: Vec<u8>,
    /// Whether the input contained any byte SASLprep could act on.
    needs_saslprep: bool,
    /// Whether step 3 actually removed anything.
    truncated: bool,
}

impl PreparedPassword {
    /// Prepare `password` for hashing.
    ///
    /// `password` is taken as bytes rather than as `&str` because that is what
    /// reaches pdfcer: a CLI argument, a password file, a GUI text box, all of
    /// which may hold something that is not valid UTF-8. Step 2 ("convert to
    /// UTF-8") is therefore a no-op on already-UTF-8 input and a
    /// pass-the-bytes-through on anything else — inventing a re-encoding for
    /// invalid input would be guessing at the producer's intent, and the
    /// supplement offers no branch for it.
    #[must_use]
    pub fn new(password: &[u8]) -> Self {
        // A byte is "SASLprep-relevant" if step 1 could map, prohibit or
        // reorder it. Every ASCII graphic character and the space are mapped
        // to themselves, so only the non-ASCII range (0x80..) and the ASCII
        // C0 controls can be affected. Controls are *prohibited* output by
        // RFC 4013 rather than mapped, but the honest report is the same: this
        // password is one pdfcer cannot promise it prepared correctly.
        let needs_saslprep = password
            .iter()
            .any(|&b| b >= 0x80 || (b.is_ascii_control() && b != b' '));

        let take = password.len().min(MAX_PASSWORD_LEN);
        Self {
            // `get(..take)` rather than an index: `take` is `min`-clamped, so
            // this cannot fail, and the fallback keeps the proof local in a
            // function that handles untrusted input.
            bytes: password.get(..take).unwrap_or_default().to_vec(),
            needs_saslprep,
            truncated: password.len() > MAX_PASSWORD_LEN,
        }
    }

    /// The bytes to hash.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Whether SASLprep (step 1), which pdfcer does not implement, could have
    /// changed this password.
    ///
    /// `false` means the preparation is **exact** and a failed authentication
    /// is simply a wrong password. `true` means a failure is ambiguous and
    /// must be reported as such — see the type's docs.
    #[must_use]
    pub fn needs_saslprep(&self) -> bool {
        self.needs_saslprep
    }

    /// Whether step 3's 127-byte truncation removed anything.
    ///
    /// Reported because it is otherwise invisible: two passwords sharing their
    /// first 127 bytes are the *same* password to this algorithm, which is a
    /// surprising fact worth being able to state rather than a bug.
    #[must_use]
    pub fn was_truncated(&self) -> bool {
        self.truncated
    }
}

/// Algorithm 3.11 — does `password` authenticate as the **user** password?
///
/// `SHA-256(password ‖ UserValidationSalt)` equals `/U[0..32]`.
///
/// Note what is *not* an input: `/ID[0]` (which Algorithms 2 and 5 hash at
/// `/R` ≤ 4), `/P`, `/O`, and `/EncryptMetadata`. At `/R` 5 the user check
/// depends on nothing but the password and eight bytes of salt, which is
/// precisely why the `/Perms` check exists — see [`PermsCheck`].
#[must_use]
pub fn authenticates_as_user(
    password: &PreparedPassword,
    u: &[u8; OU_LEN],
    hasher: Hasher,
) -> bool {
    // Ranges are compile-time constants over a fixed-size array, so every
    // index below is in bounds by the type.
    #[allow(clippy::indexing_slicing)]
    let (expect, salt) = (&u[HASH], &u[VALIDATION_SALT]);
    hasher.hash(&[password.as_bytes(), salt], password.as_bytes(), None) == expect
}

/// Algorithm 3.12 — does `password` authenticate as the **owner** password?
///
/// `SHA-256(password ‖ OwnerValidationSalt ‖ U)` equals `/O[0..32]`, where `U`
/// is the **whole 48-byte `/U` string** (**T26**) — not its 32-byte hash, and
/// not `/U` at all if you were reading Algorithm 3.11 a moment ago.
///
/// The concatenation is what makes the two passwords independent while both
/// recover the same key: `/O` is bound to `/U`, so `/U` must be computed
/// first on the writer side, and an owner check cannot be performed without
/// the user string in hand.
#[must_use]
pub fn authenticates_as_owner(
    password: &PreparedPassword,
    o: &[u8; OU_LEN],
    u: &[u8; OU_LEN],
    hasher: Hasher,
) -> bool {
    #[allow(clippy::indexing_slicing)]
    let (expect, salt) = (&o[HASH], &o[VALIDATION_SALT]);
    hasher.hash(&[password.as_bytes(), salt], password.as_bytes(), Some(u)) == expect
}

/// Algorithm 3.2a, user branch — recover the file encryption key from `/UE`.
///
/// Unwrap key = `SHA-256(password ‖ UserKeySalt)`; that key decrypts `/UE`
/// with **AES-256-CBC, zero IV, no padding** (see
/// [`unwrap_key_cbc_256`]) to give the 32-byte
/// file encryption key.
///
/// **The Key Salt is a different eight bytes from the Validation Salt.**
/// Transposing them is the classic slip here and it is *not* silent in the
/// helpful sense: authentication still passes (it uses the validation salt via
/// [`authenticates_as_user`]) and the recovered key is then wrong, so the
/// document opens and decrypts to noise. Only an end-to-end fidelity check
/// catches it.
///
/// # Returns
///
/// `None` if the unwrap did not yield exactly 32 bytes, which for a
/// well-formed 32-byte `/UE` cannot happen — the check exists so a malformed
/// `/UE` cannot produce a short "key" that silently decrypts nothing.
#[must_use]
pub fn file_key_from_user_password(
    password: &PreparedPassword,
    u: &[u8; OU_LEN],
    ue: &[u8; OE_UE_LEN],
    hasher: Hasher,
) -> Option<[u8; KEY_LEN_256]> {
    #[allow(clippy::indexing_slicing)]
    let salt = &u[KEY_SALT];
    let unwrap_key = hasher.hash(&[password.as_bytes(), salt], password.as_bytes(), None);
    unwrap_key_cbc_256(&unwrap_key, ue).try_into().ok()
}

/// Algorithm 3.2a, owner branch — recover the file encryption key from `/OE`.
///
/// Unwrap key = `SHA-256(password ‖ OwnerKeySalt ‖ U)`, again over the **whole
/// 48-byte `/U`** (**T26**); that key decrypts `/OE` the same way. The result
/// is the *same* 32-byte file encryption key the user branch produces — the
/// two wrapped copies exist so either password recovers it, which is the whole
/// reason `/R` 5 decoupled the key from the password in the first place.
///
/// # Returns
///
/// `None` on a malformed `/OE`; see [`file_key_from_user_password`].
#[must_use]
pub fn file_key_from_owner_password(
    password: &PreparedPassword,
    o: &[u8; OU_LEN],
    u: &[u8; OU_LEN],
    oe: &[u8; OE_UE_LEN],
    hasher: Hasher,
) -> Option<[u8; KEY_LEN_256]> {
    #[allow(clippy::indexing_slicing)]
    let salt = &o[KEY_SALT];
    let unwrap_key = hasher.hash(&[password.as_bytes(), salt], password.as_bytes(), Some(u));
    unwrap_key_cbc_256(&unwrap_key, oe).try_into().ok()
}

/// The verdict of Algorithm 3.13 — the **only integrity check in PDF
/// encryption** (negative result **N7**).
///
/// # Why this is reported and never acted on (T27)
///
/// `/Perms` is a 16-byte block holding an encrypted copy of `/P` and of
/// `/EncryptMetadata`. At `/V` 1–4 those values sit in the file as editable
/// plaintext with no protection at all; `/Perms` is the one place PDF binds
/// them to the encryption key. That makes it the only thing in clause 7.6 that
/// can detect tampering — and the supplement still states its verdict as
/// **`should` match**, with **no clause anywhere saying what to do when it
/// does not**.
///
/// pdfcer therefore **reports the disagreement and prefers neither value**:
///
/// - It does **not refuse the document.** The spec's modality is `should`, and
///   every other reader opens the file; refusing would make pdfcer reject
///   documents nothing else objects to, on the strength of a check the
///   standard declines to require.
/// - It does **not silently substitute** the decrypted `/P` for the
///   dictionary's. That is exactly the shape rule 4 forbids: a value pdfcer
///   *inferred* to be more trustworthy, becoming what the operator is shown,
///   with no disclosure. [`Permissions`](super::standard::Permissions) keeps
///   reporting the dictionary `/P` — the value the file declares and the value
///   every other viewer displays — and the disagreement is surfaced beside it
///   through [`DocumentEncryption::perms`].
/// - It does **not** treat a mismatch as damage. [`Self::MarkerMissing`] is
///   the case that means "the decryption itself is suspect", and it is kept
///   distinct for that reason.
///
/// [`DocumentEncryption::perms`]: crate::document::DocumentEncryption::perms
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PermsCheck {
    /// There is no `/Perms` entry to check. `/R` ≤ 4 has none — the entry was
    /// introduced by ExtensionLevel 3 — so this is the ordinary answer for
    /// every RC4 and AES-128 document, and is **not** a negative result.
    NotApplicable,
    /// Decrypted cleanly, the `adb` marker is present, and both recovered
    /// values agree with the plaintext dictionary.
    Match,
    /// Decrypted cleanly and the `adb` marker is present, but a recovered
    /// value disagrees with the dictionary.
    ///
    /// The most likely innocent cause is a producer that edited `/P` without
    /// re-encrypting `/Perms`; the most likely non-innocent one is someone
    /// widening the permissions of a document they could not decrypt.
    /// **Nothing in the file distinguishes those**, which is precisely why
    /// pdfcer reports rather than decides.
    Mismatch {
        /// Bytes 0–3 of the decrypted block, little-endian: the permission
        /// flags as the *encrypting producer* recorded them.
        perms_p: u32,
        /// `/P` as it sits in the `/Encrypt` dictionary, unsigned (T10).
        dict_p: u32,
        /// Byte 8: `Some(true)` for ASCII `'T'`, `Some(false)` for `'F'`,
        /// `None` for anything else — a third state the algorithm does not
        /// define and which must not be collapsed into `false`.
        perms_encrypt_metadata: Option<bool>,
        /// `/EncryptMetadata` as the dictionary states it (default `true`).
        dict_encrypt_metadata: bool,
    },
    /// Decrypted, but bytes 9–11 are not the literal `adb`.
    ///
    /// A different fact from [`Self::Mismatch`]: the marker is a fixed
    /// constant, so its absence means the *decryption* is wrong — a truncated
    /// or corrupted `/Perms`, or a file encryption key that is not the one
    /// this document was encrypted with. Since authentication has already
    /// succeeded by the time this runs, in practice it points at a damaged
    /// `/Perms` rather than at a wrong password.
    MarkerMissing,
}

/// Algorithm 3.13 — decrypt `/Perms` and compare it with the dictionary.
///
/// `file_key` is the recovered file encryption key; `perms` is the raw 16-byte
/// `/Perms` string; `dict_p` and `dict_encrypt_metadata` are the plaintext
/// values from the `/Encrypt` dictionary.
///
/// The decrypted block's layout (Algorithm 3.10):
///
/// | Bytes | Content |
/// |---|---|
/// | 0–3 | the permission flags, **little-endian** |
/// | 4–7 | `FF FF FF FF` — `/P` extended to 64 bits with the high half all 1s |
/// | 8 | ASCII `'T'` or `'F'`, the `/EncryptMetadata` boolean |
/// | 9–11 | ASCII `'a'`, `'d'`, `'b'` — the marker |
/// | 12–15 | random, **"which will be ignored"** |
///
/// Bytes 4–7 are *not* checked. The supplement's own note explains why they
/// are all 1s — "this allows for future extension without changing the
/// format" — so a future revision could put something there, and asserting on
/// them would turn a forward-compatible file into a reported mismatch. Bytes
/// 12–15 are likewise ignored, and are the reason `/Perms` can never be
/// re-derived on save: it must be preserved verbatim (**R33**), exactly like
/// `/U`'s arbitrary tail at `/R` ≥ 3 (**T15**).
///
/// # Returns
///
/// See [`PermsCheck`]. This function never fails and never decides anything —
/// it is a report.
#[must_use]
#[allow(clippy::indexing_slicing)]
pub fn validate_perms(
    file_key: &[u8; KEY_LEN_256],
    perms: &[u8; PERMS_LEN],
    dict_p: u32,
    dict_encrypt_metadata: bool,
) -> PermsCheck {
    // Every index below is a constant into a fixed 16-byte array.
    let out = decrypt_ecb_256_block(file_key, perms);

    if &out[9..12] != b"adb" {
        return PermsCheck::MarkerMissing;
    }

    let perms_p = u32::from_le_bytes([out[0], out[1], out[2], out[3]]);
    let perms_encrypt_metadata = match out[8] {
        b'T' => Some(true),
        b'F' => Some(false),
        _ => None,
    };

    if perms_p == dict_p && perms_encrypt_metadata == Some(dict_encrypt_metadata) {
        PermsCheck::Match
    } else {
        PermsCheck::Mismatch {
            perms_p,
            dict_p,
            perms_encrypt_metadata,
            dict_encrypt_metadata,
        }
    }
}

#[cfg(test)]
#[allow(
    clippy::indexing_slicing,
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic
)]
mod tests {
    use super::*;

    /// The real `/O`, `/U`, `/OE`, `/UE` and `/Perms` of
    /// `fixtures/synthetic/encryption/enc-aes-256-r5.pdf`, which pypdf — an
    /// independent implementation — produced. Held here so the unit tests can
    /// exercise each algorithm in isolation and say *which* one broke, where
    /// the end-to-end tests only say that something did.
    const U: [u8; OU_LEN] = [
        0x58, 0xc0, 0x57, 0x8f, 0xec, 0x62, 0x7b, 0x8b, 0x9b, 0x8d, 0xd4, 0x26, 0xb6, 0xc2, 0x95,
        0x4d, 0x76, 0xa0, 0x92, 0x1c, 0xa6, 0x5e, 0xfb, 0xb9, 0xa9, 0xa5, 0xc6, 0xbb, 0x9d, 0xe7,
        0x81, 0x8b, 0xa7, 0x7e, 0x79, 0xcc, 0x0a, 0x4b, 0xd1, 0x28, 0x99, 0xbd, 0xb1, 0x12, 0x8f,
        0x4b, 0xc7, 0x99,
    ];
    const O: [u8; OU_LEN] = [
        0xf8, 0xd6, 0xbf, 0xa3, 0x1b, 0x64, 0x5d, 0x37, 0x7e, 0xf8, 0xbd, 0x6e, 0xd5, 0x34, 0xb0,
        0x28, 0xa5, 0x8d, 0xd9, 0x7e, 0xdf, 0x16, 0xfe, 0xf0, 0xe4, 0x57, 0x19, 0x58, 0x5c, 0x7d,
        0x32, 0xda, 0xbb, 0xd6, 0x0d, 0xd2, 0x65, 0xc7, 0xd3, 0xd0, 0x77, 0xde, 0xbe, 0x35, 0x54,
        0xb5, 0xfb, 0x0f,
    ];
    const UE: [u8; OE_UE_LEN] = [
        0xe2, 0x24, 0xdc, 0x92, 0x32, 0x71, 0x44, 0xdf, 0x5a, 0xb4, 0x75, 0xa1, 0x00, 0x8b, 0x1d,
        0x37, 0xef, 0x90, 0xe7, 0x8a, 0x85, 0x36, 0x58, 0xe5, 0xf7, 0x77, 0x06, 0xc2, 0x1e, 0x90,
        0xb3, 0x8a,
    ];
    const OE: [u8; OE_UE_LEN] = [
        0xde, 0xd9, 0x20, 0x92, 0x7c, 0x17, 0xc9, 0xc0, 0x8d, 0x47, 0x09, 0x68, 0xd6, 0x4f, 0xae,
        0x44, 0xb6, 0x85, 0x8b, 0x08, 0xca, 0xcf, 0x51, 0x11, 0x52, 0xd4, 0x3f, 0xcd, 0x61, 0xf8,
        0x85, 0x1f,
    ];
    const PERMS: [u8; PERMS_LEN] = [
        0x71, 0x6a, 0xf6, 0xa5, 0x5e, 0xa2, 0xaf, 0xb6, 0xa9, 0xb8, 0x8a, 0xe3, 0x6e, 0x38, 0xb5,
        0xe1,
    ];
    /// The file encryption key both branches must recover. `/P` is
    /// `0xFFFFFFFC` and `/EncryptMetadata` is absent, i.e. `true`.
    const FILE_KEY: [u8; KEY_LEN_256] = [
        0x9c, 0x41, 0xcb, 0x1c, 0x02, 0x13, 0x80, 0x48, 0x96, 0x0d, 0x57, 0xf4, 0x8a, 0x21, 0x22,
        0xf8, 0xfe, 0xbf, 0x4a, 0x68, 0xdd, 0x03, 0x18, 0x62, 0xaf, 0x90, 0xba, 0xc8, 0x20, 0x51,
        0xf6, 0x0c,
    ];
    const DICT_P: u32 = 0xFFFF_FFFC;

    fn pw(s: &[u8]) -> PreparedPassword {
        PreparedPassword::new(s)
    }

    /// Algorithm 3.11 accepts the user password and rejects everything else,
    /// including the *owner* password — the two checks are independent and a
    /// handler that conflated them would report the wrong access level.
    #[test]
    fn user_validation_accepts_only_the_user_password() {
        assert!(authenticates_as_user(&pw(b"userpw"), &U, Hasher::Sha256));
        assert!(!authenticates_as_user(&pw(b"ownerpw"), &U, Hasher::Sha256));
        assert!(!authenticates_as_user(&pw(b""), &U, Hasher::Sha256));
        assert!(!authenticates_as_user(&pw(b"userpw "), &U, Hasher::Sha256));
    }

    /// Algorithm 3.12 accepts the owner password, and **needs the whole
    /// 48-byte `/U`** to do it (T26).
    #[test]
    fn owner_validation_accepts_only_the_owner_password() {
        assert!(authenticates_as_owner(
            &pw(b"ownerpw"),
            &O,
            &U,
            Hasher::Sha256
        ));
        assert!(!authenticates_as_owner(
            &pw(b"userpw"),
            &O,
            &U,
            Hasher::Sha256
        ));
    }

    /// T26 as a falsification: hashing only `/U`'s 32-byte *hash* instead of
    /// the whole 48-byte string fails, and fails **only** on the owner path.
    ///
    /// Written as an inline recomputation rather than by breaking the real
    /// function, because that is the only way to assert the wrong answer is
    /// wrong without leaving the wrong answer in the source.
    #[test]
    fn truncating_u_to_its_hash_breaks_owner_validation_only() {
        let truncated = Hasher::Sha256.hash(
            &[b"ownerpw", &O[VALIDATION_SALT], &U[HASH]],
            b"ownerpw",
            None,
        );
        assert_ne!(
            truncated, O[HASH],
            "hashing U's 32-byte hash instead of the whole 48-byte string must \
             NOT validate — if this ever passes, T26 has stopped being a trap \
             and the whole-string requirement can be relaxed"
        );
        // And the correct form does validate, so the assertion above is about
        // the truncation rather than about the test's own inputs.
        assert!(authenticates_as_owner(
            &pw(b"ownerpw"),
            &O,
            &U,
            Hasher::Sha256
        ));
    }

    /// Both branches of Algorithm 3.2a recover the **same** key. That
    /// equality is the whole design of `/R` 5 — the key is generated
    /// independently of both passwords and wrapped twice.
    #[test]
    fn both_password_branches_recover_the_same_file_encryption_key() {
        let from_user = file_key_from_user_password(&pw(b"userpw"), &U, &UE, Hasher::Sha256)
            .expect("UE unwraps to 32 bytes");
        let from_owner = file_key_from_owner_password(&pw(b"ownerpw"), &O, &U, &OE, Hasher::Sha256)
            .expect("OE unwraps to 32 bytes");
        assert_eq!(from_user, FILE_KEY);
        assert_eq!(from_owner, FILE_KEY);
    }

    /// Falsification: the two salts are **not** interchangeable.
    ///
    /// Deriving the unwrap key from the Validation Salt instead of the Key
    /// Salt gives a different key — and, crucially, authentication would still
    /// have succeeded, so nothing before the first decrypted object would
    /// notice.
    #[test]
    fn transposing_the_two_salts_yields_a_different_key() {
        let right = Hasher::Sha256.hash(&[b"userpw".as_slice(), &U[KEY_SALT]], b"userpw", None);
        let wrong = Hasher::Sha256.hash(
            &[b"userpw".as_slice(), &U[VALIDATION_SALT]],
            b"userpw",
            None,
        );
        assert_ne!(right, wrong);
        assert_ne!(
            unwrap_key_cbc_256(&wrong, &UE),
            FILE_KEY.to_vec(),
            "the validation salt must not produce the file encryption key"
        );
        assert_eq!(unwrap_key_cbc_256(&right, &UE), FILE_KEY.to_vec());
    }

    /// A wrong password unwraps to *something* — 32 bytes of nonsense — rather
    /// than failing. That is why authentication (3.11/3.12) has to run first
    /// and is not optional: the unwrap has no integrity of its own.
    #[test]
    fn unwrapping_with_a_wrong_password_yields_a_wrong_key_not_an_error() {
        let bad = file_key_from_user_password(&pw(b"not the password"), &U, &UE, Hasher::Sha256)
            .expect("32 bytes of nonsense is still 32 bytes");
        assert_ne!(bad, FILE_KEY);
    }

    /// Algorithm 3.13 on the real fixture: marker present, both values agree.
    #[test]
    fn perms_validates_against_the_dictionary() {
        assert_eq!(
            validate_perms(&FILE_KEY, &PERMS, DICT_P, true),
            PermsCheck::Match
        );
    }

    /// A `/P` that disagrees with the encrypted copy is reported with **both**
    /// numbers, so a caller can show the operator what disagrees rather than
    /// only that something does.
    #[test]
    fn a_tampered_p_is_reported_with_both_values() {
        match validate_perms(&FILE_KEY, &PERMS, 0xFFFF_FFFF, true) {
            PermsCheck::Mismatch {
                perms_p,
                dict_p,
                perms_encrypt_metadata,
                dict_encrypt_metadata,
            } => {
                assert_eq!(perms_p, DICT_P, "the encrypted copy is unchanged");
                assert_eq!(dict_p, 0xFFFF_FFFF, "the plaintext copy is what moved");
                assert_eq!(perms_encrypt_metadata, Some(true));
                assert!(dict_encrypt_metadata);
            }
            other => panic!("expected a mismatch, got {other:?}"),
        }
    }

    /// An `/EncryptMetadata` that disagrees is a mismatch too — byte 8 is part
    /// of the protected block, not decoration.
    #[test]
    fn a_flipped_encrypt_metadata_is_a_mismatch() {
        assert!(matches!(
            validate_perms(&FILE_KEY, &PERMS, DICT_P, false),
            PermsCheck::Mismatch { .. }
        ));
    }

    /// A `/Perms` that does not decrypt to the `adb` marker is
    /// [`PermsCheck::MarkerMissing`], not a mismatch. The two mean different
    /// things — "someone changed the numbers" versus "these bytes are not a
    /// permissions block at all" — and collapsing them would report tampering
    /// for a corrupted file.
    #[test]
    fn a_corrupt_perms_block_reports_the_missing_marker() {
        let mut damaged = PERMS;
        damaged[0] ^= 0xFF;
        assert_eq!(
            validate_perms(&FILE_KEY, &damaged, DICT_P, true),
            PermsCheck::MarkerMissing
        );
    }

    /// Falsification: `/Perms` is **ECB**, and giving it CBC's treatment
    /// destroys it.
    ///
    /// `unwrap_key_cbc_256` is CBC with a zero IV — the closest neighbouring
    /// mode, and the one an implementation is most likely to reach for by
    /// accident since it is right there and takes the same key. Over a single
    /// block the two differ by an XOR with the zero IV… which is a no-op, so
    /// they *agree*. The test therefore uses a **non-zero** IV's worth of
    /// difference by decrypting the block as if it were the second block of a
    /// two-block CBC message, which is what happens the moment `/Perms` is
    /// routed through a general CBC path with real preceding data.
    #[test]
    fn perms_decrypted_as_chained_cbc_loses_its_marker() {
        // Two blocks: some arbitrary "previous" ciphertext, then /Perms. Under
        // CBC the second block is XORed with the first block's ciphertext.
        let mut chained = [0u8; 32];
        chained[..16].copy_from_slice(&[0xAA; 16]);
        chained[16..].copy_from_slice(&PERMS);
        let out = unwrap_key_cbc_256(&FILE_KEY, &chained);
        assert_eq!(out.len(), 32);
        assert_ne!(
            &out[16 + 9..16 + 12],
            b"adb",
            "chaining must corrupt the marker; if it does not, this test is \
             not observing the difference it claims to"
        );
        // ECB, correctly, does not.
        assert_eq!(&decrypt_ecb_256_block(&FILE_KEY, &PERMS)[9..12], b"adb");
    }

    /// **A published cross-implementation test vector.**
    ///
    /// Everything above checks pdfcer against a fixture pdfcer can also read, so
    /// a consistent misreading would agree with itself. This checks it against
    /// a number **a fourth implementation printed**.
    ///
    /// The values are the `/Encrypt` entries of qpdf's `c-r5-in.pdf`
    /// (`qpdf/qtest/qpdf/`, Apache-2.0), and `QPDF_KEY` is the file encryption
    /// key qpdf's own test suite asserts for it — `encryption.test` runs
    /// `qpdf --check --show-encryption-key` against that file and separately
    /// accepts `--password-is-hex-key --password=35ea16a4…a020`, so the key is
    /// stated in qpdf's expected output rather than inferred from behaviour.
    /// Its passwords are `user3` (user) and `owner3` (owner).
    ///
    /// Copied as constants rather than read from `fixtures/external/` on
    /// purpose: that tree is gitignored (`LEGAL.md` §5), so a test that read
    /// the file would skip on every clean checkout and in CI — which is the
    /// "fixture that cannot fail" shape this project keeps finding. Sixteen
    /// lines of hex make the vector unconditional.
    ///
    /// What it proves that nothing else here does: pdfcer's `/R` 5 key
    /// derivation lands on a **specific 32-byte value an independent
    /// implementation published**, by both password branches. A subtly wrong
    /// derivation cannot agree with that by accident.
    #[test]
    fn matches_qpdfs_published_file_encryption_key() {
        const QPDF_O: [u8; OU_LEN] = [
            0x58, 0x4a, 0x53, 0x53, 0xc4, 0x24, 0xc1, 0xf9, 0x63, 0xb6, 0xb5, 0xf0, 0xa0, 0x92,
            0xd7, 0x20, 0xf0, 0x7b, 0xf1, 0x20, 0xeb, 0x32, 0x9a, 0xdd, 0x86, 0x63, 0xfe, 0x33,
            0xa8, 0x58, 0x9a, 0xdc, 0xad, 0x4f, 0xca, 0x26, 0x53, 0x79, 0x3d, 0x09, 0x94, 0x94,
            0x8f, 0x7f, 0x6f, 0x30, 0xa0, 0x35,
        ];
        const QPDF_U: [u8; OU_LEN] = [
            0xd7, 0x7c, 0xd8, 0x82, 0xaf, 0x29, 0xe7, 0xbe, 0xc7, 0x57, 0x91, 0x57, 0x18, 0x76,
            0x16, 0xc3, 0x24, 0xa6, 0xa0, 0x0e, 0x8b, 0x90, 0xf0, 0x95, 0x9e, 0x6b, 0x01, 0xf8,
            0x39, 0x72, 0x06, 0x5e, 0xc5, 0xb7, 0xc4, 0x51, 0x21, 0xf5, 0x96, 0x34, 0x30, 0xff,
            0xe0, 0x3a, 0x06, 0xa2, 0x23, 0x01,
        ];
        const QPDF_OE: [u8; OE_UE_LEN] = [
            0x50, 0xb2, 0x41, 0x5e, 0x8d, 0xc2, 0x04, 0x23, 0x5c, 0x83, 0x7e, 0x85, 0xb6, 0xa3,
            0x36, 0xae, 0x85, 0x7b, 0x36, 0x6e, 0xde, 0x9e, 0x9c, 0xc7, 0xd3, 0x06, 0x57, 0xdb,
            0x00, 0x03, 0x3e, 0xc3,
        ];
        const QPDF_UE: [u8; OE_UE_LEN] = [
            0x86, 0x56, 0x0d, 0x35, 0xa1, 0x5c, 0x06, 0x74, 0x57, 0xdc, 0xbf, 0xb5, 0x7e, 0xdd,
            0x49, 0x5c, 0xb0, 0xf5, 0xc2, 0xc1, 0xce, 0x77, 0xc9, 0xcf, 0x46, 0x2a, 0x49, 0x6c,
            0xe4, 0x84, 0xcc, 0xfd,
        ];
        const QPDF_PERMS: [u8; PERMS_LEN] = [
            0x89, 0x71, 0x9c, 0xe2, 0x26, 0xa7, 0x30, 0xc2, 0x18, 0x99, 0x60, 0xbb, 0x53, 0x34,
            0x50, 0xad,
        ];
        /// The key qpdf's expected output states for this file.
        const QPDF_KEY: [u8; KEY_LEN_256] = [
            0x35, 0xea, 0x16, 0xa4, 0x8b, 0x6a, 0x30, 0x45, 0x13, 0x3b, 0x69, 0xac, 0x09, 0x06,
            0xc2, 0xe8, 0xfb, 0x0a, 0x2c, 0xc9, 0x79, 0x03, 0xae, 0x17, 0xb5, 0x1a, 0x57, 0x86,
            0xeb, 0xdb, 0xa0, 0x20,
        ];
        /// `/P -2052`, reinterpreted unsigned (T10).
        const QPDF_P: u32 = 0xFFFF_F7FC;

        assert!(authenticates_as_user(
            &pw(b"user3"),
            &QPDF_U,
            Hasher::Sha256
        ));
        assert!(authenticates_as_owner(
            &pw(b"owner3"),
            &QPDF_O,
            &QPDF_U,
            Hasher::Sha256
        ));

        assert_eq!(
            file_key_from_user_password(&pw(b"user3"), &QPDF_U, &QPDF_UE, Hasher::Sha256),
            Some(QPDF_KEY),
            "the user branch must reach the key qpdf publishes for this file"
        );
        assert_eq!(
            file_key_from_owner_password(
                &pw(b"owner3"),
                &QPDF_O,
                &QPDF_U,
                &QPDF_OE,
                Hasher::Sha256
            ),
            Some(QPDF_KEY),
            "and so must the owner branch — one key, two wrapped copies"
        );

        // The /Perms block of a document produced by a different encryptor,
        // with a different /P, decrypts under that key and agrees.
        assert_eq!(
            validate_perms(&QPDF_KEY, &QPDF_PERMS, QPDF_P, true),
            PermsCheck::Match
        );
    }

    /// Step 3: 127 **bytes**, and the truncation is reported.
    #[test]
    fn passwords_are_truncated_to_127_bytes_and_say_so() {
        let short = PreparedPassword::new(b"userpw");
        assert_eq!(short.as_bytes(), b"userpw");
        assert!(!short.was_truncated());

        let long = vec![b'x'; 200];
        let p = PreparedPassword::new(&long);
        assert_eq!(p.as_bytes().len(), MAX_PASSWORD_LEN);
        assert!(p.was_truncated());

        // Exactly 127 is not truncated; 128 is.
        assert!(!PreparedPassword::new(&[b'x'; 127]).was_truncated());
        assert!(PreparedPassword::new(&[b'x'; 128]).was_truncated());

        // Two passwords sharing their first 127 bytes are the same password.
        let a = PreparedPassword::new(&[vec![b'a'; 127], vec![b'1']].concat());
        let b = PreparedPassword::new(&[vec![b'a'; 127], vec![b'2']].concat());
        assert_eq!(a.as_bytes(), b.as_bytes());
    }

    /// The SASLprep report: ASCII graphic passwords are exact, anything with a
    /// non-ASCII byte or an ASCII control is flagged.
    #[test]
    fn saslprep_relevance_is_reported_for_non_ascii_only() {
        for exact in [
            &b"userpw"[..],
            b"",
            b"a very long ASCII passphrase with spaces",
            b"!@#$%^&*()_+-={}|[]\\:\";'<>?,./",
        ] {
            assert!(
                !PreparedPassword::new(exact).needs_saslprep(),
                "SASLprep is the identity on ASCII graphics: {exact:?}"
            );
        }
        for inexact in [
            "pässwörd".as_bytes(),
            "パスワード".as_bytes(),
            // U+00A0 NO-BREAK SPACE: SASLprep MAPS this to an ordinary space,
            // so a document whose password contains one genuinely cannot be
            // opened without step 1.
            "a\u{00A0}b".as_bytes(),
            &[b'a', 0x01, b'b'],
            // Not valid UTF-8 at all. Still flagged, because step 2 has no
            // defined behaviour for it either.
            &[0xFF, 0xFE],
        ] {
            assert!(
                PreparedPassword::new(inexact).needs_saslprep(),
                "must be flagged: {inexact:?}"
            );
        }
    }
}