flpdf 0.8.0

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
//! Shared encryption state for crypt-filter dispatch and object-key caching.
//!
//! qpdf correspondence: `QPDF.hh:899-923` and `QPDF_encryption.cc:700-1205` encryption state, crypt-filter dispatch, object-key cache, and inspection projection.
//!
//! Deviation: qpdf's AES providers map every key length other than 24 and 32
//! to AES-128 and hand the cipher 16 bytes from the key buffer
//! (`QPDFCrypto_gnutls.cc:197-213`, `QPDFCrypto_openssl.cc:225-241`), so an
//! *object* key shorter than 16 bytes is read past its end. What reaches the
//! provider is the per-object key, not the document key: for `V` below 5
//! [`super::primitives::compute_data_key_qpdf_obj_gen`] appends the object and
//! generation bytes plus `sAlT` and truncates the digest to that input's
//! length, so a document key of 7 bytes already yields a full 16, while for
//! `V` 5 and above the document key is used unchanged. Such a key is
//! reachable through `--password-is-hex-key`, which uses the decoded bytes
//! without a length check (`QPDF_encryption.cc:933-934`).
//!
//! The bytes qpdf reads past the end are undefined, so
//! [`aes128_object_key`] rejects the key instead of fabricating them. Against
//! the qpdf 11.9.0 build used here the exit codes sometimes agree and
//! sometimes do not, and which paths diverge depends on the input as much
//! as on the build: on one file `--check` agreed while the write and
//! `--json` paths differed (0 vs. 2, 0 vs. 3), while on
//! `enc-XI-R6,V5,O=master` all of `--check`, the write path, `--json` and
//! `--show-npages` differed the same way (3 vs. 2), and on
//! `enc-XI-R6,V5,U=attachment,encrypted-attachments` `--json` agreed while
//! the other two differed. An out-of-bounds read has no guaranteed outcome,
//! so none of these pairings is part of the deviation's contract -- they
//! are observations, not a target to port. See
//! `docs/qpdf-correspondence.md` for the corresponding row.
//!

use super::crypt_filters::{
    crypt_filter_method_from_handle, crypt_filter_modes_from_handle,
    interpret_cf_selector_from_handle,
};
use super::password::{decode_hex, password_bytes_for_read, PasswordMode};
use super::permissions::Permissions;
use super::standard::{
    check_owner_password_r5, check_owner_password_r6, check_owner_password_v4_with_user_password,
    check_owner_password_with_user_password, check_user_password, check_user_password_r5,
    check_user_password_r6, check_user_password_v4, StandardHandlerInputs, StandardHandlerR5Inputs,
};
use crate::encryption::standard::{decrypt_cipher_bytes, StringCipher};
use crate::error::{EncryptedError, Result};
use crate::pipeline::aes::PlAesPdf;
use crate::qpdf_obj_gen::QpdfObjGen;
use crate::{ObjectHandle, ObjectRef};
use std::collections::BTreeMap;

/// qpdf's `QPDF::EncryptionParameters` state for an authenticated document.
///
/// qpdf's `encrypted` and `encryption_initialized` flags are folded into this
/// being an `Option<EncryptionState>`; the user password is retained only for
/// qpdf's read-only `getTrimmedUserPassword` inspection contract.
#[derive(Debug, Clone)]
pub(crate) struct EncryptionState {
    pub(crate) file_key: Vec<u8>,
    /// qpdf `encryption_V`.
    pub(crate) encryption_v: i64,
    /// qpdf `cf_stream` / `cf_string`.
    pub(crate) cf_stream: EncryptionMode,
    pub(crate) cf_string: EncryptionMode,
    pub(crate) crypt_filters: BTreeMap<Vec<u8>, EncryptionMode>,
    pub(crate) encrypt_metadata: bool,
    pub(crate) encrypt_ref: Option<ObjectRef>,
    pub(crate) weak_crypto: bool,
    pub(crate) permissions: Permissions,
    /// The `/ID[0]` bytes used to derive `file_key`, when derivation is
    /// `/ID[0]`-dependent (qpdf's Algorithm 2, V<5). `None` for the R5/R6
    /// AES-256 path, which does not read `/ID` at all
    /// (`QPDF_encryption.cc:736-743` computes `id1` unconditionally before
    /// dispatching to a handler, but only the V<5 handler consumes it). A
    /// consumer that must stay paired with `file_key` (for example a
    /// preserve-encryption copy source) must use this cached value instead
    /// of re-reading a possibly-since-mutated live trailer `/ID`.
    pub(crate) id0: Option<Vec<u8>>,
    pub(crate) user_password_matched: bool,
    pub(crate) owner_password_matched: bool,
    /// qpdf `EncryptionParameters::user_password`: padded/recovered for
    /// V<5 owner authentication, supplied bytes for a user-password match,
    /// and empty for V>=5 owner-only or raw-key authentication.
    pub(crate) user_password: Vec<u8>,
    /// qpdf `cached_object_encryption_key` / `cached_key_og`
    /// (`include/qpdf/QPDF.hh:918-919`).
    pub(crate) cached_object_encryption_key: Vec<u8>,
    pub(crate) cached_key_og: Option<QpdfObjGen>,
}

/// What qpdf's crypt-filter switch decided: whether AES is used, whether the
/// caller returns without a decrypt stage, and whether an unknown-filter
/// warning is owed.
type MethodChoice = (Option<bool>, bool);

impl EncryptionState {
    /// qpdf's `decryptString` and `decryptStream` crypt-filter switch
    /// (`QPDF_encryption.cc:982-1006,1062-1134`).
    pub(crate) fn select_method(method: EncryptionMode, encryption_v: i64) -> MethodChoice {
        if encryption_v < 4 {
            // qpdf enters this switch only for V >= 4. Older revisions always
            // use RC4, regardless of the stored crypt-filter fields.
            return (Some(false), false);
        }
        match method {
            EncryptionMode::Identity => (None, false),
            EncryptionMode::Aes128 | EncryptionMode::Aes256 => (Some(true), false),
            EncryptionMode::Rc4 => (Some(false), false),
            EncryptionMode::Unknown => {
                // The caller emits qpdf's warning before committing this
                // fallback. Keeping the decision side-effect free is
                // essential when the warning sink itself fails.
                (Some(true), true)
            }
        }
    }

