flpdf 0.10.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
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
//! Standard Security Handler key derivation for PDF V=1, V=2, V=4, and V=5.
//!
//! qpdf correspondence: QPDF_encryption.cc Standard security handler algorithms split from writer setup.
//!
//! Implements the following algorithms from PDF 1.7 §7.6.3.3:
//! - **Algorithm 2**: Compute the file encryption key from password + dictionary entries.
//! - **Algorithm 6**: Test a user password (returns the file key on success).
//! - **Algorithm 7**: Test an owner password (returns the file key on success).
//!
//! Output is an RC4 file key of 40–128 bits (5–16 bytes).
//!
//! # V=4 Crypt Filter support
//! This module contains the V=4 key derivation shim (`compute_file_key_v4`).
//! Crypt-filter interpretation itself — the `/CF` table walk and the `/StmF`,
//! `/StrF`, `/EFF` use-site selection — lives in
//! [`super::crypt_filters`], mirroring qpdf's split between
//! `QPDF::interpretCF` and the Standard handler's key algorithms.
//!
//! This module provides key derivation only. Parsing of the `/Encrypt`
//! dictionary and end-to-end round-trip decryption are handled elsewhere.
//!
//! # V=5 AES-256 support
//! R=5 is the deprecated pre-ISO 32000-2 AES-256 Standard handler. It uses a
//! single SHA-256 pass over `password || salt` and AES-256-CBC with a zero IV to
//! unwrap the 256-bit file key from `/UE` or `/OE`. New output using this legacy
//! handler must remain behind weak-crypto opt-in if writer support is added.
//! R=6 is the ISO 32000-2 AES-256 Standard handler. It keeps the same dictionary
//! entry shape and replaces the salted hash with Algorithm 2.B's iterative
//! SHA-256/384/512 construction.
//!
//! # Scope
//! V=1/V=2 (R=2/R=3, with V=1 fixed at 40 bits), V=4 (R=4, 128-bit), and
//! V=5 R=5/R=6 AES-256 key derivation are covered here.
//!
//! # Note on end-to-end compatibility
//! The tests here use Python-generated known-answer vectors (see inline
//! comments) to verify algorithmic correctness rather than full
//! qpdf-compatible fixture testing against real encrypted PDF files.
//!
//! # Entry points that qpdf does not have
//! Owner-password authentication has exactly one qpdf entry point,
//! `check_owner_password` (`QPDF_encryption.cc:582-590`), and it always yields
//! the recovered user password through its `std::string& user_password`
//! out-parameter (`QPDF_encryption.cc:542-567`), because the single call site
//! consumes that password immediately afterwards. The tuple-returning
//! [`check_owner_password_with_user_password`] and
//! [`check_owner_password_v4_with_user_password`] are therefore the whole
//! owner-password surface here; no variant discards the recovered password.
//!
//! Likewise there is no identity cipher. qpdf treats a `/Identity` crypt
//! filter by returning from `decryptString` and `decryptStream` before any
//! cipher is constructed (`QPDF_encryption.cc:985-986,1106-1107`), so
//! [`StringCipher`] and [`StringEncryptCipher`] carry cipher material only;
//! the pass-through decision is made by the caller that selects the method.

pub(crate) use super::keys::ObjectKeyAlg;
use crate::encryption::primitives::md5;
use crate::encryption::rc4::Rc4;
use crate::error::{EncryptedError, Result};
use crate::pipeline::aes::PlAesPdf;
use crate::pipeline::sha2::PlSha2;
use crate::pipeline::Pipeline;
use crate::ObjectHandle;

// ────────────────────────────────────────────────────────────────────────────
// Constants
// ────────────────────────────────────────────────────────────────────────────

/// The 32-byte password-padding string from PDF 1.7 §7.6.3.3, Algorithm 2, step 1.
pub(crate) const PASSWORD_PADDING: [u8; 32] = [
    0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
    0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80, 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A,
];

// ────────────────────────────────────────────────────────────────────────────
// Public types
// ────────────────────────────────────────────────────────────────────────────

/// All dictionary-derived inputs needed for V=1/V=2 key derivation.
///
/// Callers are responsible for parsing these fields from the `/Encrypt`
/// dictionary before invoking the functions in this module.
pub(crate) struct StandardHandlerInputs<'a> {
    /// `/V` — algorithm version (1 or 2).
    pub v: i64,
    /// `/R` — revision (2 or 3 for V=1/V=2).
    pub r: i64,
    /// `/Length` in bits (40–128, must be a multiple of 8).
    pub length_bits: i64,
    /// `/P` — permissions flags (signed 32-bit, encoded as 4-byte little-endian).
    pub p: i32,
    /// First element of the `/ID` array.
    pub id0: &'a [u8],
    /// `/U` entry — 32 bytes.
    pub u: &'a [u8; 32],
    /// `/O` entry — 32 bytes.
    pub o: &'a [u8; 32],
    /// `/EncryptMetadata` flag.  For R ≤ 3, this is always treated as `true`
    /// per spec (the 0xFF×4 tail in Algorithm 2 is only appended for R ≥ 4).
    pub encrypt_metadata: bool,
}

/// Dictionary-derived inputs for legacy V=5 R=5 AES-256 key derivation.
///
/// `/U` and `/O` are 48 bytes each: 32-byte validation hash, 8-byte validation
/// salt, and 8-byte file-key salt. `/UE` and `/OE` are the 32-byte AES-256-CBC
/// encrypted file-key entries.
pub(crate) struct StandardHandlerR5Inputs<'a> {
    /// `/U` entry — validation hash, validation salt, key salt.
    pub u: &'a [u8; 48],
    /// `/O` entry — validation hash, validation salt, key salt.
    pub o: &'a [u8; 48],
    /// `/UE` entry — encrypted file key for the user password.
    pub ue: &'a [u8; 32],
    /// `/OE` entry — encrypted file key for the owner password.
    pub oe: &'a [u8; 32],
}

// ────────────────────────────────────────────────────────────────────────────
// Internal helpers
// ────────────────────────────────────────────────────────────────────────────

/// Pad or truncate `password` to exactly 32 bytes using `PASSWORD_PADDING`.
///
/// PDF 1.7 §7.6.3.3 Algorithm 2, step 1:
/// > Pad or truncate the password string to exactly 32 bytes.  If the password
/// > string is more than 32 bytes long, use only its first 32 bytes; if it is
/// > less than 32 bytes long, pad it by appending the required number of
/// > additional bytes from the beginning of the following padding string.
fn pad_password(password: &[u8]) -> [u8; 32] {
    let mut out = [0u8; 32];
    let pw_len = password.len().min(32);
    out[..pw_len].copy_from_slice(&password[..pw_len]);
    if pw_len < 32 {
        let pad_needed = 32 - pw_len;
        out[pw_len..].copy_from_slice(&PASSWORD_PADDING[..pad_needed]);
    }
    out
}

/// Project a `/O` or `/U` entry onto the fixed 32-byte buffer qpdf's V<5
/// key derivation reads.
///
/// qpdf stores `/O` and `/U` in `EncryptionData` as `std::string` and reads
/// exactly `key_bytes` (32) from `c_str()` (`QPDF_encryption.cc:384-385`),
/// so an entry longer than 32 bytes contributes only its first 32 and a
/// shorter one is read past its end. This projection truncates the same way
/// and NUL-pads the short case, matching the decision already recorded for
/// the reader-side entry projection (`state.rs`'s
/// `required_v_lt_5_32_byte_string_from_handle`, qpdf's
/// `pad_short_parameter`, `QPDF_encryption.cc:316-321`).
///
/// The truncating arm is not reachable from a donor that authenticated: both
/// readers NUL-pad a short V<5 `/O`//`U` and then require exactly 32 bytes
/// (`QPDF_encryption.cc:805-813`), so a longer entry fails at open in qpdf
/// and in flpdf alike. It matters only for a caller that builds a
/// copy-encryption source from an arbitrary dictionary.
///
/// The NUL-padding arm is reachable from such a donor, because
/// `copyEncryptionParameters` re-reads the raw entry from the donor's
/// dictionary (`QPDFWriter.cc:693-694`) instead of the padded copy the reader
/// built. A file whose `/U` stores only the leading 16 bytes the R>=3
/// user-password check compares (`QPDF_encryption.cc:511-518`), or whose `/O`
/// drops trailing NUL bytes that this padding restores, opens normally and
/// arrives here at its stored length.
pub(crate) fn v_lt_5_32_byte_parameter(bytes: &[u8]) -> [u8; 32] {
    let mut out = [0u8; 32];
    let len = bytes.len().min(32);
    out[..len].copy_from_slice(&bytes[..len]);
    out
}

/// qpdf's `truncate_password_V5` (`QPDF_encryption.cc:171-174`).
///
/// V=5 password truncation belongs to the reader-side authentication call
/// sites (`QPDF_encryption.cc:520-529`, `:569-579`, and `:665-689`), not to
/// the shared hash primitive used by the writer.
fn truncate_password_v5(password: &[u8]) -> &[u8] {
    &password[..password.len().min(127)]
}

/// Validate `inputs` fields that are in scope for V<5.
///
/// qpdf's `initializeEncryption` accepts every V∈{1,2,4,5} × R∈2..=6
/// (`QPDF_encryption.cc:787-795`); the V<5 branch handles
/// V∈{1,2,4} × R∈2..=6 here with the R-keyed Algorithm 2/6/7 paths
/// (`R>=3` selects the 50-iteration/20-pass form, `R>=4` adds the
/// `/EncryptMetadata` tail). V=5 is handled by the R5/R6 functions.
///
/// The effective `/Length` selection happens in
/// [`super::state::effective_length_bits`] before this validator runs, so
/// only the V=1 (always 40-bit) and structural `[40,128]` checks remain.
fn validate_inputs(inputs: &StandardHandlerInputs<'_>) -> Result<usize> {
    if !matches!(inputs.v, 1 | 2 | 4) {
        return Err(EncryptedError::UnsupportedHandler {
            filter: "Standard".into(),
            v: inputs.v,
            r: inputs.r,
            cfm: None,
        }
        .into());
    }
    // R must be a revision this module handles.
    if !(2..=6).contains(&inputs.r) {
        return Err(EncryptedError::UnsupportedHandler {
            filter: "Standard".into(),
            v: inputs.v,
            r: inputs.r,
            cfm: None,
        }
        .into());
    }
    // qpdf's initializeEncryption selects 40 bits for every V <= 1. The
    // reader-side input object already carries that effective length, so a
    // V=1 value other than 40 bits is an invalid internal projection even
    // though R=3 itself is accepted.
    if inputs.v == 1 && inputs.length_bits != 40 {
        return Err(EncryptedError::UnsupportedHandler {
            filter: "Standard".into(),
            v: inputs.v,
            r: inputs.r,
            cfm: None,
        }
        .into());
    }
    if inputs.length_bits < 40 || inputs.length_bits > 128 || inputs.length_bits % 8 != 0 {
        return Err(EncryptedError::Malformed {
            reason: format!(
                "/Length {} is invalid; must be a multiple of 8 between 40 and 128",
                inputs.length_bits
            ),
        }
        .into());
    }
    Ok((inputs.length_bits / 8) as usize)
}