    /// qpdf `QPDF::decryptString` method selection.
    pub(crate) fn string_method(&self) -> MethodChoice {
        let (method, encryption_v) = (self.cf_string, self.encryption_v);
        Self::select_method(method, encryption_v)
    }

    /// Commit qpdf's unknown `/StrF` fallback after its warning was delivered.
    pub(crate) fn commit_string_method(&mut self) {
        if self.cf_string == EncryptionMode::Unknown {
            self.cf_string = EncryptionMode::Aes128;
        }
    }

    /// qpdf `QPDF::decryptString` cipher operation for one literal string.
    #[allow(dead_code)]
    pub(crate) fn decrypt_object_string(
        &mut self,
        object_ref: ObjectRef,
        bytes: &mut Vec<u8>,
        use_aes: Option<bool>,
    ) -> Result<()> {
        self.decrypt_object_string_qpdf_obj_gen(
            QpdfObjGen::try_from_object_ref(object_ref)?,
            bytes,
            use_aes,
        )
    }

    pub(crate) fn decrypt_object_string_qpdf_obj_gen(
        &mut self,
        object_gen: QpdfObjGen,
        bytes: &mut Vec<u8>,
        use_aes: Option<bool>,
    ) -> Result<()> {
        if let Some(use_aes) = use_aes {
            let key = self.key_for_qpdf_obj_gen(object_gen, use_aes).to_vec();
            if !use_aes {
                decrypt_cipher_bytes(bytes, StringCipher::Rc4 { key: &key })?;
            } else if let Ok(key) = <&[u8; 32]>::try_from(key.as_slice()) {
                decrypt_cipher_bytes(bytes, StringCipher::Aes256 { key })?;
            } else if let Ok(key) = aes192_object_key(&key) {
                decrypt_cipher_bytes(bytes, StringCipher::Aes192 { key: &key })?;
            } else {
                let key = aes128_object_key(&key)?;
                decrypt_cipher_bytes(bytes, StringCipher::Aes128 { key: &key })?;
            }
        }
        Ok(())
    }

    /// qpdf `QPDF::decryptStream` method selection, after the caller has
    /// inspected the stream's own `/Crypt` filter.
    pub(crate) fn stream_method(&self, method: Option<EncryptionMode>) -> MethodChoice {
        let (method, encryption_v) = (method.unwrap_or(self.cf_stream), self.encryption_v);
        Self::select_method(method, encryption_v)
    }

    /// Commit qpdf's unknown `/StmF` fallback after its warning was delivered.
    /// `method` is the stream-local override when one was selected; qpdf still
    /// rewrites the shared default `/StmF` field in that case.
    pub(crate) fn commit_stream_method(&mut self, method: Option<EncryptionMode>) {
        if method.unwrap_or(self.cf_stream) == EncryptionMode::Unknown {
            self.cf_stream = EncryptionMode::Aes128;
        }
    }

    /// qpdf `QPDF::getKeyForObject` cache semantics. The cache key is only the
    /// object/generation pair; `use_aes` is intentionally omitted.
    #[cfg(test)]
    #[allow(dead_code)]
    pub(crate) fn key_for_object(&mut self, og: ObjectRef, use_aes: bool) -> &[u8] {
        self.key_for_qpdf_obj_gen(QpdfObjGen::from_valid_object_ref_for_test(og), use_aes)
    }

    pub(crate) fn key_for_qpdf_obj_gen(&mut self, og: QpdfObjGen, use_aes: bool) -> &[u8] {
        if self.cached_key_og != Some(og) {
            self.cached_object_encryption_key =
                crate::encryption::primitives::compute_data_key_qpdf_obj_gen(
                    &self.file_key,
                    i64::from(og.get_obj()),
                    i64::from(og.get_gen()),
                    use_aes,
                    self.encryption_v,
                );
            self.cached_key_og = Some(og);
        }
        &self.cached_object_encryption_key
    }
}

pub(crate) fn aes128_object_key(key: &[u8]) -> Result<[u8; 16]> {
    match key.len() {
        16 => key.try_into().map_err(|_| unreachable!("length checked")),
        // qpdf's providers map every key length other than 16/24/32 to
        // AES-128 and hand the provider the first 16 bytes
        // (`QPDFCrypto_gnutls.cc:197-213`, `QPDFCrypto_openssl.cc:225-241`).
        // A 32-byte key is dispatched to AES-256 by the caller, and 24 bytes
        // selects AES-192 before reaching this AES-128 helper.
        len if len > 16 && len != 24 && len != 32 => {
            let mut object_key = [0u8; 16];
            object_key.copy_from_slice(&key[..16]);
            Ok(object_key)
        }
        // qpdf-deviation: qpdf's providers read 16 key bytes past the end of a shorter raw key (undefined contents); reject instead of fabricating them
        _ => Err(EncryptedError::Malformed {
            reason: "AES-128 object key is not 16 bytes".into(),
        }
        .into()),
    }
}

pub(crate) fn aes192_object_key(key: &[u8]) -> Result<[u8; 24]> {
    key.try_into().map_err(|_| {
        EncryptedError::Malformed {
            reason: "AES-192 object key is not 24 bytes".into(),
        }
        .into()
    })
}

/// qpdf `QPDF::encryption_method_e` (`QPDF.hh:436`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum EncryptionMode {
    Rc4,
    Aes128,
    Identity,
    Aes256,
    /// Unknown `/CFM` or crypt-filter name. qpdf defers judgment until the
    /// filter is actually referenced.
    Unknown,
}