/// Validate `inputs` for V=4, R=4, Length=128 (the only combination this module
/// supports for the CF-dispatch handler).
///
/// Accepts exactly V=4, R=4, Length=128.  Other combinations return
/// [`EncryptedError::UnsupportedHandler`].
fn validate_v4_inputs(inputs: &StandardHandlerInputs<'_>) -> Result<usize> {
    if inputs.v != 4 || inputs.r != 4 || inputs.length_bits != 128 {
        return Err(EncryptedError::UnsupportedHandler {
            filter: "Standard".into(),
            v: inputs.v,
            r: inputs.r,
            cfm: None,
        }
        .into());
    }
    Ok(16)
}

/// The R<6 result of qpdf's `hash_V5` (`QPDF_encryption.cc:245-251`).
///
/// qpdf streams the three inputs into `Pl_SHA2` as separate writes rather than
/// concatenating them first, so this port does the same.
///
/// # Errors
///
/// Returns [`crate::Error::Internal`] if the SHA-2 pipeline rejects a
/// request, mirroring the `std::logic_error` qpdf's `Pl_SHA2` raises
/// (`Pl_SHA2.cc:53,63`).
fn r5_salted_hash(password: &[u8], salt: &[u8], extra: &[u8]) -> Result<[u8; 32]> {
    let mut hash = PlSha2::new("sha2", None, 256)?;
    hash.write(password)?;
    hash.write(salt)?;
    hash.write(extra)?;
    hash.finish()?;
    let mut key = [0u8; 32];
    key.copy_from_slice(hash.get_raw_digest()?);
    Ok(key)
}

fn aes256_cbc_zero_iv_unwrap(encrypted_key: &[u8; 32], aes_key: &[u8; 32]) -> Result<Vec<u8>> {
    PlAesPdf::process_to_vec_without_padding(
        "AES V=5 file-key unwrap",
        false,
        encrypted_key,
        aes_key,
        1,
        None,
    )
    // cov:ignore-start: the key and 32-byte input are statically valid, so
    // qpdf's Pl_AES_PDF process cannot fail on this production path.
    .map_err(|_| EncryptedError::Malformed {
        reason: "invalid V=5 encrypted file-key entry".into(),
    })
    // cov:ignore-end
    .map_err(Into::into)
}

fn decrypt_r5_file_key(
    password: &[u8],
    entry: &[u8; 48],
    encrypted_key: &[u8; 32],
    extra: &[u8],
) -> Result<Vec<u8>> {
    let validation_salt = &entry[32..40];
    let key_salt = &entry[40..48];

    let validation_hash = r5_salted_hash(password, validation_salt, extra)?;
    if validation_hash[..] != entry[..32] {
        return Err(EncryptedError::BadPassword.into());
    }

    let aes_key = r5_salted_hash(password, key_salt, extra)?;
    aes256_cbc_zero_iv_unwrap(encrypted_key, &aes_key)
}

/// ISO 32000-2 Algorithm 2.B, the R=6 branch of qpdf's `hash_V5`
/// (`QPDF_encryption.cc:256-309`).
///
/// # Errors
///
/// Returns [`crate::Error::Internal`] if the SHA-2 pipeline rejects a
/// request, mirroring the `std::logic_error` qpdf's `Pl_SHA2` raises
/// (`Pl_SHA2.cc:53,63`).
fn r6_password_hash(password: &[u8], salt: &[u8], extra: &[u8]) -> Result<[u8; 32]> {
    // qpdf computes this SHA-256 once in `hash_V5` and only then branches on the
    // revision, so Algorithm 2.B's round 0 is exactly the R<6 value
    // (`QPDF_encryption.cc:245-258`).
    let mut key = r5_salted_hash(password, salt, extra)?.to_vec();

    let mut round_number = 0usize;
    loop {
        round_number += 1;

        let mut k1 = Vec::with_capacity(password.len() + key.len() + extra.len());
        k1.extend_from_slice(password);
        k1.extend_from_slice(&key);
        k1.extend_from_slice(extra);

        let mut aes_key = [0u8; 16];
        aes_key.copy_from_slice(&key[..16]);
        let mut iv = [0u8; 16];
        iv.copy_from_slice(&key[16..32]);
        let e = PlAesPdf::process_to_vec_without_padding(
            "AES R=6 hash",
            true,
            &k1,
            &aes_key,
            64,
            Some(&iv),
        )?; // cov:ignore: qpdf's fixed AES key, IV, and 64 aligned writes cannot fail

        let e_mod_3 = e[..16]
            .iter()
            .fold(0u16, |acc, byte| acc + u16::from(*byte))
            % 3;
        let next_hash = match e_mod_3 {
            0 => 256,
            1 => 384,
            _ => 512,
        };
        let mut sha2 = PlSha2::new("sha2", None, next_hash)?;
        sha2.write(&e)?;
        sha2.finish()?;
        key = sha2.get_raw_digest()?.to_vec();

        if round_number >= 64
            && usize::from(*e.last().expect("R=6 E is non-empty")) <= round_number - 32
        {
            let mut out = [0u8; 32];
            out.copy_from_slice(&key[..32]);
            return Ok(out);
        }
    }
}

fn decrypt_r6_file_key(
    password: &[u8],
    entry: &[u8; 48],
    encrypted_key: &[u8; 32],
    extra: &[u8],
) -> Result<Vec<u8>> {
    let validation_salt = &entry[32..40];
    let key_salt = &entry[40..48];

    let validation_hash = r6_password_hash(password, validation_salt, extra)?;
    if validation_hash[..] != entry[..32] {
        return Err(EncryptedError::BadPassword.into());
    }

    let aes_key = r6_password_hash(password, key_salt, extra)?;
    aes256_cbc_zero_iv_unwrap(encrypted_key, &aes_key)
}

// ────────────────────────────────────────────────────────────────────────────
// Public API
// ────────────────────────────────────────────────────────────────────────────

/// qpdf `QPDF::compute_encryption_key_from_password`
/// (`QPDF_encryption.cc:373-403`) — PDF 1.7 §7.6.3.3 Algorithm 2.
///
/// This is the unvalidated core every V<5 key derivation shares. qpdf applies
/// no handler validation here: the key length is `min(16, /Length / 8)` taken
/// straight from the `EncryptionData` the caller built, so a malformed
/// `/Length` yields a correspondingly short (or truncated) key rather than an
/// error. `QPDFWriter::setEncryptionParametersInternal` (`QPDFWriter.cc:836`)
/// depends on exactly that, since `copyEncryptionParameters`
/// (`QPDFWriter.cc:668-670`) feeds it the donor's raw `/Length` value.
///
/// # Errors
///
/// Returns [`crate::Error::System`] when `/Length` is negative, mirroring the
/// `std::range_error` qpdf's `QIntC::to_size` / `QIntC::to_size` conversions
/// raise for the same value (`QPDF_encryption.cc:181,402`).
pub(crate) fn compute_encryption_key_from_password(
    password: &[u8],
    inputs: &StandardHandlerInputs<'_>,
) -> Result<Vec<u8>> {
    // Step 1: Pad/truncate the password to 32 bytes.
    let padded = pad_password(password);

    // Step 2: Initialise MD5 with padded_password || /O || P (LE) || /ID[0].
    let p_le = inputs.p.to_le_bytes();
    let mut md5_input = Vec::with_capacity(32 + 32 + 4 + inputs.id0.len() + 4);
    md5_input.extend_from_slice(&padded);
    md5_input.extend_from_slice(inputs.o);
    md5_input.extend_from_slice(&p_le);
    md5_input.extend_from_slice(inputs.id0);
    // Step 3 (R≥4 tail): append 0xFF×4 when metadata is left in the clear.
    if inputs.r >= 4 && !inputs.encrypt_metadata {
        md5_input.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]);
    }

    // qpdf's `std::min(sizeof(MD5::Digest), data.getLengthBytes())`.
    let key_len = usize::try_from((inputs.length_bits / 8).min(16)).map_err(|_| {
        crate::Error::System(format!(
            "/Length {} is negative; encryption key length is out of range",
            inputs.length_bits
        ))
    })?;

    // Step 3: Take the MD5 digest.
    let mut digest = md5(&md5_input);

    // Step 4: If revision ≥ 3, do 50 iterations of MD5 on the first key_len bytes.
    if inputs.r >= 3 {
        for _ in 0..50 {
            digest = md5(&digest[..key_len]);
        }
    }

    // Step 5: Return the first key_len bytes as the file encryption key.
    Ok(digest[..key_len].to_vec())
}

/// PDF 1.7 §7.6.3.3 Algorithm 2 — Compute the V=1/V=2 file encryption key.
///
/// Validates the V=1/V=2 handler matrix (a flpdf-side projection of the
/// reader checks qpdf performs in `QPDF::initializeEncryption`, not part of
/// qpdf's derivation function) and then runs the shared core. Validation
/// pins `/Length` to a multiple of 8 in `[40, 128]`, so
/// `min(16, /Length / 8)` is always `/Length / 8` and the delegation is
/// byte-for-byte what this function computed inline before.
///
/// Returns the file encryption key as a `Vec<u8>` of length `length_bits/8`.
pub(crate) fn compute_file_key(
    password: &[u8],
    inputs: &StandardHandlerInputs<'_>,
) -> Result<Vec<u8>> {
    let _n = validate_inputs(inputs)?;
    compute_encryption_key_from_password(password, inputs)
}