impl EncryptionMode {
    /// qpdf `show_encryption_method()` spelling.
    pub(crate) fn qpdf_name(self) -> &'static str {
        match self {
            Self::Rc4 => "RC4",
            Self::Aes128 => "AESv2",
            Self::Aes256 => "AESv3",
            Self::Identity => "none",
            Self::Unknown => "unknown",
        }
    }
}

/// qpdf's parsed `EncryptionParameters` projection that exists before
/// password authentication completes. This is intentionally separate from
/// [`EncryptionState`]: an inspection may retain this state after a bad
/// password, but no decryption consumer may see an unauthenticated file key.
#[derive(Debug, Clone)]
pub(crate) struct EncryptionInspectionState {
    pub(crate) v: i64,
    pub(crate) r: i64,
    pub(crate) length_bits: i64,
    pub(crate) permissions: Permissions,
    pub(crate) cf_stream: EncryptionMode,
    pub(crate) cf_string: EncryptionMode,
    pub(crate) crypt_filters: BTreeMap<Vec<u8>, EncryptionMode>,
    pub(crate) stream_method: &'static str,
    pub(crate) string_method: &'static str,
    pub(crate) eff_method: &'static str,
    pub(crate) user_password: Vec<u8>,
    pub(crate) user_password_matched: bool,
    pub(crate) owner_password_matched: bool,
    /// Whether the standard security handler uses RC4 or R=5, matching
    /// [`EncryptionState::weak_crypto`]'s classification. Computed here
    /// (before authentication) from the same revision/crypt-filter fields,
    /// so `Pdf::uses_weak_crypto` can report this after a `BadPassword` open
    /// that never populates the authenticated `EncryptionState`.
    pub(crate) weak_crypto: bool,
}

struct StandardHandlerInputsOwned {
    v: i64,
    r: i64,
    length_bits: i64,
    p: i32,
    id0: Vec<u8>,
    u: [u8; 32],
    o: [u8; 32],
    encrypt_metadata: bool,
}

impl StandardHandlerInputsOwned {
    fn borrowed(&self) -> StandardHandlerInputs<'_> {
        StandardHandlerInputs {
            v: self.v,
            r: self.r,
            length_bits: self.length_bits,
            p: self.p,
            id0: &self.id0,
            u: &self.u,
            o: &self.o,
            encrypt_metadata: self.encrypt_metadata,
        }
    }
}

struct StandardHandlerR5InputsOwned {
    u: [u8; 48],
    o: [u8; 48],
    ue: [u8; 32],
    oe: [u8; 32],
}

impl StandardHandlerR5InputsOwned {
    fn borrowed(&self) -> StandardHandlerR5Inputs<'_> {
        StandardHandlerR5Inputs {
            u: &self.u,
            o: &self.o,
            ue: &self.ue,
            oe: &self.oe,
        }
    }
}

/// Parse the qpdf-owned `/Encrypt` parameters before authentication.
pub(crate) fn parse_inspection_state(encrypt: &ObjectHandle) -> Result<EncryptionInspectionState> {
    let v = required_version_from_handle(encrypt)?;
    let r = required_revision_from_handle(encrypt)?;
    let permissions = Permissions::new(required_permissions_from_handle(encrypt)?);
    required_name_from_handle(encrypt, "Filter")?;
    let length = encrypt.try_get_key(b"/Length")?;
    let length_bits = effective_length_bits(v, &length)?;
    encrypt_metadata_flag_from_handle(encrypt)?;
    let crypt_filters = crypt_filter_modes_from_handle(encrypt, v)?;
    let (cf_stream, cf_string, cf_file) = if matches!(v, 4 | 5) {
        let stream =
            interpret_cf_selector_from_handle(&crypt_filters, &encrypt.try_get_key(b"/StmF")?)?;
        let string =
            interpret_cf_selector_from_handle(&crypt_filters, &encrypt.try_get_key(b"/StrF")?)?;
        let eff = encrypt.try_get_key(b"/EFF")?;
        let file = if eff.try_as_name()?.is_some() {
            interpret_cf_selector_from_handle(&crypt_filters, &eff)?
        } else {
            stream
        };
        (stream, string, file)
    } else {
        (
            EncryptionMode::Identity,
            EncryptionMode::Identity,
            EncryptionMode::Identity,
        )
    };
    let (stream_method, string_method, eff_method) = if matches!(v, 4 | 5) {
        (
            cf_stream.qpdf_name(),
            cf_string.qpdf_name(),
            cf_file.qpdf_name(),
        )
    } else {
        ("none", "none", "none")
    };
    // Same classification `authenticate` computes per version branch
    // (`weak_crypto = revision == 5 || rc4_in_use()` inside the V=5 handler,
    // `rc4_in_use()` alone for V<5) -- password-independent, so it is
    // available before authentication even attempts a candidate. The split is
    // on V rather than R because the R5 weakness belongs to the V=5 AES-256
    // key derivation; a V=4 document keeps Algorithm 2 with its /Length bits
    // whatever R says, and qpdf accepts V=4 with any R in 2..=6
    // (`libqpdf/QPDF_encryption.cc:787`). Splitting on R here would report a
    // V=4/R=5 file as weak after a failed password and not weak after a
    // successful one.
    let effective = |cf: EncryptionMode| {
        if v >= 4 {
            cf
        } else {
            EncryptionMode::Rc4
        }
    };
    let rc4_in_use = matches!(effective(cf_stream), EncryptionMode::Rc4)
        || matches!(effective(cf_string), EncryptionMode::Rc4)
        || crypt_filters
            .values()
            .any(|mode| matches!(mode, EncryptionMode::Rc4));
    let weak_crypto = if v == 5 {
        r == 5 || rc4_in_use
    } else {
        rc4_in_use
    };

    Ok(EncryptionInspectionState {
        v,
        r,
        length_bits,
        permissions,
        cf_stream,
        cf_string,
        crypt_filters,
        stream_method,
        string_method,
        eff_method,
        user_password: Vec::new(),
        user_password_matched: false,
        owner_password_matched: false,
        weak_crypto,
    })
}