/// PDF 1.7 §7.6.3.3 Algorithm 2 (R=4 path) — Compute the V=4 file encryption key.
///
/// This is a thin shim that validates the inputs as V=4/R=4/Length=128 and then
/// runs the same shared Algorithm 2 core as [`compute_file_key`], which already
/// contains the 0xFF×4 tail Algorithm 2 step 3 requires when
/// `!encrypt_metadata && R≥4`. Validation pins `/Length` to 128, so
/// `min(16, /Length / 8)` is 16.
///
/// Returns the 16-byte file encryption key.
pub(crate) fn compute_file_key_v4(
    password: &[u8],
    inputs: &StandardHandlerInputs<'_>,
) -> Result<Vec<u8>> {
    // Validate that inputs are specifically V=4/R=4/Length=128.
    let _n = validate_v4_inputs(inputs)?;
    compute_encryption_key_from_password(password, inputs)
}

/// Authenticate a user password for legacy V=5 R=5 and return the 32-byte file key.
///
/// This is the deprecated pre-ISO 32000-2 AES-256 path: authenticate with
/// `SHA-256(password || /U validation_salt)`, then derive the AES key with
/// `SHA-256(password || /U key_salt)` and decrypt `/UE` with AES-256-CBC using
/// a zero IV.
pub(crate) fn check_user_password_r5(
    password: &[u8],
    inputs: &StandardHandlerR5Inputs<'_>,
) -> Result<Vec<u8>> {
    decrypt_r5_file_key(truncate_password_v5(password), inputs.u, inputs.ue, &[])
}

/// Authenticate an owner password for legacy V=5 R=5 and return the 32-byte file key.
///
/// This mirrors [`check_user_password_r5`] using `/O` salts, `/OE`, and the
/// required `/U` entry suffix in the owner-password hash input.
pub(crate) fn check_owner_password_r5(
    password: &[u8],
    inputs: &StandardHandlerR5Inputs<'_>,
) -> Result<Vec<u8>> {
    decrypt_r5_file_key(
        truncate_password_v5(password),
        inputs.o,
        inputs.oe,
        inputs.u,
    )
}

/// Authenticate a user password for V=5 R=6 and return the 32-byte file key.
///
/// Uses ISO 32000-2 Algorithm 2.B for the validation and file-key hashes, then
/// decrypts `/UE` with AES-256-CBC using a zero IV.
pub(crate) fn check_user_password_r6(
    password: &[u8],
    inputs: &StandardHandlerR5Inputs<'_>,
) -> Result<Vec<u8>> {
    decrypt_r6_file_key(truncate_password_v5(password), inputs.u, inputs.ue, &[])
}

/// Authenticate an owner password for V=5 R=6 and return the 32-byte file key.
///
/// Owner-password hashes include the full 48-byte `/U` entry as the extra input,
/// and the resulting key unwraps `/OE` with AES-256-CBC using a zero IV.
pub(crate) fn check_owner_password_r6(
    password: &[u8],
    inputs: &StandardHandlerR5Inputs<'_>,
) -> Result<Vec<u8>> {
    decrypt_r6_file_key(
        truncate_password_v5(password),
        inputs.o,
        inputs.oe,
        inputs.u,
    )
}

/// PDF 1.7 §7.6.3.3 Algorithm 6 — Authenticate the user password.
///
/// Returns the file encryption key on success, or
/// `Error::Encrypted(EncryptedError::BadPassword)` if the password does not match.
pub(crate) fn check_user_password(
    password: &[u8],
    inputs: &StandardHandlerInputs<'_>,
) -> Result<Vec<u8>> {
    let file_key = compute_file_key(password, inputs)?;

    if inputs.r == 2 {
        // Algorithm 6, step (b) for R=2:
        // Encrypt the padding string with the file key using RC4.
        let mut encrypted = PASSWORD_PADDING;
        let mut cipher = Rc4::new(&file_key)?;
        cipher.process_in_place(&mut encrypted);
        // Compare against /U (all 32 bytes).
        if encrypted[..] != inputs.u[..] {
            return Err(EncryptedError::BadPassword.into());
        }
    } else {
        // Algorithm 6, step (b) for R≥3:
        // 1. MD5(PASSWORD_PADDING || /ID[0])
        let mut md5_input = Vec::with_capacity(32 + inputs.id0.len());
        md5_input.extend_from_slice(&PASSWORD_PADDING);
        md5_input.extend_from_slice(inputs.id0);
        let digest = md5(&md5_input);

        // 2. Encrypt that 16-byte digest with the file key.
        let mut data = digest;
        let mut cipher = Rc4::new(&file_key)?;
        cipher.process_in_place(&mut data);

        // 3. Apply 19 further RC4 passes with (file_key XOR i) for i = 1..=19.
        let mut xor_key = file_key.clone();
        for i in 1_u8..=19 {
            for (byte, &orig) in xor_key.iter_mut().zip(&file_key) {
                *byte = orig ^ i;
            }
            let mut cipher = Rc4::new(&xor_key)?;
            cipher.process_in_place(&mut data);
        }

        // 4. Compare the 16-byte result with the first 16 bytes of /U.
        if data[..] != inputs.u[..16] {
            return Err(EncryptedError::BadPassword.into());
        }
    }

    Ok(file_key)
}

/// PDF 1.7 §7.6.3.3 Algorithm 6 for V=4/R=4 Standard handler inputs.
pub(crate) fn check_user_password_v4(
    password: &[u8],
    inputs: &StandardHandlerInputs<'_>,
) -> Result<Vec<u8>> {
    let file_key = compute_file_key_v4(password, inputs)?;

    let mut md5_input = Vec::with_capacity(32 + inputs.id0.len());
    md5_input.extend_from_slice(&PASSWORD_PADDING);
    md5_input.extend_from_slice(inputs.id0);
    let digest = md5(&md5_input);

    let mut data = digest;
    let mut cipher = Rc4::new(&file_key)?;
    cipher.process_in_place(&mut data);
    let mut xor_key = file_key.clone();
    for i in 1_u8..=19 {
        for (byte, &orig) in xor_key.iter_mut().zip(&file_key) {
            *byte = orig ^ i;
        }
        let mut cipher = Rc4::new(&xor_key)?;
        cipher.process_in_place(&mut data);
    }

    if data[..] != inputs.u[..16] {
        return Err(EncryptedError::BadPassword.into());
    }

    Ok(file_key)
}

/// PDF 1.7 §7.6.3.3 Algorithm 7 — Authenticate the owner password and retain
/// the recovered padded user password for qpdf's `getTrimmedUserPassword`
/// inspection contract.
///
/// Returns the file encryption key and the recovered padded user password on
/// success, or `Error::Encrypted(EncryptedError::BadPassword)` if the password
/// does not match.
pub(crate) fn check_owner_password_with_user_password(
    password: &[u8],
    inputs: &StandardHandlerInputs<'_>,
) -> Result<(Vec<u8>, Vec<u8>)> {
    let n = validate_inputs(inputs)?;

    // Steps 1-2: derive the RC4 key from the (padded) owner password.
    let rc4_key = derive_owner_password_rc4_key(password, inputs.r, n);

    // Step 3: Use the RC4 key to decrypt /O and recover the (padded) user password.
    let mut candidate = *inputs.o; // 32 bytes

    if inputs.r == 2 {
        // Single RC4 pass.
        let mut cipher = Rc4::new(&rc4_key)?;
        cipher.process_in_place(&mut candidate);
    } else {
        // 20 passes in DESCENDING order (i = 19..=0).
        let mut xor_key = rc4_key.clone();
        for i in (0_u8..=19).rev() {
            for (byte, &orig) in xor_key.iter_mut().zip(&rc4_key) {
                *byte = orig ^ i;
            }
            let mut cipher = Rc4::new(&xor_key)?;
            cipher.process_in_place(&mut candidate);
        }
    }

    // Step 4: Use the recovered candidate as the user password in Algorithm 6.
    let file_key = check_user_password(&candidate, inputs)?;
    Ok((file_key, candidate.to_vec()))
}

/// PDF 1.7 §7.6.3.3 Algorithm 7 for V=4/R=4 Standard handler inputs.
///
/// V=4/R=4 counterpart of [`check_owner_password_with_user_password`].
pub(crate) fn check_owner_password_v4_with_user_password(
    password: &[u8],
    inputs: &StandardHandlerInputs<'_>,
) -> Result<(Vec<u8>, Vec<u8>)> {
    let n = validate_v4_inputs(inputs)?;
    let padded_owner = pad_password(password);
    let mut digest = md5(&padded_owner);
    for _ in 0..50 {
        digest = md5(&digest);
    }
    let rc4_key = &digest[..n];
    let mut candidate = *inputs.o;
    let mut xor_key = rc4_key.to_vec();
    for i in (0_u8..=19).rev() {
        for (byte, &orig) in xor_key.iter_mut().zip(rc4_key) {
            *byte = orig ^ i;
        }
        let mut cipher = Rc4::new(&xor_key)?;
        cipher.process_in_place(&mut candidate);
    }
    let file_key = check_user_password_v4(&candidate, inputs)?;
    Ok((file_key, candidate.to_vec()))
}

/// qpdf `QPDF::trim_user_password` (`QPDF_encryption.cc:138-161`).
///
/// The padding suffix is removed only when it begins at a `0x28` byte and the
/// remaining bytes match the corresponding prefix of the PDF password padding
/// constant. Otherwise the original bytes are preserved.
pub(crate) fn trim_user_password(password: &[u8]) -> Vec<u8> {
    if password.len() < PASSWORD_PADDING.len() {
        return password.to_vec();
    }
    for index in 0..password.len() {
        if password[index] == PASSWORD_PADDING[0]
            && password.len() - index <= PASSWORD_PADDING.len()
            && password[index..] == PASSWORD_PADDING[..password.len() - index]
        {
            return password[..index].to_vec();
        }
    }
    password.to_vec()
}

// ────────────────────────────────────────────────────────────────────────────
// Writer side — /Encrypt dictionary construction (V=1/V=2)
// ────────────────────────────────────────────────────────────────────────────

/// Inputs for building a V=1 or V=2 `/Encrypt` dictionary via
/// [`build_v1_v2_encrypt_dict`].
///
/// This writer-side matrix is intentionally narrower than the reader-side
/// [`StandardHandlerInputs`] matrix: writer generation keeps V=1 at R=2,
/// while the reader also accepts qpdf's V=1/R=3 input form. V=2 accepts
/// R∈{2,3}, with R=2 fixed at Length=40 and R=3 spanning Length∈`[40,128]`
/// in 8-bit steps.
pub(crate) struct V1V2EncryptParams<'a> {
    /// `/V` — algorithm version (1 or 2).
    pub v: i64,
    /// `/R` — revision (2 or 3 for V=1/V=2).
    pub r: i64,
    /// `/Length` in bits (40–128, must be a multiple of 8).
    pub length_bits: i64,
    /// Raw bytes of the user password (post-`PasswordMode` normalization).
    pub user_password: &'a [u8],
    /// Raw bytes of the owner password. Empty falls back to `user_password`
    /// per Algorithm 3 step 1.
    pub owner_password: &'a [u8],
    /// `/P` permission flags (signed 32-bit).
    pub p: i32,
    /// First element of the `/ID` array. Required by Algorithms 2 and 5.
    pub id0: &'a [u8],
}

/// Derive the owner-password RC4 key shared by Algorithm 3 (writer: encrypt
/// padded user password → `/O`) and Algorithm 7 (reader: decrypt `/O` →
/// padded user password).
///
/// Pads `password` to 32 bytes, takes MD5, and for R≥3 iterates 50 further
/// MD5 passes over the FULL 16-byte digest (NOT the n-truncated prefix; see
/// the `alg3_owner_key_iteration_uses_full_digest_for_short_keys` regression
/// test). Returns the first `n` bytes.
fn derive_owner_password_rc4_key(password: &[u8], r: i64, n: usize) -> Vec<u8> {
    let padded = pad_password(password);
    let mut digest = md5(&padded);
    if r >= 3 {
        for _ in 0..50 {
            digest = md5(&digest);
        }
    }
    digest[..n].to_vec()
}

/// Compute the first 16 bytes of `/U` for R≥3 (Algorithm 5, steps 1-4).
///
/// Shared by the writer ([`compute_u_entry`]) and the reader
/// ([`check_user_password`] R≥3 branch); the writer emits these bytes as the
/// first 16 of `/U`, the reader compares them against the first 16 of the
/// stored `/U`.
fn compute_u_first_16_r3plus(file_key: &[u8], id0: &[u8]) -> Result<[u8; 16]> {
    let mut md5_input = Vec::with_capacity(32 + id0.len());
    md5_input.extend_from_slice(&PASSWORD_PADDING);
    md5_input.extend_from_slice(id0);
    let mut data = md5(&md5_input);

    let mut cipher = Rc4::new(file_key)?;
    cipher.process_in_place(&mut data);
    let mut xor_key = file_key.to_vec();
    for i in 1_u8..=19 {
        for (byte, &orig) in xor_key.iter_mut().zip(file_key) {
            *byte = orig ^ i;
        }
        let mut cipher = Rc4::new(&xor_key)?;
        cipher.process_in_place(&mut data);
    }
    Ok(data)
}

/// Validate `params` for V=1/V=2 writer side. Mirrors the reader-side
/// [`validate_inputs`] V/R/Length matrix.
fn validate_v1_v2_params(params: &V1V2EncryptParams<'_>) -> Result<usize> {
    let unsupported = || -> crate::error::Error {
        EncryptedError::UnsupportedHandler {
            filter: "Standard".into(),
            v: params.v,
            r: params.r,
            cfm: None,
        }
        .into()
    };

    if params.v != 1 && params.v != 2 {
        return Err(unsupported());
    }
    if params.r != 2 && params.r != 3 {
        return Err(unsupported());
    }
    // V=1 is fixed at R=2 / Length=40 by spec.
    if params.v == 1 && (params.r != 2 || params.length_bits != 40) {
        return Err(unsupported());
    }
    // R=2 is a 40-bit revision regardless of V.
    if params.r == 2 && params.length_bits != 40 {
        return Err(unsupported());
    }
    if params.length_bits < 40 || params.length_bits > 128 || params.length_bits % 8 != 0 {
        return Err(EncryptedError::Malformed {
            reason: format!(
                "/Length {} is invalid; must be a multiple of 8 between 40 and 128",
                params.length_bits
            ),
        }
        .into());
    }
    Ok((params.length_bits / 8) as usize)
}

/// Guard for [`compute_o_entry`] / [`compute_u_entry`]: the writer-side
/// Algorithm 3 / 5 paths are defined only for the V<5 Standard handler
/// revisions (r ∈ {2, 3, 4}). V=5 R=5/R=6 use a wholly different family
/// (Algorithms 2.A/2.B/8/9) and dispatch via separate writer functions
/// (e.g. `compute_u_ue_r6`); silently routing an
/// r=5 (or any other) value through the R≥3 branch would produce
/// well-formed but cryptographically wrong bytes.
fn ensure_v_lt_5_revision(r: i64, entry: &str) -> Result<()> {
    if matches!(r, 2..=4) {
        Ok(())
    } else {
        Err(EncryptedError::Malformed {
            reason: format!(
                "/R {r} is unsupported for {entry} computation; expected one of 2, 3, 4"
            ),
        }
        .into())
    }
}

/// PDF 1.7 §7.6.3.4 Algorithm 3 — Compute the 32-byte `/O` (owner password)
/// entry for the Standard handler when V<5.
///
/// `n` is the file-key length in bytes (5 for V=1; 5..=16 for V=2; 16 for
/// V=4). The algorithm is independent of the file encryption key: it derives
/// an RC4 key from the owner password (using [`derive_owner_password_rc4_key`])
/// and encrypts the padded user password with it (single pass for R=2; 20
/// ascending passes for R≥3, the inverse of Algorithm 7's descending passes
/// in [`check_owner_password_with_user_password`] /
/// [`check_owner_password_v4_with_user_password`]).
///
/// Accepts r ∈ {2, 3, 4}; any other revision is rejected with
/// [`EncryptedError::Malformed`]. V=4/R=4 uses the same Algorithm 3 path as
/// R=3. V=5 R=5/R=6 use a wholly different algorithm (Algorithm 2.A/2.B)
/// and are not handled here.
///
/// If `owner_password` is empty, the user password is used instead per
/// Algorithm 3 step 1.
pub(crate) fn compute_o_entry(
    user_password: &[u8],
    owner_password: &[u8],
    r: i64,
    n: usize,
) -> Result<[u8; 32]> {
    ensure_v_lt_5_revision(r, "/O")?;

    let effective_owner: &[u8] = if owner_password.is_empty() {
        user_password
    } else {
        owner_password
    };

    let rc4_key = derive_owner_password_rc4_key(effective_owner, r, n);

    let mut buf: [u8; 32] = pad_password(user_password);
    if r == 2 {
        let mut cipher = Rc4::new(&rc4_key)?;
        cipher.process_in_place(&mut buf);
    } else {
        let mut xor_key = rc4_key.clone();
        for i in 0_u8..=19 {
            for (byte, &orig) in xor_key.iter_mut().zip(&rc4_key) {
                *byte = orig ^ i;
            }
            let mut cipher = Rc4::new(&xor_key)?;
            cipher.process_in_place(&mut buf);
        }
    }
    Ok(buf)
}

/// PDF 1.7 §7.6.3.4 Algorithms 4 (R=2) and 5 (R≥3) — Compute the 32-byte
/// `/U` (user password) entry for the Standard handler when V<5.
///
/// Accepts r ∈ {2, 3, 4}; any other revision is rejected with
/// [`EncryptedError::Malformed`]. V=4/R=4 uses the same Algorithm 5 path
/// as R=3. V=5 R=5/R=6 derive `/U` differently (Algorithm 8) and are not
/// handled here.
///
/// For R≥3 ISO 32000-1 Algorithm 5 mandates only the first 16 bytes and
/// leaves the remaining 16 arbitrary. Readers — including
/// [`check_user_password`] — ignore them, so any filler round-trips, but the
/// bytes are written into the file: they are `(i * i) % 0xff` for `i` in
/// `16..32`, which is what qpdf writes (`libqpdf/QPDF_encryption.cc:492-496`,
/// whose own comment is "pad with arbitrary data -- make it consistent for
/// the sake of testing").
pub(crate) fn compute_u_entry(file_key: &[u8], id0: &[u8], r: i64) -> Result<[u8; 32]> {
    ensure_v_lt_5_revision(r, "/U")?;

    if r == 2 {
        let mut buf = PASSWORD_PADDING;
        let mut cipher = Rc4::new(file_key)?;
        cipher.process_in_place(&mut buf);
        Ok(buf)
    } else {
        let first16 = compute_u_first_16_r3plus(file_key, id0)?;
        let mut u = [0u8; 32];
        u[..16].copy_from_slice(&first16);
        for (i, byte) in u.iter_mut().enumerate().skip(16) {
            // qpdf `QPDF_encryption.cc:494-496`. Note `% 0xff`, not `% 0x100`.
            *byte = u8::try_from((i * i) % 0xff).expect("(i * i) % 255 < 256");
        }
        Ok(u)
    }
}

/// Construct the `/Encrypt` dictionary for V=1 or V=2 from passwords and
/// permissions, returning the dictionary and the derived file encryption key.
///
/// The file key is returned alongside the dictionary because the
/// string/stream encryption passes need it
/// to derive per-object keys via [`super::primitives::compute_data_key`];
/// the dictionary alone does not carry it.
///
/// Algorithmic order: `/O` (Algorithm 3) → file key (Algorithm 2, consumes
/// `/O`) → `/U` (Algorithm 4/5, consumes file key). Each step's output is an
/// input to the next.
pub(crate) fn build_v1_v2_encrypt_dict(
    params: &V1V2EncryptParams<'_>,
) -> Result<(ObjectHandle, Vec<u8>)> {
    let n = validate_v1_v2_params(params)?;

    // Algorithm 3: /O.
    let o_entry = compute_o_entry(params.user_password, params.owner_password, params.r, n)?;

    // Algorithm 2: file encryption key (uses /O).
    //
    // `dummy_u` is a placeholder for `StandardHandlerInputs.u`. `compute_file_key`
    // does not read `u` — Algorithm 2 only consumes `/O`, `/P`, `/ID[0]`, and
    // `/EncryptMetadata` — so any 32 bytes are safe here. If that ever changes,
    // the `compute_u_entry` call below (which depends on this file key) would
    // see a stale key and the round-trip tests in this module would fail.
    let dummy_u = [0u8; 32];
    let inputs = StandardHandlerInputs {
        v: params.v,
        r: params.r,
        length_bits: params.length_bits,
        p: params.p,
        id0: params.id0,
        u: &dummy_u,
        o: &o_entry,
        // V<5 R<4: the 0xFF×4 tail is not appended; /EncryptMetadata is
        // unused by Algorithm 2 for these revisions.
        encrypt_metadata: true,
    };
    let file_key = compute_file_key(params.user_password, &inputs)?;

    // Algorithm 4 (R=2) or Algorithm 5 (R=3): /U.
    let u_entry = compute_u_entry(&file_key, params.id0, params.r)?;

    let dict = ObjectHandle::dictionary(vec![
        (b"Filter".to_vec(), ObjectHandle::name(b"Standard".to_vec())),
        (b"V".to_vec(), ObjectHandle::integer(params.v)),
        (b"R".to_vec(), ObjectHandle::integer(params.r)),
        (
            b"Length".to_vec(),
            ObjectHandle::integer(params.length_bits),
        ),
        (b"P".to_vec(), ObjectHandle::integer(i64::from(params.p))),
        (b"U".to_vec(), ObjectHandle::string(u_entry.to_vec())),
        (b"O".to_vec(), ObjectHandle::string(o_entry.to_vec())),
    ]);

    Ok((dict, file_key))
}