/// Result of qpdf's `initializeEncryption` plus password authentication.
pub(crate) struct AuthenticationResult {
    pub(crate) state: EncryptionState,
    pub(crate) perms_warning: Option<String>,
}

/// Authenticate one password candidate and construct the canonical encryption
/// state. The reader supplies only document-owned dictionary values and the
/// canonical `/ID` handle selected from the trailer; all Standard-handler
/// parsing and key derivation stays in this module.
pub(crate) fn authenticate(
    encrypt: &ObjectHandle,
    id: &ObjectHandle,
    encrypt_ref: Option<ObjectRef>,
    password: &[u8],
    password_mode: PasswordMode,
    password_is_hex_key: bool,
) -> Result<AuthenticationResult> {
    let raw_password = password;
    let parsed = parse_inspection_state(encrypt)?;
    let revision = parsed.r;
    let version = parsed.v;
    let permissions = parsed.permissions;
    let cf_stream = parsed.cf_stream;
    let cf_string = parsed.cf_string;
    let crypt_filters = parsed.crypt_filters.clone();

    let effective = |cf: EncryptionMode| {
        if version >= 4 {
            cf
        } else {
            EncryptionMode::Rc4
        }
    };
    let rc4_in_use = || {
        matches!(effective(cf_stream), EncryptionMode::Rc4)
            || matches!(effective(cf_string), EncryptionMode::Rc4)
            || crypt_filters
                .values()
                .any(|mode| matches!(mode, EncryptionMode::Rc4))
    };
    let password = if password_is_hex_key {
        Vec::new()
    } else {
        password_bytes_for_read(password, password_mode)?
    };

    let (
        file_key,
        encrypt_metadata,
        weak_crypto,
        user_password_matched,
        owner_password_matched,
        user_password,
        id0,
    ) = if password_is_hex_key {
        // qpdf `--password-is-hex-key`: the value passed via --password is
        // the precomputed file encryption key as hex, NOT a user/owner
        // password. We skip ALL password→key derivation (Algorithm 2 /
        // 2.A / 2.B / 6 / 7) and the layer-2 user/owner attempt +
        // bad-password ordering block entirely. This is a SEPARATE
        // sibling branch: the `else` below preserves the normal password
        // authentication logic.
        //
        // revision / crypt_filters / encrypt_ref / permissions and the
        // crypt-filter methods are already determined above and do NOT
        // depend on the password. /EncryptMetadata is likewise
        // password-independent; compute it with the SAME revision-aware
        // split layer-2 uses.
        let file_key = decode_hex_file_key(raw_password)?;
        let (encrypt_metadata, weak_crypto, id0) = if version == 5 {
            let encrypt_metadata = encrypt_metadata_flag_from_handle(encrypt)?;
            // Same weak-crypto classification as layer-2's V=5 branch.
            (encrypt_metadata, revision == 5 || rc4_in_use(), None)
        } else {
            let id0 = first_file_id_handle(id)?;
            let inputs = standard_handler_inputs_from_handle(encrypt, &id0)?;
            let borrowed = inputs.borrowed();
            (borrowed.encrypt_metadata, rc4_in_use(), Some(id0))
        };
        // A raw key bypasses authentication, so neither the user nor the
        // owner password was matched. qpdf likewise reports no password
        // match for `--password-is-hex-key`; report both as false.
        (
            file_key,
            encrypt_metadata,
            weak_crypto,
            false,
            false,
            Vec::new(),
            id0,
        )
    } else if version == 5 {
        // Authentication error behavior must match qpdf:
        //
        //   1. Password authentication runs FIRST.  If neither the user nor
        //      the owner password authenticates, return `BadPassword`.
        //   2. A wrong-length `/U` or `/O` entry on this authentication
        //      path is reported as `BadPassword` (an unusable credential
        //      entry is indistinguishable from a wrong password to a
        //      caller), not `Malformed`.  This is scoped to the auth path
        //      via `standard_handler_r5_inputs` (its only caller); all
        //      other `Malformed` reclassification is intentionally NOT done
        //      (e.g. `/UE`/`/OE` length errors stay `Malformed`).
        //
        // Keep this authentication ordering identical in the `else`
        // (V<5 / V=4) branch below.
        let inputs = standard_handler_r5_inputs_from_handle(encrypt)
            .map_err(map_uo_length_to_bad_password)?;
        let encrypt_metadata = encrypt_metadata_flag_from_handle(encrypt)?;
        let inputs = inputs.borrowed();
        let weak_crypto = revision == 5 || rc4_in_use();
        // qpdf's `hash_V5` branches on `R < 6` (`QPDF_encryption.cc:240-251`),
        // so V=5 with R=2..5 uses the single SHA-256 salt hash and only R>=6
        // runs ISO 32000-2 Algorithm 2.B.
        let user_attempt = if revision >= 6 {
            check_user_password_r6(&password, &inputs)
        } else {
            check_user_password_r5(&password, &inputs)
        };
        let owner_attempt = if revision >= 6 {
            check_owner_password_r6(&password, &inputs)
        } else {
            check_owner_password_r5(&password, &inputs)
        };
        let user_password_matched = user_attempt.is_ok();
        let owner_password_matched = owner_attempt.is_ok();
        let file_key = match (user_attempt, owner_attempt) {
            (Ok(key), _) => key,
            (Err(_), Ok(key)) => key,
            (Err(user_err), Err(_owner_err)) => return Err(user_err),
        };
        let user_password = if user_password_matched {
            password.clone()
        } else {
            Vec::new()
        };
        (
            file_key,
            encrypt_metadata,
            weak_crypto,
            user_password_matched,
            owner_password_matched,
            user_password,
            None,
        )
    } else {
        let id0 = first_file_id_handle(id)?;
        let inputs = standard_handler_inputs_from_handle(encrypt, &id0)?;
        let borrowed = inputs.borrowed();
        let encrypt_metadata = borrowed.encrypt_metadata;
        let weak_crypto = rc4_in_use();
        // Password authentication runs before any state is committed, so
        // both failing attempts return `BadPassword`.
        let v4_path = inputs.v == 4 && inputs.r == 4;
        let user_attempt = if v4_path {
            check_user_password_v4(&password, &borrowed)
        } else {
            check_user_password(&password, &borrowed)
        };
        let owner_attempt = if v4_path {
            check_owner_password_v4_with_user_password(&password, &borrowed)
        } else {
            check_owner_password_with_user_password(&password, &borrowed)
        };
        let user_password_matched = user_attempt.is_ok();
        let owner_password_matched = owner_attempt.is_ok();
        let (file_key, user_password) = match (user_attempt, owner_attempt) {
            (Ok(key), _) => (key, password.clone()),
            (Err(_), Ok((key, recovered))) => (key, recovered),
            (Err(user_err), Err(_owner_err)) => return Err(user_err),
        };
        (
            file_key,
            encrypt_metadata,
            weak_crypto,
            user_password_matched,
            owner_password_matched,
            user_password,
            Some(id0),
        )
    };

    // qpdf's raw-key branch bypasses password recovery entirely, including
    // the R=6 /Perms validation that belongs to the password-authenticated
    // path (QPDF_encryption.cc:907-950).
    let perms_warning = if revision == 6 && !password_is_hex_key {
        r6_perms_warning_from_handle(encrypt, &file_key, permissions, encrypt_metadata)?
    } else {
        None
    };
    Ok(AuthenticationResult {
        state: EncryptionState {
            file_key,
            encryption_v: version,
            cf_stream,
            cf_string,
            crypt_filters,
            encrypt_metadata,
            encrypt_ref,
            weak_crypto,
            permissions,
            id0,
            user_password_matched,
            owner_password_matched,
            user_password,
            cached_object_encryption_key: Vec::new(),
            cached_key_og: None,
        },
        perms_warning,
    })
}