// ────────────────────────────────────────────────────────────────────────────
// Writer side — /Encrypt dictionary construction (V=4 CF)
// ────────────────────────────────────────────────────────────────────────────

/// Cipher method selected for V=4's single named crypt filter (`/StdCF`).
///
/// Only RC4-128 (`/CFM /V2`) and AES-128 (`/CFM /AESV2`) are emitted by
/// [`build_v4_encrypt_dict`]; `/Identity` is a use-site selector, never a
/// filter method.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum V4CryptMethod {
    /// `/CFM /V2` — RC4-128.
    Rc4,
    /// `/CFM /AESV2` — AES-128 CBC.
    Aes,
}

impl V4CryptMethod {
    fn cfm_name(self) -> &'static [u8] {
        match self {
            V4CryptMethod::Rc4 => b"V2",
            V4CryptMethod::Aes => b"AESV2",
        }
    }
}

/// Inputs for building a V=4 `/Encrypt` dictionary via [`build_v4_encrypt_dict`].
///
/// V=4 is fixed at R=4 and Length=128 (16-byte file key); only the cipher
/// method (`V2` vs `AESV2`) and `/EncryptMetadata` vary. Per qpdf's emit
/// behavior, this builder produces a single `/StdCF` entry that both
/// `/StmF` and `/StrF` reference; `/EFF` is omitted (PDF default is
/// `/EFF` ⇒ `/StmF` fallback).
pub(crate) struct V4EncryptParams<'a> {
    /// Cipher method for the `/StdCF` entry.
    pub method: V4CryptMethod,
    /// Raw bytes of the user password (post-`PasswordMode` normalization).
    pub user_password: &'a [u8],
    /// Raw bytes of the owner password. Empty falls back to `user_password`
    /// per Algorithm 3 step 1.
    pub owner_password: &'a [u8],
    /// `/P` permission flags (signed 32-bit).
    pub p: i32,
    /// First element of the `/ID` array. Required by Algorithms 2 and 5.
    pub id0: &'a [u8],
    /// `/EncryptMetadata` flag. When `false`, Algorithm 2 step 3 appends
    /// `0xFF×4` to the file-key MD5 input AND the `/Metadata` stream is
    /// left unencrypted by the stream-encryption pass. When
    /// `true` (the spec default), the key is emitted without the suffix and
    /// the `/Metadata` stream is encrypted; the entry itself is omitted from
    /// the dictionary to match qpdf's defaults-elision.
    pub encrypt_metadata: bool,
}

/// Construct the `/Encrypt` dictionary for V=4 from passwords, permissions,
/// and a crypt-filter method, returning the dictionary and the derived
/// 16-byte file encryption key.
///
/// Algorithmic order mirrors [`build_v1_v2_encrypt_dict`]: `/O` (Algorithm 3,
/// shared via [`compute_o_entry`]) → file key (Algorithm 2 V=4 path via
/// [`compute_file_key_v4`], which honors `encrypt_metadata`) → `/U`
/// (Algorithm 5, shared via [`compute_u_entry`]).
///
/// The emitted dictionary follows qpdf's defaults-elision: when
/// `encrypt_metadata` is the spec default `true`, the `/EncryptMetadata`
/// entry is omitted entirely. `/EFF` is also omitted because the PDF
/// default (`/EFF` absent ⇒ `/StmF`) already covers embedded files with
/// the same filter.
pub(crate) fn build_v4_encrypt_dict(
    params: &V4EncryptParams<'_>,
) -> Result<(ObjectHandle, Vec<u8>)> {
    let n: usize = 16; // V=4 is fixed at Length=128 (16 bytes).

    // Algorithm 3: /O.
    let o_entry = compute_o_entry(params.user_password, params.owner_password, 4, n)?;

    // Algorithm 2 (V=4 path): file encryption key (uses /O + /EncryptMetadata).
    // See `build_v1_v2_encrypt_dict` for why `dummy_u` is safe.
    let dummy_u = [0u8; 32];
    let inputs = StandardHandlerInputs {
        v: 4,
        r: 4,
        length_bits: 128,
        p: params.p,
        id0: params.id0,
        u: &dummy_u,
        o: &o_entry,
        encrypt_metadata: params.encrypt_metadata,
    };
    let file_key = compute_file_key_v4(params.user_password, &inputs)?;

    // Algorithm 5: /U.
    let u_entry = compute_u_entry(&file_key, params.id0, 4)?;

    // /CF /StdCF entry.
    let std_cf = ObjectHandle::dictionary(vec![
        (
            b"AuthEvent".to_vec(),
            ObjectHandle::name(b"DocOpen".to_vec()),
        ),
        (
            b"CFM".to_vec(),
            ObjectHandle::name(params.method.cfm_name().to_vec()),
        ),
        (b"Length".to_vec(), ObjectHandle::integer(16)),
    ]);
    let cf = ObjectHandle::dictionary(vec![(b"StdCF".to_vec(), std_cf)]);
    let mut entries = vec![
        (b"CF".to_vec(), cf),
        (b"Filter".to_vec(), ObjectHandle::name(b"Standard".to_vec())),
        (b"Length".to_vec(), ObjectHandle::integer(128)),
        (b"O".to_vec(), ObjectHandle::string(o_entry.to_vec())),
        (b"P".to_vec(), ObjectHandle::integer(i64::from(params.p))),
        (b"R".to_vec(), ObjectHandle::integer(4)),
        (b"StmF".to_vec(), ObjectHandle::name(b"StdCF".to_vec())),
        (b"StrF".to_vec(), ObjectHandle::name(b"StdCF".to_vec())),
        (b"U".to_vec(), ObjectHandle::string(u_entry.to_vec())),
        (b"V".to_vec(), ObjectHandle::integer(4)),
    ];
    if !params.encrypt_metadata {
        entries.push((b"EncryptMetadata".to_vec(), ObjectHandle::boolean(false)));
    }
    let dict = ObjectHandle::dictionary(entries);

    Ok((dict, file_key))
}

// ────────────────────────────────────────────────────────────────────────────
// Writer side — V=5 R=6 /Encrypt dictionary + /Perms blob
// (Algorithm 10)
// ────────────────────────────────────────────────────────────────────────────

/// ISO 32000-2 Algorithm 10 — Encode and AES-256-encrypt the 16-byte
/// `/Perms` block.
///
/// Plaintext layout (PDF 1.7 §7.6.4.6 / ISO 32000-2 §7.6.4.4.5):
///
/// | Bytes | Content                                                    |
/// |-------|------------------------------------------------------------|
/// | 0..4  | `/P` as a signed 32-bit little-endian integer              |
/// | 4..8  | `0xFF` × 4 (sign-extension of `/P` into the unsigned word) |
/// | 8     | `b'T'` if `encrypt_metadata`, else `b'F'`                  |
/// | 9..12 | ASCII magic `b"adb"`                                       |
/// | 12..16| `random_tail` (spec-arbitrary; round-tripped opaquely)     |
///
/// qpdf sends the block through `process_with_aes` with a zero IV and disabled
/// padding (`QPDF_encryption.cc:655-663`). For this one block that is
/// byte-equivalent to AES-256 ECB, but the pipeline route preserves qpdf's
/// ownership and error contract. Verified by the reader via the inverse path
/// in `r6_perms_warning`.
pub(crate) fn compute_perms_blob(
    p: i32,
    encrypt_metadata: bool,
    random_tail: &[u8; 4],
    file_key: &[u8; 32],
) -> Result<[u8; 16]> {
    let mut block = [0u8; 16];
    block[0..4].copy_from_slice(&p.to_le_bytes());
    block[4..8].copy_from_slice(&[0xFF; 4]);
    block[8] = if encrypt_metadata { b'T' } else { b'F' };
    block[9..12].copy_from_slice(b"adb");
    block[12..16].copy_from_slice(random_tail);
    let encrypted = PlAesPdf::process_to_vec_without_padding(
        "AES /Perms encryption",
        true,
        &block,
        file_key,
        1,
        None,
    )?; // cov:ignore: qpdf's fixed AES key, IV, and one-block input cannot fail
    Ok(encrypted
        .try_into()
        .expect("qpdf AES /Perms processing returns one encrypted block"))
}

/// Wrap `file_key` for a V=5 R=6 password using a zero IV and AES-256-CBC
/// with no padding (exactly 32 plaintext bytes → 32 ciphertext bytes).
///
/// Shared by Algorithm 8 (writer-side `/UE`) and Algorithm 9 (writer-side
/// `/OE`); the reverse path is [`aes256_cbc_zero_iv_unwrap`].
fn aes256_cbc_zero_iv_wrap(file_key: &[u8; 32], aes_key: &[u8; 32]) -> Result<[u8; 32]> {
    let ciphertext = PlAesPdf::process_to_vec_without_padding(
        "AES V=5 file-key wrap",
        true,
        file_key,
        aes_key,
        1,
        None,
    )?; // cov:ignore: qpdf's fixed AES key and 32-byte input cannot fail
    Ok(ciphertext
        .try_into()
        .expect("qpdf AES file-key wrapping returns two encrypted blocks"))
}

/// ISO 32000-2 Algorithm 8 — Compute the V=5 R=6 `/U` and `/UE` entries.
///
/// Returns `(u_entry, ue_entry)`:
///
/// - `u_entry` (48 bytes): `validation_hash` (32) ‖ `validation_salt` (8) ‖
///   `key_salt` (8).
/// - `ue_entry` (32 bytes): AES-256-CBC(zero IV, key = `r6_password_hash(
///   user_password, key_salt, &[])`) over `file_key`.
///
/// `validation_salt` and `key_salt` are spec-mandated random 8-byte values;
/// `file_key` is a spec-mandated random 32-byte value. The caller supplies
/// them so that production callers can use a CSPRNG and tests can use
/// fixed bytes for reproducibility.
///
/// # Errors
///
/// Returns [`crate::Error::Internal`] if the SHA-2 pipeline rejects a
/// request, mirroring the `std::logic_error` qpdf's `Pl_SHA2` raises
/// (`Pl_SHA2.cc:53,63`).
pub(crate) fn compute_u_ue_r6(
    user_password: &[u8],
    file_key: &[u8; 32],
    validation_salt: &[u8; 8],
    key_salt: &[u8; 8],
) -> Result<([u8; 48], [u8; 32])> {
    let validation_hash = r6_password_hash(user_password, validation_salt, &[])?;
    let aes_key = r6_password_hash(user_password, key_salt, &[])?;
    let ue_entry = aes256_cbc_zero_iv_wrap(file_key, &aes_key)?;

    let mut u_entry = [0u8; 48];
    u_entry[0..32].copy_from_slice(&validation_hash);
    u_entry[32..40].copy_from_slice(validation_salt);
    u_entry[40..48].copy_from_slice(key_salt);
    Ok((u_entry, ue_entry))
}

/// ISO 32000-2 Algorithm 9 — Compute the V=5 R=6 `/O` and `/OE` entries.
///
/// Mirrors [`compute_u_ue_r6`] using `owner_password`, the matching salts,
/// and with `user_entry` (the full 48-byte `/U`) appended to the hash
/// inputs, per the spec's "extra" parameter. `/U` must therefore be
/// computed first.
///
/// # Errors
///
/// Returns [`crate::Error::Internal`] if the SHA-2 pipeline rejects a
/// request, mirroring the `std::logic_error` qpdf's `Pl_SHA2` raises
/// (`Pl_SHA2.cc:53,63`).
pub(crate) fn compute_o_oe_r6(
    owner_password: &[u8],
    user_entry: &[u8; 48],
    file_key: &[u8; 32],
    validation_salt: &[u8; 8],
    key_salt: &[u8; 8],
) -> Result<([u8; 48], [u8; 32])> {
    let validation_hash = r6_password_hash(owner_password, validation_salt, user_entry)?;
    let aes_key = r6_password_hash(owner_password, key_salt, user_entry)?;
    let oe_entry = aes256_cbc_zero_iv_wrap(file_key, &aes_key)?;

    let mut o_entry = [0u8; 48];
    o_entry[0..32].copy_from_slice(&validation_hash);
    o_entry[32..40].copy_from_slice(validation_salt);
    o_entry[40..48].copy_from_slice(key_salt);
    Ok((o_entry, oe_entry))
}

/// User-supplied configuration for [`build_v5_r6_encrypt_dict`].
///
/// Passwords are consumed as the byte strings supplied by the caller. The
/// qpdf 11.9.0 reader validates Unicode-mode input as UTF-8 but does not apply
/// SASLprep before V=5 authentication; this lower-level builder likewise does
/// not normalize or truncate its inputs.
pub(crate) struct V5R6EncryptParams<'a> {
    /// User password bytes. Writer-side Algorithm 2.B consumes all supplied
    /// bytes; the reader-side authentication entry points apply the qpdf
    /// 127-byte prefix rule before hashing.
    pub user_password: &'a [u8],
    /// Owner password bytes. Unlike V<5 there is no empty-owner fallback to
    /// the user password — the caller decides what to pass.
    pub owner_password: &'a [u8],
    /// `/P` permission flags (signed 32-bit, also encoded into `/Perms`).
    pub p: i32,
    /// `/EncryptMetadata` flag. Encoded into `/Perms` byte 8 (`'T'`/`'F'`)
    /// and into the dictionary as `/EncryptMetadata false` when false; the
    /// spec-default `true` is omitted to match qpdf.
    pub encrypt_metadata: bool,
}

/// Spec-random secret material consumed by [`build_v5_r6_encrypt_dict`].
///
/// Pulled out into a separate struct so production callers can fill it
/// from a CSPRNG and tests can pin every byte to a fixed value for
/// reproducibility — V=5 R=6 has no path to byte-identical output with
/// qpdf without controlling every random input.
///
/// Fields are owned (not `&'a`) because every field is a small `Copy`
/// array — pass-by-value avoids dragging a lifetime parameter through
/// the call sites without changing the cost (32+8+8+8+8+4 = 68 bytes).
#[derive(Debug, Clone, Copy)]
pub(crate) struct V5R6Secrets {
    /// 32-byte file encryption key (the "FEK"). Random per spec.
    pub file_key: [u8; 32],
    /// 8-byte validation salt for the user password (`/U[32..40]`).
    pub user_validation_salt: [u8; 8],
    /// 8-byte key-derivation salt for the user password (`/U[40..48]`).
    pub user_key_salt: [u8; 8],
    /// 8-byte validation salt for the owner password (`/O[32..40]`).
    pub owner_validation_salt: [u8; 8],
    /// 8-byte key-derivation salt for the owner password (`/O[40..48]`).
    pub owner_key_salt: [u8; 8],
    /// 4 spec-arbitrary bytes appended to the `/Perms` plaintext block
    /// (bytes 12..16, after the `'adb'` magic).
    pub perms_random_tail: [u8; 4],
}

/// Construct the `/Encrypt` dictionary for V=5 R=6 (AES-256, ISO 32000-2)
/// from passwords, permissions, and pre-generated secrets. Returns the
/// dictionary; the file encryption key is `secrets.file_key` (the caller
/// already owns it).
///
/// Computation order:
///
/// 1. `/U` + `/UE` via [`compute_u_ue_r6`] (Algorithm 8).
/// 2. `/O` + `/OE` via [`compute_o_oe_r6`] (Algorithm 9, depends on `/U`).
/// 3. `/Perms` via [`compute_perms_blob`] (Algorithm 10, depends on
///    `file_key`).
///
/// Emitted dictionary keys (qpdf-compatible): `/CF` `/Filter` `/Length`
/// `/O` `/OE` `/P` `/Perms` `/R` `/StmF` `/StrF` `/U` `/UE` `/V`
/// (and `/EncryptMetadata` only when false). `/CF/StdCF/CFM` is `AESV3`
/// per the V=5 R=6 spec.
///
/// # Errors
///
/// Returns [`crate::Error::Internal`] if the SHA-2 pipeline rejects a
/// request, mirroring the `std::logic_error` qpdf's `Pl_SHA2` raises
/// (`Pl_SHA2.cc:53,63`).
pub(crate) fn build_v5_r6_encrypt_dict(
    params: &V5R6EncryptParams<'_>,
    secrets: &V5R6Secrets,
) -> Result<ObjectHandle> {
    // Algorithm 8: /U + /UE.
    let (u_entry, ue_entry) = compute_u_ue_r6(
        params.user_password,
        &secrets.file_key,
        &secrets.user_validation_salt,
        &secrets.user_key_salt,
    )?; // cov:ignore: unreachable — Pl_SHA2 with a literal bit size and no downstream stage cannot fail, and qpdf's hash_V5 likewise never catches (`QPDF_encryption.cc:246,296`)

    // Algorithm 9: /O + /OE (uses /U as extra).
    let (o_entry, oe_entry) = compute_o_oe_r6(
        params.owner_password,
        &u_entry,
        &secrets.file_key,
        &secrets.owner_validation_salt,
        &secrets.owner_key_salt,
    )?; // cov:ignore: unreachable — Pl_SHA2 with a literal bit size and no downstream stage cannot fail, and qpdf's hash_V5 likewise never catches (`QPDF_encryption.cc:246,296`)

    // Algorithm 10: /Perms.
    let perms = compute_perms_blob(
        params.p,
        params.encrypt_metadata,
        &secrets.perms_random_tail,
        &secrets.file_key,
    )?; // cov:ignore: qpdf's fixed AES /Perms stage cannot fail for a fixed block

    // /CF /StdCF entry (CFM AESV3, Length 32).
    let std_cf = ObjectHandle::dictionary(vec![
        (
            b"AuthEvent".to_vec(),
            ObjectHandle::name(b"DocOpen".to_vec()),
        ),
        (b"CFM".to_vec(), ObjectHandle::name(b"AESV3".to_vec())),
        (b"Length".to_vec(), ObjectHandle::integer(32)),
    ]);
    let cf = ObjectHandle::dictionary(vec![(b"StdCF".to_vec(), std_cf)]);
    let mut entries = vec![
        (b"CF".to_vec(), cf),
        (b"Filter".to_vec(), ObjectHandle::name(b"Standard".to_vec())),
        (b"Length".to_vec(), ObjectHandle::integer(256)),
        (b"O".to_vec(), ObjectHandle::string(o_entry.to_vec())),
        (b"OE".to_vec(), ObjectHandle::string(oe_entry.to_vec())),
        (b"P".to_vec(), ObjectHandle::integer(i64::from(params.p))),
        (b"Perms".to_vec(), ObjectHandle::string(perms.to_vec())),
        (b"R".to_vec(), ObjectHandle::integer(6)),
        (b"StmF".to_vec(), ObjectHandle::name(b"StdCF".to_vec())),
        (b"StrF".to_vec(), ObjectHandle::name(b"StdCF".to_vec())),
        (b"U".to_vec(), ObjectHandle::string(u_entry.to_vec())),
        (b"UE".to_vec(), ObjectHandle::string(ue_entry.to_vec())),
        (b"V".to_vec(), ObjectHandle::integer(5)),
    ];
    if !params.encrypt_metadata {
        entries.push((b"EncryptMetadata".to_vec(), ObjectHandle::boolean(false)));
    }
    Ok(ObjectHandle::dictionary(entries))
}

/// Spec-random secret material consumed by [`build_v5_r5_encrypt_dict`].
///
/// Identical to [`V5R6Secrets`] — R=5 also emits `/Perms` (Algorithm 10)
/// because qpdf 11.x requires it for all V=5 documents, R=5 and R=6 alike.
pub(crate) type V5R5Secrets = V5R6Secrets;