fn standard_handler_inputs_from_handle(
    encrypt: &ObjectHandle,
    id0: &[u8],
) -> Result<StandardHandlerInputsOwned> {
    let filter = required_name_from_handle(encrypt, "Filter")?;
    let v = required_integer_from_handle(encrypt, "V")?;
    let r = required_integer_from_handle(encrypt, "R")?;
    if filter != "Standard" || !matches!(v, 1 | 2 | 4) || !(2..=6).contains(&r) {
        return Err(crate::error::EncryptedError::UnsupportedHandler {
            filter,
            v,
            r,
            cfm: crypt_filter_method_from_handle(encrypt)?,
        }
        .into());
    }
    let length = encrypt.try_get_key(b"/Length")?;
    let length_bits = effective_length_bits(v, &length)?;
    let p = required_permissions_from_handle(encrypt)?;
    let u = required_v_lt_5_32_byte_string_from_handle(encrypt, "U")?;
    let o = required_v_lt_5_32_byte_string_from_handle(encrypt, "O")?;
    let encrypt_metadata = encrypt_metadata_flag_from_handle(encrypt)?;
    Ok(StandardHandlerInputsOwned {
        v,
        r,
        length_bits,
        p,
        id0: id0.to_vec(),
        u,
        o,
        encrypt_metadata,
    })
}

/// qpdf's `initializeEncryption` length selection
/// (`QPDF_encryption.cc:835-853`). V=1 always uses 40 bits, V=4 uses 128,
/// and V=5 uses 256. Other versions honor a valid `/Length`; missing,
/// malformed, or out-of-range values fall back to qpdf's 128-bit guess.
pub(crate) fn effective_length_bits(v: i64, length: &ObjectHandle) -> Result<i64> {
    if v <= 1 {
        return Ok(40);
    }
    if v == 4 {
        return Ok(128);
    }
    if v == 5 {
        return Ok(256);
    }
    match length.try_as_integer()? {
        Some(value) if (40..=128).contains(&value) && value % 8 == 0 => Ok(value),
        _ => Ok(128),
    }
}

fn standard_handler_r5_inputs_from_handle(
    encrypt: &ObjectHandle,
) -> Result<StandardHandlerR5InputsOwned> {
    let filter = required_name_from_handle(encrypt, "Filter")?;
    let v = required_integer_from_handle(encrypt, "V")?;
    let r = required_integer_from_handle(encrypt, "R")?;
    if filter != "Standard" || v != 5 || !(2..=6).contains(&r) {
        return Err(crate::error::EncryptedError::UnsupportedHandler {
            filter,
            v,
            r,
            cfm: crypt_filter_method_from_handle(encrypt)?,
        }
        .into());
    }
    Ok(StandardHandlerR5InputsOwned {
        u: required_48_byte_string_from_handle(encrypt, "U")?,
        o: required_48_byte_string_from_handle(encrypt, "O")?,
        ue: required_32_byte_string_from_handle(encrypt, "UE")?,
        oe: required_32_byte_string_from_handle(encrypt, "OE")?,
    })
}

/// Scoped to the V=5 R=5/R=6 authentication path (the sole caller of
/// `standard_handler_r5_inputs`): a `/U` or `/O` entry that is not exactly
/// 48 bytes is an unusable credential entry that is indistinguishable, from a
/// caller's perspective, from supplying the wrong password — qpdf reports
/// "invalid password" here, so we map to `BadPassword` for parity.
///
/// Only the `/U` / `/O` *length* error is remapped. `/UE` / `/OE` length
/// errors, missing entries, and non-string entries stay `Malformed`: those are
/// genuine structural defects, not credential mismatches. No broader
/// `Malformed` reclassification is performed.
fn map_uo_length_to_bad_password(err: crate::Error) -> crate::Error {
    match &err {
        crate::Error::Encrypted(crate::error::EncryptedError::Malformed { reason })
            if reason == "/U entry is not 48 bytes" || reason == "/O entry is not 48 bytes" =>
        {
            crate::error::EncryptedError::BadPassword.into()
        }
        _ => err,
    }
}