/// Compute the V=5 R=5 `/U` and `/UE` entries using SHA-256 (not Algorithm 2.B).
///
/// Identical to [`compute_u_ue_r6`] except the hash function is
/// [`r5_salted_hash`] — the deprecated simpler SHA-256 path.
///
/// # Errors
///
/// Returns [`crate::Error::Internal`] if the SHA-2 pipeline rejects a
/// request, mirroring the `std::logic_error` qpdf's `Pl_SHA2` raises
/// (`Pl_SHA2.cc:53,63`).
pub(crate) fn compute_u_ue_r5(
    user_password: &[u8],
    file_key: &[u8; 32],
    validation_salt: &[u8; 8],
    key_salt: &[u8; 8],
) -> Result<([u8; 48], [u8; 32])> {
    let validation_hash = r5_salted_hash(user_password, validation_salt, &[])?;
    let aes_key = r5_salted_hash(user_password, key_salt, &[])?;
    let ue_entry = aes256_cbc_zero_iv_wrap(file_key, &aes_key)?;

    let mut u_entry = [0u8; 48];
    u_entry[0..32].copy_from_slice(&validation_hash);
    u_entry[32..40].copy_from_slice(validation_salt);
    u_entry[40..48].copy_from_slice(key_salt);
    Ok((u_entry, ue_entry))
}

/// Compute the V=5 R=5 `/O` and `/OE` entries using SHA-256 (not Algorithm 2.B).
///
/// Mirrors [`compute_u_ue_r5`] using `owner_password` and appending the 48-byte
/// `/U` entry as the extra hash input for the owner path.
///
/// # Errors
///
/// Returns [`crate::Error::Internal`] if the SHA-2 pipeline rejects a
/// request, mirroring the `std::logic_error` qpdf's `Pl_SHA2` raises
/// (`Pl_SHA2.cc:53,63`).
pub(crate) fn compute_o_oe_r5(
    owner_password: &[u8],
    user_entry: &[u8; 48],
    file_key: &[u8; 32],
    validation_salt: &[u8; 8],
    key_salt: &[u8; 8],
) -> Result<([u8; 48], [u8; 32])> {
    let validation_hash = r5_salted_hash(owner_password, validation_salt, user_entry)?;
    let aes_key = r5_salted_hash(owner_password, key_salt, user_entry)?;
    let oe_entry = aes256_cbc_zero_iv_wrap(file_key, &aes_key)?;

    let mut o_entry = [0u8; 48];
    o_entry[0..32].copy_from_slice(&validation_hash);
    o_entry[32..40].copy_from_slice(validation_salt);
    o_entry[40..48].copy_from_slice(key_salt);
    Ok((o_entry, oe_entry))
}

/// Construct the `/Encrypt` dictionary for V=5 R=5 (deprecated pre-ISO 32000-2
/// AES-256) from passwords, permissions, and pre-generated secrets.
///
/// Like [`build_v5_r6_encrypt_dict`] but:
/// - Uses R=5 SHA-256 password hashes (not Algorithm 2.B).
/// - Emits `/R 5` instead of `/R 6`.
/// - Still emits `/Perms` (Algorithm 10) — qpdf 11.x requires it for all V=5
///   documents regardless of revision.
///
/// # Errors
///
/// Returns [`crate::Error::Internal`] if the SHA-2 pipeline rejects a
/// request, mirroring the `std::logic_error` qpdf's `Pl_SHA2` raises
/// (`Pl_SHA2.cc:53,63`).
pub(crate) fn build_v5_r5_encrypt_dict(
    params: &V5R6EncryptParams<'_>,
    secrets: &V5R5Secrets,
) -> Result<ObjectHandle> {
    let (u_entry, ue_entry) = compute_u_ue_r5(
        params.user_password,
        &secrets.file_key,
        &secrets.user_validation_salt,
        &secrets.user_key_salt,
    )?; // cov:ignore: unreachable — Pl_SHA2 with a literal bit size and no downstream stage cannot fail, and qpdf's hash_V5 likewise never catches (`QPDF_encryption.cc:246`)

    let (o_entry, oe_entry) = compute_o_oe_r5(
        params.owner_password,
        &u_entry,
        &secrets.file_key,
        &secrets.owner_validation_salt,
        &secrets.owner_key_salt,
    )?; // cov:ignore: unreachable — Pl_SHA2 with a literal bit size and no downstream stage cannot fail, and qpdf's hash_V5 likewise never catches (`QPDF_encryption.cc:246`)

    let std_cf = ObjectHandle::dictionary(vec![
        (
            b"AuthEvent".to_vec(),
            ObjectHandle::name(b"DocOpen".to_vec()),
        ),
        (b"CFM".to_vec(), ObjectHandle::name(b"AESV3".to_vec())),
        (b"Length".to_vec(), ObjectHandle::integer(32)),
    ]);
    let cf = ObjectHandle::dictionary(vec![(b"StdCF".to_vec(), std_cf)]);

    // Algorithm 10: /Perms — required by qpdf 11.x for all V=5 documents.
    let perms = compute_perms_blob(
        params.p,
        params.encrypt_metadata,
        &secrets.perms_random_tail,
        &secrets.file_key,
    )?; // cov:ignore: qpdf's fixed AES /Perms stage cannot fail for a fixed block

    let mut entries = vec![
        (b"CF".to_vec(), cf),
        (b"Filter".to_vec(), ObjectHandle::name(b"Standard".to_vec())),
        (b"Length".to_vec(), ObjectHandle::integer(256)),
        (b"O".to_vec(), ObjectHandle::string(o_entry.to_vec())),
        (b"OE".to_vec(), ObjectHandle::string(oe_entry.to_vec())),
        (b"P".to_vec(), ObjectHandle::integer(i64::from(params.p))),
        (b"Perms".to_vec(), ObjectHandle::string(perms.to_vec())),
        (b"R".to_vec(), ObjectHandle::integer(5)),
        (b"StmF".to_vec(), ObjectHandle::name(b"StdCF".to_vec())),
        (b"StrF".to_vec(), ObjectHandle::name(b"StdCF".to_vec())),
        (b"U".to_vec(), ObjectHandle::string(u_entry.to_vec())),
        (b"UE".to_vec(), ObjectHandle::string(ue_entry.to_vec())),
        (b"V".to_vec(), ObjectHandle::integer(5)),
    ];
    if !params.encrypt_metadata {
        entries.push((b"EncryptMetadata".to_vec(), ObjectHandle::boolean(false)));
    }
    Ok(ObjectHandle::dictionary(entries))
}

// ────────────────────────────────────────────────────────────────────────────
// Algorithm 1 — Per-object key derivation (V=1/V=2/V=4)
// ────────────────────────────────────────────────────────────────────────────