fn decode_hex_file_key(raw: &[u8]) -> Result<Vec<u8>> {
    // qpdf stores QUtil::hex_decode's result without imposing the normal
    // Standard-handler key-size limit when --password-is-hex-key is active
    // (QPDF_encryption.cc:933-934). V>=5 object-key derivation returns this
    // raw value unchanged; the crypto provider chooses its own AES fallback
    // when the length is not one of its supported AES sizes.
    Ok(decode_hex(raw))
}

fn required_integer_from_handle(dict: &ObjectHandle, key: &'static str) -> Result<i64> {
    let key_name = format!("/{key}");
    let value = dict.try_get_key(key_name.as_bytes())?;
    match value.try_as_integer()? {
        Some(value) => Ok(value),
        None if value.is_null() => Err(crate::error::EncryptedError::Malformed {
            reason: format!("missing /{key} entry"),
        }
        .into()),
        None => Err(crate::error::EncryptedError::Malformed {
            reason: format!("/{key} entry is not an integer"),
        }
        .into()),
    }
}

fn required_revision_from_handle(encrypt: &ObjectHandle) -> Result<i64> {
    required_integer_from_handle(encrypt, "R")
}

fn required_version_from_handle(encrypt: &ObjectHandle) -> Result<i64> {
    required_integer_from_handle(encrypt, "V")
}

fn required_name_from_handle(dict: &ObjectHandle, key: &'static str) -> Result<String> {
    let key_name = format!("/{key}");
    let value = dict.try_get_key(key_name.as_bytes())?;
    match value.try_as_name()? {
        Some(name) => String::from_utf8(name).map_err(|_| {
            crate::error::EncryptedError::Malformed {
                reason: format!("/{key} entry is not valid UTF-8"),
            }
            .into()
        }),
        None if value.is_null() => Err(crate::error::EncryptedError::Malformed {
            reason: format!("missing /{key} entry"),
        }
        .into()),
        None => Err(crate::error::EncryptedError::Malformed {
            reason: format!("/{key} entry is not a name"),
        }
        .into()),
    }
}

fn required_32_byte_string_from_handle(dict: &ObjectHandle, key: &'static str) -> Result<[u8; 32]> {
    let key_name = format!("/{key}");
    let value = dict.try_get_key(key_name.as_bytes())?;
    let Some(bytes) = value.try_as_string()? else {
        return Err(if value.is_null() {
            crate::error::EncryptedError::Malformed {
                reason: format!("missing /{key} entry"),
            }
        } else {
            crate::error::EncryptedError::Malformed {
                reason: format!("/{key} entry is not a string"),
            }
        }
        .into());
    };
    bytes.as_slice().try_into().map_err(|_| {
        crate::error::EncryptedError::Malformed {
            reason: format!("/{key} entry is not 32 bytes"),
        }
        .into()
    })
}

/// Read a V<5 `/O` or `/U` entry as the fixed 32-byte value qpdf authenticates
/// against, NUL-padding a shorter stored string.
///
/// qpdf's `initializeEncryption` runs `pad_short_parameter`
/// (`QPDF_encryption.cc:316-321`) over both entries at `:807-808` and only then
/// requires exactly 32 bytes, so a longer entry is rejected while a shorter one
/// is accepted and padded.
///
/// The short case is reachable from an ordinary file that authenticates, not
/// only from a synthetic dictionary. At R>=3 `check_user_password_V4`
/// (`QPDF_encryption.cc:511-518`) compares only the leading 16 bytes of `/U`,
/// so a file storing just those 16 bytes opens with its original password; at
/// R=2 the comparison covers all 32 bytes and the same truncation would be
/// rejected. A short `/O` is reachable as well, but only when the bytes it
/// drops are already NUL, because Algorithm 2 hashes the padded `/O` into the
/// file key (`QPDF_encryption.cc:385`) and any other truncation changes the key
/// the file was encrypted with. Such a file keeps its stored length on the way
/// out: `copyEncryptionParameters` re-emits the raw entry
/// (`QPDFWriter.cc:693-694`) rather than this padded projection.
fn required_v_lt_5_32_byte_string_from_handle(
    dict: &ObjectHandle,
    key: &'static str,
) -> Result<[u8; 32]> {
    let key_name = format!("/{key}");
    let value = dict.try_get_key(key_name.as_bytes())?;
    let Some(bytes) = value.try_as_string()? else {
        return Err(if value.is_null() {
            crate::error::EncryptedError::Malformed {
                reason: format!("missing /{key} entry"),
            }
        } else {
            crate::error::EncryptedError::Malformed {
                reason: format!("/{key} entry is not a string"),
            }
        }
        .into());
    };
    if bytes.len() > 32 {
        return Err(crate::error::EncryptedError::Malformed {
            reason: format!("/{key} entry is not 32 bytes"),
        }
        .into());
    }

    // qpdf's pad_short_parameter (QPDF_encryption.cc:316-321) pads short
    // V<5 /O and /U entries with NUL bytes before the exact-size check.
    let mut padded = [0; 32];
    padded[..bytes.len()].copy_from_slice(&bytes);
    Ok(padded)
}

fn required_48_byte_string_from_handle(dict: &ObjectHandle, key: &'static str) -> Result<[u8; 48]> {
    let key_name = format!("/{key}");
    let value = dict.try_get_key(key_name.as_bytes())?;
    let Some(bytes) = value.try_as_string()? else {
        return Err(if value.is_null() {
            crate::error::EncryptedError::Malformed {
                reason: format!("missing /{key} entry"),
            }
        } else {
            crate::error::EncryptedError::Malformed {
                reason: format!("/{key} entry is not a string"),
            }
        }
        .into());
    };
    if bytes.len() < 48 {
        return Err(crate::error::EncryptedError::Malformed {
            reason: format!("/{key} entry is not 48 bytes"),
        }
        .into());
    }
    // cov:ignore-start: the preceding length guard makes this slice exactly 48 bytes
    bytes[..48].try_into().map_err(|_| {
        crate::error::EncryptedError::Malformed {
            reason: format!("/{key} entry is not 48 bytes"),
        }
        .into()
    })
    // cov:ignore-end
}

fn encrypt_metadata_flag_from_handle(encrypt: &ObjectHandle) -> Result<bool> {
    let value = encrypt.try_get_key(b"/EncryptMetadata")?;
    value.try_dereference()?;
    match value.as_boolean() {
        Some(value) => Ok(value),
        None if value.is_null() => Ok(true),
        None => Err(crate::error::EncryptedError::Malformed {
            reason: "/EncryptMetadata entry is not a boolean".into(),
        }
        .into()),
    }
}

fn required_permissions_from_handle(encrypt: &ObjectHandle) -> Result<i32> {
    // qpdf QPDF_encryption.cc:783 uses static_cast<int>(getIntValue())
    // rather than getIntValueAsInt(). Preserve that signed permission
    // bitfield narrowing so an unsigned /P such as 4294967292 becomes -4,
    // matching qpdf on the pinned Linux x86_64 oracle.
    Ok(crate::encryption::qpdf_permission_i32(
        required_integer_from_handle(encrypt, "P")?,
    ))
}

fn r6_perms_warning_from_handle(
    encrypt: &ObjectHandle,
    file_key: &[u8],
    permissions: Permissions,
    encrypt_metadata: bool,
) -> Result<Option<String>> {
    let Some(entries) = encrypt.try_as_dictionary()? else {
        return Ok(None);
    };
    let Some(perms) = entries.get(b"/Perms".as_slice()).cloned() else {
        return Ok(None);
    };
    let Some(bytes) = perms.try_as_string()? else {
        return Ok(Some("R=6 /Perms entry is not a string".into()));
    };
    let Ok(bytes) = <[u8; 16]>::try_from(bytes.as_slice()) else {
        return Ok(Some("R=6 /Perms entry is not 16 bytes".into()));
    };
    let Ok(file_key) = <&[u8; 32]>::try_from(file_key) else {
        return Ok(Some(
            "R=6 /Perms cannot be verified with non-256-bit file key".into(),
        ));
    };
    let decrypted = PlAesPdf::process_to_vec_without_padding(
        "AES /Perms decryption",
        false,
        &bytes,
        file_key,
        1,
        None,
    )?; // cov:ignore: qpdf's fixed AES key, IV, and 16-byte input cannot fail
    let block: [u8; 16] = decrypted
        .try_into()
        .expect("qpdf AES /Perms processing returns one decrypted block");
    let perms_p = i32::from_le_bytes(block[..4].try_into().expect("slice length checked"));
    let perms_metadata = match block[8] {
        b'T' => true,
        b'F' => false,
        _ => {
            return Ok(Some(
                "R=6 /Perms encrypted-metadata flag is not T or F".into(),
            ))
        }
    };
    if perms_p != permissions.raw() {
        return Ok(Some(format!(
            "R=6 /Perms permissions value {perms_p} does not match /P {}",
            permissions.raw()
        )));
    }
    if block[4..8] != [0xff; 4] {
        return Ok(Some("R=6 /Perms reserved bytes are invalid".into()));
    }
    if perms_metadata != encrypt_metadata {
        return Ok(Some(
            "R=6 /Perms encrypted-metadata flag does not match /EncryptMetadata".into(),
        ));
    }
    if &block[9..12] != b"adb" {
        return Ok(Some("R=6 /Perms magic bytes are not 'adb'".into()));
    }
    Ok(None)
}

/// qpdf's `/ID[0]` value and whether the trailer satisfied its two-element
/// array contract. An invalid ID still carries a real empty fallback value;
/// `valid` keeps that value distinct from a valid empty string so the reader
/// can emit qpdf's warning exactly once during encryption initialization.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FirstFileId {
    pub(crate) value: Vec<u8>,
    pub(crate) valid: bool,
}

/// Read qpdf's `/ID[0]` value from the already-selected canonical trailer key.
/// The caller supplies `QPDF::getTrailer().getKey("/ID")` rather than the
/// whole trailer so unrelated entries do not affect this one-value lookup.
///
/// qpdf accepts exactly two array elements and only requires the first element
/// to be a string (`QPDF_encryption.cc:738-746`). Any other shape is a
/// non-fatal warning with an empty `id1` fallback. The second element is not
/// inspected because qpdf does not inspect it either.
pub(crate) fn first_file_id_handle_with_status(id: &ObjectHandle) -> Result<FirstFileId> {
    let Some(ids) = id.try_as_array()? else {
        return Ok(FirstFileId {
            value: Vec::new(),
            valid: false,
        });
    };
    if ids.len() != 2 {
        return Ok(FirstFileId {
            value: Vec::new(),
            valid: false,
        });
    }
    let first = &ids[0];
    first.try_dereference()?;
    let Some(value) = first.as_string() else {
        return Ok(FirstFileId {
            value: Vec::new(),
            valid: false,
        });
    };
    Ok(FirstFileId { value, valid: true })
}

/// Return only qpdf's effective `id1` value for callers that do not own the
/// document warning sink. Invalid trailer shapes intentionally return the
/// empty value selected by qpdf rather than an error.
pub(crate) fn first_file_id_handle(id: &ObjectHandle) -> Result<Vec<u8>> {
    Ok(first_file_id_handle_with_status(id)?.value)
}

#[cfg(test)]
mod tests {
    use super::{
        decode_hex_file_key, parse_inspection_state, required_v_lt_5_32_byte_string_from_handle,
    };
    use crate::ObjectHandle;

    #[test]
    fn v2_missing_length_uses_qpdf_128_bit_fallback() {
        let encrypt = ObjectHandle::dictionary(vec![
            (
                b"/Filter".to_vec(),
                ObjectHandle::name(b"Standard".to_vec()),
            ),
            (b"/V".to_vec(), ObjectHandle::integer(2)),
            (b"/R".to_vec(), ObjectHandle::integer(3)),
            (b"/P".to_vec(), ObjectHandle::integer(-4)),
        ]);

        let state = parse_inspection_state(&encrypt).expect("parse encryption dictionary");

        assert_eq!(state.length_bits, 128);
    }