/// Cipher material selected for decrypting string objects at a given use site.
///
/// A `/Identity` crypt filter has no representation here: qpdf returns from
/// `decryptString` before deriving a key or constructing a cipher
/// (`QPDF_encryption.cc:985-986`), and the flpdf caller mirrors that by
/// skipping [`decrypt_cipher_bytes`] entirely.
#[derive(Debug, Clone, Copy)]
pub(crate) enum StringCipher<'a> {
    /// RC4 with an already-derived object key (V<5) or selected CF key.
    Rc4 { key: &'a [u8] },
    /// AES with the raw qpdf object key. The crypto provider chooses AES-128,
    /// AES-192, or AES-256 from the key length. PDF string bytes include the IV.
    Aes { key: &'a [u8] },
}

pub(crate) fn decrypt_cipher_bytes(bytes: &mut Vec<u8>, cipher: StringCipher<'_>) -> Result<()> {
    match cipher {
        StringCipher::Rc4 { key } => {
            let mut cipher = Rc4::new(key)?;
            cipher.process_in_place(bytes);
            Ok(())
        }
        // qpdf has exactly one AES implementation, `Pl_AES_PDF`, and reaches it
        // for strings at `libqpdf/QPDF_encryption.cc:1014` and for streams at
        // `:1139`. Both hand it the whole stored payload and let the stage take
        // the leading block as the initialization vector, so the IV is not
        // split off here and a payload of one block or less simply yields no
        // plaintext. Keeping this on the stage rather than a one-shot cipher is
        // what preserves qpdf's tolerance for a short or unpadded tail.
        StringCipher::Aes { key } => {
            *bytes = PlAesPdf::decrypt_to_vec("AES string decryption", bytes, key)?;
            Ok(())
        }
    }
}

// ────────────────────────────────────────────────────────────────────────────
// Writer side — String / stream encryption passes
// (strings and stream payloads)
// ────────────────────────────────────────────────────────────────────────────

/// Cipher material for ENCRYPTING string objects and stream payloads.
///
/// Mirror of [`StringCipher`] but for the write direction. The AES variants
/// intentionally do NOT carry an IV — IVs MUST be unique per encryption call
/// because reusing an IV with the same AES-CBC key leaks information about
/// plaintext XORs (a well-known CBC weakness). Callers supply IVs via the
/// `iv_gen` closure supplied by the caller or the explicit `iv` parameter on
/// [`encrypt_cipher_bytes`].
///
/// For V<5, the per-object key from
/// [`super::primitives::compute_data_key`] is the key material.
/// For V=5, the file key itself or a selected `/CF` key is used directly.
///
/// Like [`StringCipher`], this carries no pass-through variant: the writer
/// emits the plain string before reaching cipher selection whenever no data
/// key is in force.
#[derive(Debug, Clone, Copy)]
pub(crate) enum StringEncryptCipher<'a> {
    /// RC4 (V=1, V=2, V=4 `/CFM /V2`) with an already-derived per-object key.
    /// IV is unused (RC4 is a stream cipher with no IV).
    Rc4 { key: &'a [u8] },
    /// AES-CBC with the raw qpdf key. The crypto provider selects the cipher
    /// from the key length. Output is `IV ‖ AES-CBC(plaintext, key, IV)` with
    /// PKCS#7 padding.
    Aes { key: &'a [u8] },
}

/// Encrypt a single byte buffer in place — the writer-side inverse of
/// [`decrypt_cipher_bytes`].
///
/// Behavior by cipher:
///
/// - `Rc4`: RC4-encrypts `bytes` in place; the buffer length is unchanged.
///   `iv` is ignored.
/// - `Aes`: PKCS#7-pads `bytes` to a 16-byte block boundary,
///   AES-CBC-encrypts under `key` with `iv`, then sets `bytes` to
///   `iv ‖ ciphertext`. The output is always at least 32 bytes (16-byte IV
///   + at least one 16-byte ciphertext block).
///
/// The caller is responsible for supplying a FRESH `iv` per AES call —
/// reusing an IV with the same key under AES-CBC is a known weakness. For
/// non-AES ciphers `iv` is unused, so passing a stale `iv` is harmless.
pub(crate) fn encrypt_cipher_bytes(
    bytes: &mut Vec<u8>,
    cipher: StringEncryptCipher<'_>,
    iv: &[u8; 16],
) -> Result<()> {
    match cipher {
        StringEncryptCipher::Rc4 { key } => {
            let mut cipher = Rc4::new(key)?;
            cipher.process_in_place(bytes);
            Ok(())
        }
        StringEncryptCipher::Aes { key } => {
            let encrypted =
                PlAesPdf::encrypt_to_vec_with_iv("AES string encryption", bytes, key, iv)?;
            bytes.clear();
            bytes.extend_from_slice(iv);
            bytes.extend_from_slice(&encrypted);
            Ok(())
        }
    }
}

// ────────────────────────────────────────────────────────────────────────────
// Writer side — explicit /Crypt filter chain entry
// ────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod v5_dictionary_tests {
    use super::{build_v5_r5_encrypt_dict, V5R5Secrets, V5R6EncryptParams};

    #[test]
    fn v5_r5_dictionary_emits_encrypt_metadata_false() {
        let secrets = V5R5Secrets {
            file_key: [1; 32],
            user_validation_salt: [2; 8],
            user_key_salt: [3; 8],
            owner_validation_salt: [4; 8],
            owner_key_salt: [5; 8],
            perms_random_tail: [6; 4],
        };
        let params = V5R6EncryptParams {
            user_password: b"user",
            owner_password: b"owner",
            p: -4,
            encrypt_metadata: false,
        };

        let dictionary = build_v5_r5_encrypt_dict(&params, &secrets).expect("valid V=5 R=5 data");
        assert_eq!(
            dictionary
                .try_get_key(b"/EncryptMetadata")
                .expect("dictionary lookup")
                .as_boolean(),
            Some(false)
        );
    }
}

#[cfg(test)]
mod v1_v2_reader_tests {
    use super::{check_user_password, StandardHandlerInputs};

    #[test]
    fn v1_r3_uses_qpdf_r3_key_derivation_with_a_40_bit_key() {
        let id0 = [
            0xdd, 0x22, 0x11, 0x51, 0x71, 0xe3, 0x2b, 0x2c, 0x97, 0x7f, 0x0d, 0x40, 0xd4, 0x5c,
            0x99, 0x72,
        ];
        let o = [
            0xd8, 0x03, 0xdb, 0xa0, 0x8a, 0xc8, 0xe1, 0x91, 0xd7, 0x89, 0x88, 0xa6, 0x74, 0xbd,
            0x14, 0xb8, 0x18, 0x01, 0xc4, 0xa2, 0xac, 0x82, 0xde, 0x11, 0x52, 0x5b, 0x69, 0xac,
            0x42, 0xf0, 0x45, 0x89,
        ];
        let u = [
            0x16, 0xa5, 0xf5, 0xd4, 0xa6, 0x3a, 0x2c, 0xd3, 0x26, 0x55, 0x24, 0xfa, 0x22, 0x48,
            0x46, 0x60, 0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41, 0x64, 0x00, 0x4e, 0x56,
            0xff, 0xfa, 0x01, 0x08,
        ];
        let inputs = StandardHandlerInputs {
            v: 1,
            r: 3,
            length_bits: 40,
            p: -12,
            id0: &id0,
            u: &u,
            o: &o,
            encrypt_metadata: true,
        };

        let file_key = check_user_password(b"623", &inputs)
            .expect("qpdf accepts Standard V=1/R=3 with a 40-bit key");

        assert_eq!(file_key, [0xe3, 0x90, 0xe2, 0x20, 0xda]);
    }

    #[test]
    fn v1_rejects_an_inconsistent_non_40_bit_internal_projection() {
        let id0 = [0xdd; 16];
        let o = [0xd8; 32];
        let u = [0x16; 32];
        let inputs = StandardHandlerInputs {
            v: 1,
            r: 3,
            length_bits: 128,
            p: -12,
            id0: &id0,
            u: &u,
            o: &o,
            encrypt_metadata: true,
        };

        let error = check_user_password(b"623", &inputs)
            .expect_err("V=1 must retain qpdf's fixed 40-bit effective length");

        assert!(matches!(
            error,
            crate::Error::Encrypted(crate::error::EncryptedError::UnsupportedHandler {
                v: 1,
                r: 3,
                ..
            })
        ));
    }
}

#[cfg(test)]
mod copy_writer_key_derivation_tests {
    use super::{
        compute_encryption_key_from_password, v_lt_5_32_byte_parameter, StandardHandlerInputs,
    };

    /// `/O` from a V=4 donor produced by
    /// `qpdf --static-id --encrypt --user-password=u --owner-password=o
    /// --bits=128 --use-aes=y`.
    const DONOR_O: [u8; 32] = [
        0x2a, 0x2f, 0x0a, 0x19, 0x90, 0x19, 0x2c, 0x60, 0x11, 0x47, 0x30, 0xbd, 0xcd, 0x39, 0xf3,
        0x78, 0x28, 0xa5, 0x3c, 0x89, 0xa3, 0x40, 0xdd, 0x47, 0x3c, 0x85, 0x29, 0x9d, 0xc5, 0x25,
        0x8e, 0x1c,
    ];
    /// qpdf's `--static-id` `/ID[0]`.
    const STATIC_ID0: [u8; 16] = [
        0x31, 0x41, 0x59, 0x26, 0x53, 0x58, 0x97, 0x93, 0x23, 0x84, 0x62, 0x64, 0x33, 0x83, 0x27,
        0x95,
    ];

    fn inputs(r: i64, length_bits: i64, encrypt_metadata: bool) -> StandardHandlerInputs<'static> {
        static U: [u8; 32] = [0; 32];
        StandardHandlerInputs {
            v: 4,
            r,
            length_bits,
            p: -4,
            id0: &STATIC_ID0,
            u: &U,
            o: &DONOR_O,
            encrypt_metadata,
        }
    }

    /// Known answer taken from qpdf 11.9.0, not from flpdf.
    ///
    /// Reproduce it by patching that donor's `/Length 128` to `/Length 040`
    /// in place (same width, so every xref offset stays valid) and running
    /// `qpdf --static-id --static-aes-iv --allow-weak-crypto --password=u
    /// <donor> out.pdf`. qpdf exits 0. Derive the 14-byte per-object AES key
    /// for the first content stream with `QPDF::compute_data_key` over the
    /// 5-byte key below, extend it to 16 bytes with two zero bytes (the
    /// bytes qpdf's crypto provider reads past the end of that buffer, see
    /// `copy_encryption_rejects_an_aes_key_qpdf_would_read_out_of_bounds`),
    /// and AES-128-CBC decrypt the stream with its leading 16 bytes as the
    /// IV: the plaintext inflates to the original content stream. Only this
    /// 5-byte key produces that result, so it is qpdf's own value.
    #[test]
    fn short_length_matches_the_qpdf_derived_key() {
        let key = compute_encryption_key_from_password(b"u", &inputs(4, 40, true))
            .expect("a positive /Length derives a key");
        assert_eq!(key, [0x46, 0x07, 0x82, 0xd6, 0x66]);
    }

    /// qpdf clamps the key length to the MD5 digest size, so any `/Length`
    /// above 128 bits derives exactly the 128-bit key.
    #[test]
    fn oversized_length_is_clamped_to_the_digest_size() {
        let clamped = compute_encryption_key_from_password(b"u", &inputs(3, 240, true))
            .expect("an oversized /Length is clamped");
        let digest_sized = compute_encryption_key_from_password(b"u", &inputs(3, 128, true))
            .expect("a 128-bit /Length derives a key");
        assert_eq!(clamped.len(), 16);
        assert_eq!(clamped, digest_sized);
    }

    /// qpdf's `getIntValueAsInt` fallback turns a non-integer `/Length` into
    /// zero, which derives a zero-length key rather than failing.
    #[test]
    fn zero_length_derives_an_empty_key() {
        let key = compute_encryption_key_from_password(b"u", &inputs(3, 0, true))
            .expect("a zero /Length derives an empty key");
        assert!(key.is_empty());
    }

    /// Below R=3 qpdf skips the 50 MD5 iterations entirely.
    #[test]
    fn revision_two_skips_the_iteration_loop() {
        let r2 = compute_encryption_key_from_password(b"u", &inputs(2, 40, true))
            .expect("R=2 derives a key");
        let r3 = compute_encryption_key_from_password(b"u", &inputs(3, 40, true))
            .expect("R=3 derives a key");
        assert_eq!(r2.len(), 5);
        assert_ne!(r2, r3);
    }

    /// From R=4 on, cleartext metadata appends 0xFF x4 to the digest input.
    #[test]
    fn cleartext_metadata_changes_the_key_from_revision_four() {
        let encrypted = compute_encryption_key_from_password(b"u", &inputs(4, 128, true))
            .expect("R=4 derives a key");
        let cleartext = compute_encryption_key_from_password(b"u", &inputs(4, 128, false))
            .expect("R=4 derives a key");
        assert_ne!(encrypted, cleartext);
        // R=3 has no such tail, so the flag cannot change its key.
        assert_eq!(
            compute_encryption_key_from_password(b"u", &inputs(3, 128, true))
                .expect("R=3 derives a key"),
            compute_encryption_key_from_password(b"u", &inputs(3, 128, false))
                .expect("R=3 derives a key")
        );
    }

    /// qpdf's `QIntC` conversions raise a range error for a negative length.
    #[test]
    fn negative_length_is_out_of_range() {
        let error = compute_encryption_key_from_password(b"u", &inputs(3, -8, true))
            .expect_err("a negative /Length has no key length");
        assert!(
            matches!(&error, crate::Error::System(message) if message.contains("-8")),
            "unexpected error: {error}"
        );
    }

    /// The 32-byte `/O` and `/U` projection truncates and NUL-pads.
    #[test]
    fn parameter_projection_truncates_and_pads() {
        assert_eq!(v_lt_5_32_byte_parameter(&[0xab; 40]), [0xab; 32]);
        let short = v_lt_5_32_byte_parameter(&[0xcd; 3]);
        assert_eq!(&short[..3], &[0xcd; 3]);
        assert_eq!(&short[3..], &[0; 29]);
    }
}