    /// qpdf accepts V=4 with any R in 2..=6 (`libqpdf/QPDF_encryption.cc:787`),
    /// so a V=4/R=5 AES-only document is a real input. Its weak-crypto
    /// classification has to be the V-based one `authenticate` uses, or the
    /// same file would be reported weak after a failed password and not weak
    /// after a successful one. The R5 weakness belongs to the V=5 AES-256 key
    /// derivation, which a V=4 document never performs.
    #[test]
    fn v4_r5_aes_is_not_weak_before_authentication() {
        let aes_filter = ObjectHandle::dictionary(vec![(
            b"/CFM".to_vec(),
            ObjectHandle::name(b"AESV2".to_vec()),
        )]);
        let encrypt = ObjectHandle::dictionary(vec![
            (
                b"/Filter".to_vec(),
                ObjectHandle::name(b"Standard".to_vec()),
            ),
            (b"/V".to_vec(), ObjectHandle::integer(4)),
            (b"/R".to_vec(), ObjectHandle::integer(5)),
            (b"/P".to_vec(), ObjectHandle::integer(-4)),
            (b"/Length".to_vec(), ObjectHandle::integer(128)),
            (
                b"/CF".to_vec(),
                ObjectHandle::dictionary(vec![(b"/StdCF".to_vec(), aes_filter)]),
            ),
            (b"/StmF".to_vec(), ObjectHandle::name(b"StdCF".to_vec())),
            (b"/StrF".to_vec(), ObjectHandle::name(b"StdCF".to_vec())),
        ]);

        let state = parse_inspection_state(&encrypt).expect("parse encryption dictionary");

        assert_eq!((state.v, state.r), (4, 5));
        assert!(
            !state.weak_crypto,
            "V=4/R=5 with AES filters must not be classified weak"
        );
    }

    /// The V=5 handler keeps R5 marked weak: that revision's AES-256 key
    /// derivation is the broken one.
    #[test]
    fn v5_r5_stays_weak_before_authentication() {
        let encrypt = ObjectHandle::dictionary(vec![
            (
                b"/Filter".to_vec(),
                ObjectHandle::name(b"Standard".to_vec()),
            ),
            (b"/V".to_vec(), ObjectHandle::integer(5)),
            (b"/R".to_vec(), ObjectHandle::integer(5)),
            (b"/P".to_vec(), ObjectHandle::integer(-4)),
        ]);

        let state = parse_inspection_state(&encrypt).expect("parse encryption dictionary");

        assert!(state.weak_crypto, "V=5/R=5 must stay weak");
    }

    #[test]
    fn positive_unsigned_permission_value_wraps_like_qpdf() {
        let encrypt = ObjectHandle::dictionary(vec![
            (
                b"/Filter".to_vec(),
                ObjectHandle::name(b"Standard".to_vec()),
            ),
            (b"/V".to_vec(), ObjectHandle::integer(2)),
            (b"/R".to_vec(), ObjectHandle::integer(3)),
            (b"/P".to_vec(), ObjectHandle::integer(4_294_967_292)),
        ]);

        let state = parse_inspection_state(&encrypt).expect("parse positive /P");

        assert_eq!(state.permissions.raw(), -4);
    }

    #[test]
    fn raw_key_hex_decoding_matches_qpdf_ignored_characters_and_odd_nibbles() {
        assert_eq!(decode_hex_file_key(b"zA-1").unwrap(), vec![0xa1]);
        assert_eq!(decode_hex_file_key(b"F").unwrap(), vec![0xf0]);
    }

    #[test]
    fn v_lt_5_short_standard_entry_is_nul_padded_like_qpdf() {
        let short_u = vec![
            0x82, 0xf8, 0x58, 0xc9, 0x56, 0xfc, 0x27, 0xa1, 0xd0, 0x51, 0xb0, 0x9b, 0xfb, 0x19,
            0xb7, 0x2,
        ];
        let encrypt = ObjectHandle::dictionary(vec![(
            b"/U".to_vec(),
            ObjectHandle::string(short_u.clone()),
        )]);

        let padded = required_v_lt_5_32_byte_string_from_handle(&encrypt, "U")
            .expect("qpdf pads a short V<5 /U entry with NUL bytes");

        assert_eq!(&padded[..short_u.len()], short_u.as_slice());
        assert_eq!(&padded[short_u.len()..], &[0; 32 - 16]);
    }

    #[test]
    fn v_lt_5_missing_standard_entry_is_malformed() {
        let encrypt = ObjectHandle::dictionary(Vec::new());

        let error = required_v_lt_5_32_byte_string_from_handle(&encrypt, "U")
            .expect_err("missing /U must remain malformed");

        assert!(matches!(
            error,
            crate::Error::Encrypted(crate::error::EncryptedError::Malformed { reason })
                if reason == "missing /U entry"
        ));
    }

    #[test]
    fn v_lt_5_non_string_standard_entry_is_malformed() {
        let encrypt = ObjectHandle::dictionary(vec![(b"/U".to_vec(), ObjectHandle::integer(1))]);

        let error = required_v_lt_5_32_byte_string_from_handle(&encrypt, "U")
            .expect_err("non-string /U must remain malformed");

        assert!(matches!(
            error,
            crate::Error::Encrypted(crate::error::EncryptedError::Malformed { reason })
                if reason == "/U entry is not a string"
        ));
    }

    #[test]
    fn v_lt_5_overlength_standard_entry_is_malformed() {
        let encrypt =
            ObjectHandle::dictionary(vec![(b"/U".to_vec(), ObjectHandle::string(vec![0; 33]))]);

        let error = required_v_lt_5_32_byte_string_from_handle(&encrypt, "U")
            .expect_err("overlength /U must remain malformed");

        assert!(matches!(
            error,
            crate::Error::Encrypted(crate::error::EncryptedError::Malformed { reason })
                if reason == "/U entry is not 32 bytes"
        ));
    }
}