oxidize-pdf 2.5.1

A pure Rust PDF generation and manipulation library with zero external dependencies
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
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
//! Standard Security Handler implementation according to ISO 32000-1/32000-2
//!
//! # Security Considerations
//!
//! This implementation includes several security hardening measures:
//!
//! - **Constant-time comparison**: Password validation uses `subtle::ConstantTimeEq`
//!   to prevent timing side-channel attacks that could leak password information.
//!
//! - **Memory zeroization**: Sensitive data (`EncryptionKey`, `UserPassword`,
//!   `OwnerPassword`) implements `Zeroize` to ensure secrets are cleared from
//!   memory when dropped, preventing memory dump attacks.
//!
//! - **Cryptographically secure RNG**: Salt generation uses `rand::rng()` which
//!   provides OS-level entropy suitable for cryptographic operations.

#![allow(clippy::needless_range_loop)]

use crate::encryption::{generate_iv, Aes, AesKey, Permissions, Rc4, Rc4Key};
use crate::error::Result;
use crate::objects::ObjectId;
use rand::Rng;
use sha2::{Digest, Sha256, Sha384, Sha512};
use subtle::ConstantTimeEq;
use zeroize::{Zeroize, ZeroizeOnDrop};

/// Padding used in password processing
const 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,
];

/// User password
///
/// # Security
/// Implements `Zeroize` and `ZeroizeOnDrop` to ensure password is cleared from memory.
#[derive(Debug, Clone, Zeroize, ZeroizeOnDrop)]
pub struct UserPassword(pub String);

/// Owner password
///
/// # Security
/// Implements `Zeroize` and `ZeroizeOnDrop` to ensure password is cleared from memory.
#[derive(Debug, Clone, Zeroize, ZeroizeOnDrop)]
pub struct OwnerPassword(pub String);

/// Encryption key
///
/// # Security
/// Implements `Zeroize` and `ZeroizeOnDrop` to ensure key bytes are cleared from memory.
#[derive(Debug, Clone, Zeroize, ZeroizeOnDrop)]
pub struct EncryptionKey {
    /// Key bytes
    pub key: Vec<u8>,
}

impl EncryptionKey {
    /// Create from bytes
    pub fn new(key: Vec<u8>) -> Self {
        Self { key }
    }

    /// Get key length in bytes
    pub fn len(&self) -> usize {
        self.key.len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.key.is_empty()
    }

    /// Get key as bytes
    pub fn as_bytes(&self) -> &[u8] {
        &self.key
    }
}

/// Security handler revision
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub enum SecurityHandlerRevision {
    /// Revision 2 (RC4 40-bit)
    R2 = 2,
    /// Revision 3 (RC4 128-bit)
    R3 = 3,
    /// Revision 4 (RC4 128-bit with metadata encryption control)
    R4 = 4,
    /// Revision 5 (AES-256 with improved password validation)
    R5 = 5,
    /// Revision 6 (AES-256 with Unicode password support)
    R6 = 6,
}

/// Standard Security Handler
pub struct StandardSecurityHandler {
    /// Revision
    pub revision: SecurityHandlerRevision,
    /// Key length in bytes
    pub key_length: usize,
}

impl StandardSecurityHandler {
    /// Create handler for RC4 40-bit encryption
    pub fn rc4_40bit() -> Self {
        Self {
            revision: SecurityHandlerRevision::R2,
            key_length: 5,
        }
    }

    /// Create handler for RC4 128-bit encryption
    pub fn rc4_128bit() -> Self {
        Self {
            revision: SecurityHandlerRevision::R3,
            key_length: 16,
        }
    }

    /// Create handler for AES-128 encryption (Revision 4)
    pub fn aes_128_r4() -> Self {
        Self {
            revision: SecurityHandlerRevision::R4,
            key_length: 16,
        }
    }

    /// Create handler for AES-256 encryption (Revision 5)
    pub fn aes_256_r5() -> Self {
        Self {
            revision: SecurityHandlerRevision::R5,
            key_length: 32,
        }
    }

    /// Create handler for AES-256 encryption (Revision 6)
    pub fn aes_256_r6() -> Self {
        Self {
            revision: SecurityHandlerRevision::R6,
            key_length: 32,
        }
    }

    /// Pad or truncate password to 32 bytes
    fn pad_password(password: &str) -> [u8; 32] {
        let mut padded = [0u8; 32];
        let password_bytes = password.as_bytes();
        let len = password_bytes.len().min(32);

        // Copy password bytes
        padded[..len].copy_from_slice(&password_bytes[..len]);

        // Fill remaining with padding
        if len < 32 {
            padded[len..].copy_from_slice(&PADDING[..32 - len]);
        }

        padded
    }

    /// Compute owner password hash (O entry)
    pub fn compute_owner_hash(
        &self,
        owner_password: &OwnerPassword,
        user_password: &UserPassword,
    ) -> Vec<u8> {
        // Step 1: Pad passwords
        let owner_pad = Self::pad_password(&owner_password.0);
        let user_pad = Self::pad_password(&user_password.0);

        // Step 2: Create MD5 hash of owner password
        let mut hash = md5::compute(&owner_pad).to_vec();

        // Step 3: For revision 3+, do 50 additional iterations
        if self.revision >= SecurityHandlerRevision::R3 {
            for _ in 0..50 {
                hash = md5::compute(&hash).to_vec();
            }
        }

        // Step 4: Create RC4 key from hash (truncated to key length)
        let rc4_key = Rc4Key::from_slice(&hash[..self.key_length]);

        // Step 5: Encrypt user password with RC4
        let mut result = rc4_encrypt(&rc4_key, &user_pad);

        // Step 6: For revision 3+, do 19 additional iterations
        if self.revision >= SecurityHandlerRevision::R3 {
            for i in 1..=19 {
                let mut key_bytes = hash[..self.key_length].to_vec();
                for j in 0..self.key_length {
                    key_bytes[j] ^= i as u8;
                }
                let iter_key = Rc4Key::from_slice(&key_bytes);
                result = rc4_encrypt(&iter_key, &result);
            }
        }

        result
    }

    /// Compute user password hash (U entry)
    pub fn compute_user_hash(
        &self,
        user_password: &UserPassword,
        owner_hash: &[u8],
        permissions: Permissions,
        file_id: Option<&[u8]>,
    ) -> Result<Vec<u8>> {
        // Compute encryption key
        let key = self.compute_encryption_key(user_password, owner_hash, permissions, file_id)?;

        match self.revision {
            SecurityHandlerRevision::R2 => {
                // For R2, encrypt padding with key
                let rc4_key = Rc4Key::from_slice(&key.key);
                Ok(rc4_encrypt(&rc4_key, &PADDING))
            }
            SecurityHandlerRevision::R3 | SecurityHandlerRevision::R4 => {
                // For R3/R4, compute MD5 hash including file ID
                let mut data = Vec::new();
                data.extend_from_slice(&PADDING);

                if let Some(id) = file_id {
                    data.extend_from_slice(id);
                }

                let hash = md5::compute(&data);

                // Encrypt hash with RC4
                let rc4_key = Rc4Key::from_slice(&key.key);
                let mut result = rc4_encrypt(&rc4_key, hash.as_ref());

                // Do 19 additional iterations
                for i in 1..=19 {
                    let mut key_bytes = key.key.clone();
                    for j in 0..key_bytes.len() {
                        key_bytes[j] ^= i as u8;
                    }
                    let iter_key = Rc4Key::from_slice(&key_bytes);
                    result = rc4_encrypt(&iter_key, &result);
                }

                // Result is 32 bytes (16 bytes encrypted hash + 16 bytes arbitrary data)
                result.resize(32, 0);
                Ok(result)
            }
            SecurityHandlerRevision::R5 | SecurityHandlerRevision::R6 => {
                // For R5/R6, use AES-based hash computation
                let aes_key = self.compute_aes_encryption_key(
                    user_password,
                    owner_hash,
                    permissions,
                    file_id,
                )?;
                let hash = sha256(&aes_key.key);

                // For AES revisions, return the hash directly (simplified)
                Ok(hash)
            }
        }
    }

    /// Compute encryption key from user password
    pub fn compute_encryption_key(
        &self,
        user_password: &UserPassword,
        owner_hash: &[u8],
        permissions: Permissions,
        file_id: Option<&[u8]>,
    ) -> Result<EncryptionKey> {
        match self.revision {
            SecurityHandlerRevision::R5 | SecurityHandlerRevision::R6 => {
                // For AES revisions, use AES-specific key computation
                self.compute_aes_encryption_key(user_password, owner_hash, permissions, file_id)
            }
            _ => {
                // For RC4 revisions, use MD5-based key computation
                // Step 1: Pad password
                let padded = Self::pad_password(&user_password.0);

                // Step 2: Create hash input
                let mut data = Vec::new();
                data.extend_from_slice(&padded);
                data.extend_from_slice(owner_hash);
                data.extend_from_slice(&permissions.bits().to_le_bytes());

                if let Some(id) = file_id {
                    data.extend_from_slice(id);
                }

                #[cfg(debug_assertions)]
                {
                    eprintln!("[DEBUG compute_key] padded[0..8]: {:02x?}", &padded[..8]);
                    eprintln!("[DEBUG compute_key] owner_hash len: {}", owner_hash.len());
                    eprintln!(
                        "[DEBUG compute_key] P bytes: {:02x?}",
                        permissions.bits().to_le_bytes()
                    );
                    eprintln!("[DEBUG compute_key] data len before MD5: {}", data.len());
                    // Print full data for comparison
                    let data_hex: String = data.iter().map(|b| format!("{:02x}", b)).collect();
                    eprintln!("[DEBUG compute_key] full data hex: {}", data_hex);

                    // Verify specific expected hash for debugging
                    if data_hex == "7573657228bf4e5e4e758a4164004e56fffa01082e2e00b6d0683e802f0ca9fe94e8094419662a774442fb072e3d9f19e9d130ec09a4d0061e78fe920f7ab62ffcffffff9c5b2a0606f918182e6c5cc0cac374d6" {
                        eprintln!("[DEBUG compute_key] DATA MATCHES EXPECTED - should produce eee5568378306e35...");
                    }
                }

                // For R4 with metadata not encrypted, add extra bytes
                if self.revision == SecurityHandlerRevision::R4 {
                    // In a full implementation, check EncryptMetadata flag
                    // For now, assume metadata is encrypted
                }

                // Step 3: Create MD5 hash
                let mut hash = md5::compute(&data).to_vec();

                #[cfg(debug_assertions)]
                {
                    eprintln!(
                        "[DEBUG compute_key] initial hash[0..8]: {:02x?}",
                        &hash[..8]
                    );
                    let hash_hex: String = hash.iter().map(|b| format!("{:02x}", b)).collect();
                    eprintln!("[DEBUG compute_key] full hash: {}", hash_hex);
                    eprintln!("[DEBUG compute_key] key_length: {}", self.key_length);
                }

                // Step 4: For revision 3+, do 50 additional iterations
                if self.revision >= SecurityHandlerRevision::R3 {
                    for _ in 0..50 {
                        hash = md5::compute(&hash[..self.key_length]).to_vec();
                    }
                }

                // Step 5: Truncate to key length
                hash.truncate(self.key_length);

                #[cfg(debug_assertions)]
                {
                    eprintln!("[DEBUG compute_key] final key: {:02x?}", &hash);
                }

                Ok(EncryptionKey::new(hash))
            }
        }
    }

    /// Encrypt a string
    pub fn encrypt_string(&self, data: &[u8], key: &EncryptionKey, obj_id: &ObjectId) -> Vec<u8> {
        match self.revision {
            SecurityHandlerRevision::R4
            | SecurityHandlerRevision::R5
            | SecurityHandlerRevision::R6 => {
                // AES path for R4 (AES-128) and R5/R6 (AES-256)
                self.encrypt_aes(data, key, obj_id).unwrap_or_default()
            }
            _ => {
                // RC4 for R2/R3
                let obj_key = self.compute_object_key(key, obj_id);
                let rc4_key = Rc4Key::from_slice(&obj_key);
                rc4_encrypt(&rc4_key, data)
            }
        }
    }

    /// Decrypt a string
    pub fn decrypt_string(&self, data: &[u8], key: &EncryptionKey, obj_id: &ObjectId) -> Vec<u8> {
        match self.revision {
            SecurityHandlerRevision::R4
            | SecurityHandlerRevision::R5
            | SecurityHandlerRevision::R6 => {
                // AES path for R4 (AES-128) and R5/R6 (AES-256)
                self.decrypt_aes(data, key, obj_id).unwrap_or_default()
            }
            _ => {
                // RC4 is symmetric
                self.encrypt_string(data, key, obj_id)
            }
        }
    }

    /// Encrypt a stream
    pub fn encrypt_stream(&self, data: &[u8], key: &EncryptionKey, obj_id: &ObjectId) -> Vec<u8> {
        self.encrypt_string(data, key, obj_id)
    }

    /// Decrypt a stream
    pub fn decrypt_stream(&self, data: &[u8], key: &EncryptionKey, obj_id: &ObjectId) -> Vec<u8> {
        match self.revision {
            SecurityHandlerRevision::R4
            | SecurityHandlerRevision::R5
            | SecurityHandlerRevision::R6 => {
                // AES path for R4 (AES-128) and R5/R6 (AES-256)
                self.decrypt_aes(data, key, obj_id).unwrap_or_default()
            }
            _ => {
                // RC4 is symmetric
                self.decrypt_string(data, key, obj_id)
            }
        }
    }

    /// Encrypt data using AES.
    ///
    /// - **R4**: AES-128-CBC with MD5-based per-object key (ISO 32000-1 §7.6.2 Algorithm 1 + "sAlT")
    /// - **R5/R6**: AES-256-CBC with SHA-256 key derivation
    pub fn encrypt_aes(
        &self,
        data: &[u8],
        key: &EncryptionKey,
        obj_id: &ObjectId,
    ) -> Result<Vec<u8>> {
        let aes = match self.revision {
            SecurityHandlerRevision::R4 => {
                let obj_key = self.compute_r4_aes_object_key(key, obj_id);
                Aes::new(AesKey::new_128(obj_key)?)
            }
            SecurityHandlerRevision::R5 | SecurityHandlerRevision::R6 => {
                let obj_key = self.compute_aes_object_key(key, obj_id)?;
                Aes::new(AesKey::new_256(obj_key)?)
            }
            _ => {
                return Err(crate::error::PdfError::EncryptionError(
                    "AES encryption requires Rev 4+ (use RC4 for Rev 2/3)".to_string(),
                ));
            }
        };

        let iv = generate_iv();
        let mut result = Vec::with_capacity(16 + data.len() + 16);
        result.extend_from_slice(&iv);

        let encrypted = aes.encrypt_cbc(data, &iv).map_err(|e| {
            crate::error::PdfError::EncryptionError(format!("AES encryption failed: {e}"))
        })?;

        result.extend_from_slice(&encrypted);
        Ok(result)
    }

    /// Decrypt data using AES.
    ///
    /// - **R4**: AES-128-CBC with MD5-based per-object key
    /// - **R5/R6**: AES-256-CBC with SHA-256 key derivation
    pub fn decrypt_aes(
        &self,
        data: &[u8],
        key: &EncryptionKey,
        obj_id: &ObjectId,
    ) -> Result<Vec<u8>> {
        if data.len() < 16 {
            return Err(crate::error::PdfError::EncryptionError(
                "AES encrypted data must be at least 16 bytes (IV)".to_string(),
            ));
        }

        let iv = &data[0..16];
        let encrypted_data = &data[16..];

        let aes = match self.revision {
            SecurityHandlerRevision::R4 => {
                let obj_key = self.compute_r4_aes_object_key(key, obj_id);
                Aes::new(AesKey::new_128(obj_key)?)
            }
            SecurityHandlerRevision::R5 | SecurityHandlerRevision::R6 => {
                let obj_key = self.compute_aes_object_key(key, obj_id)?;
                Aes::new(AesKey::new_256(obj_key)?)
            }
            _ => {
                return Err(crate::error::PdfError::EncryptionError(
                    "AES decryption requires Rev 4+ (use RC4 for Rev 2/3)".to_string(),
                ));
            }
        };

        aes.decrypt_cbc(encrypted_data, iv).map_err(|e| {
            crate::error::PdfError::EncryptionError(format!("AES decryption failed: {e}"))
        })
    }

    /// Compute AES-128 per-object key for R4 (ISO 32000-1 §7.6.2 Algorithm 1 with "sAlT").
    ///
    /// key = MD5(file_key || obj_num[0..3] || gen_num[0..2] || "sAlT")[0..min(key_len+5, 16)]
    /// For AES-128 (key_len=16), min(16+5, 16) = 16, so always 16 bytes.
    fn compute_r4_aes_object_key(&self, key: &EncryptionKey, obj_id: &ObjectId) -> Vec<u8> {
        let mut data = Vec::new();
        data.extend_from_slice(&key.key);
        data.extend_from_slice(&obj_id.number().to_le_bytes()[..3]);
        data.extend_from_slice(&obj_id.generation().to_le_bytes()[..2]);
        data.extend_from_slice(b"sAlT");

        let hash = md5::compute(&data);
        let key_len = (key.len() + 5).min(16);
        hash[..key_len].to_vec()
    }

    /// Compute AES-256 object-specific encryption key for Rev 5/6 (SHA-256 based).
    fn compute_aes_object_key(&self, key: &EncryptionKey, obj_id: &ObjectId) -> Result<Vec<u8>> {
        if self.revision < SecurityHandlerRevision::R5 {
            return Err(crate::error::PdfError::EncryptionError(
                "SHA-256 AES key derivation only for Rev 5+".to_string(),
            ));
        }

        let mut data = Vec::new();
        data.extend_from_slice(&key.key);
        data.extend_from_slice(&obj_id.number().to_le_bytes());
        data.extend_from_slice(&obj_id.generation().to_le_bytes());
        data.extend_from_slice(b"sAlT");

        Ok(sha256(&data))
    }

    /// Compute encryption key for AES Rev 5/6
    pub fn compute_aes_encryption_key(
        &self,
        user_password: &UserPassword,
        owner_hash: &[u8],
        permissions: Permissions,
        file_id: Option<&[u8]>,
    ) -> Result<EncryptionKey> {
        if self.revision < SecurityHandlerRevision::R5 {
            return Err(crate::error::PdfError::EncryptionError(
                "AES key computation only for Rev 5+".to_string(),
            ));
        }

        // For Rev 5/6, use more secure key derivation
        let mut data = Vec::new();

        // Use UTF-8 encoding for passwords in Rev 5/6
        let password_bytes = user_password.0.as_bytes();
        data.extend_from_slice(password_bytes);

        // Add validation data
        data.extend_from_slice(owner_hash);
        data.extend_from_slice(&permissions.bits().to_le_bytes());

        if let Some(id) = file_id {
            data.extend_from_slice(id);
        }

        // Use SHA-256 for stronger hashing
        let mut hash = sha256(&data);

        // Perform additional iterations for Rev 5/6 (simplified)
        for _ in 0..100 {
            hash = sha256(&hash);
        }

        // AES-256 requires 32 bytes
        hash.truncate(32);

        Ok(EncryptionKey::new(hash))
    }

    /// Validate user password for AES Rev 5/6
    pub fn validate_aes_user_password(
        &self,
        password: &UserPassword,
        user_hash: &[u8],
        permissions: Permissions,
        file_id: Option<&[u8]>,
    ) -> Result<bool> {
        if self.revision < SecurityHandlerRevision::R5 {
            return Err(crate::error::PdfError::EncryptionError(
                "AES password validation only for Rev 5+".to_string(),
            ));
        }

        let computed_key =
            self.compute_aes_encryption_key(password, user_hash, permissions, file_id)?;

        // Compare first 32 bytes of computed hash with stored hash
        let computed_hash = sha256(&computed_key.key);

        Ok(user_hash.len() >= 32 && computed_hash[..32] == user_hash[..32])
    }

    // ========================================================================
    // R5/R6 Password Validation (ISO 32000-1 §7.6.4.3.4)
    // ========================================================================

    /// Compute R5 user password hash (U entry) - Algorithm 8
    ///
    /// Returns 48 bytes: hash(32) + validation_salt(8) + key_salt(8)
    ///
    /// # Algorithm
    /// 1. Generate random validation_salt (8 bytes)
    /// 2. Generate random key_salt (8 bytes)
    /// 3. Compute hash: SHA-256(password + validation_salt)
    /// 4. Apply 64 iterations of SHA-256
    /// 5. Return hash[0..32] + validation_salt + key_salt
    pub fn compute_r5_user_hash(&self, user_password: &UserPassword) -> Result<Vec<u8>> {
        if self.revision != SecurityHandlerRevision::R5 {
            return Err(crate::error::PdfError::EncryptionError(
                "R5 user hash only for Revision 5".to_string(),
            ));
        }

        // Generate cryptographically secure random salts
        let validation_salt = generate_salt(R5_SALT_LENGTH);
        let key_salt = generate_salt(R5_SALT_LENGTH);

        // Compute hash: SHA-256(password + validation_salt)
        let mut data = Vec::new();
        data.extend_from_slice(user_password.0.as_bytes());
        data.extend_from_slice(&validation_salt);

        let mut hash = sha256(&data);

        // Apply R5 iterations of SHA-256 (PDF spec §7.6.4.3.4)
        for _ in 0..R5_HASH_ITERATIONS {
            hash = sha256(&hash);
        }

        // Construct U entry: hash[0..32] + validation_salt + key_salt
        let mut u_entry = Vec::with_capacity(48);
        u_entry.extend_from_slice(&hash[..32]);
        u_entry.extend_from_slice(&validation_salt);
        u_entry.extend_from_slice(&key_salt);

        debug_assert_eq!(u_entry.len(), 48);
        Ok(u_entry)
    }

    /// Validate R5 user password - Algorithm 11
    ///
    /// Returns Ok(true) if password is correct, Ok(false) if incorrect.
    ///
    /// # Algorithm
    /// 1. Extract validation_salt from U[32..40]
    /// 2. Compute hash: SHA-256(password + validation_salt)
    /// 3. Apply 64 iterations of SHA-256
    /// 4. Compare result with U[0..32] using constant-time comparison
    ///
    /// # Security
    /// Uses constant-time comparison (`subtle::ConstantTimeEq`) to prevent
    /// timing side-channel attacks that could leak password information.
    pub fn validate_r5_user_password(
        &self,
        password: &UserPassword,
        u_entry: &[u8],
    ) -> Result<bool> {
        if u_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "R5 U entry must be {} bytes, got {}",
                U_ENTRY_LENGTH,
                u_entry.len()
            )));
        }

        // Extract validation_salt from U
        let validation_salt = &u_entry[U_VALIDATION_SALT_START..U_VALIDATION_SALT_END];

        // Compute hash: SHA-256(password + validation_salt)
        let mut data = Vec::new();
        data.extend_from_slice(password.0.as_bytes());
        data.extend_from_slice(validation_salt);

        let mut hash = sha256(&data);

        // Apply same R5 iterations as compute
        for _ in 0..R5_HASH_ITERATIONS {
            hash = sha256(&hash);
        }

        // SECURITY: Constant-time comparison prevents timing attacks
        let stored_hash = &u_entry[..U_HASH_LENGTH];
        let computed_hash = &hash[..U_HASH_LENGTH];
        Ok(bool::from(computed_hash.ct_eq(stored_hash)))
    }

    /// Compute R5 UE entry (encrypted encryption key)
    ///
    /// The UE entry stores the encryption key encrypted with a key derived
    /// from the user password.
    ///
    /// # Algorithm
    /// 1. Extract key_salt from U[40..48]
    /// 2. Compute intermediate key: SHA-256(password + key_salt)
    /// 3. Encrypt encryption_key with intermediate_key using AES-256-CBC (zero IV)
    pub fn compute_r5_ue_entry(
        &self,
        user_password: &UserPassword,
        u_entry: &[u8],
        encryption_key: &EncryptionKey,
    ) -> Result<Vec<u8>> {
        if u_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "U entry must be {} bytes",
                U_ENTRY_LENGTH
            )));
        }
        if encryption_key.len() != UE_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "Encryption key must be {} bytes for R5",
                UE_ENTRY_LENGTH
            )));
        }

        // Extract key_salt from U
        let key_salt = &u_entry[U_KEY_SALT_START..U_KEY_SALT_END];

        // Compute intermediate key: SHA-256(password + key_salt)
        let mut data = Vec::new();
        data.extend_from_slice(user_password.0.as_bytes());
        data.extend_from_slice(key_salt);

        let intermediate_key = sha256(&data);

        // Encrypt encryption_key with intermediate_key using AES-256-CBC
        // Zero IV as per PDF spec, no padding since 32 bytes is block-aligned
        let aes_key = AesKey::new_256(intermediate_key)?;
        let aes = Aes::new(aes_key);
        let iv = [0u8; 16];

        let encrypted = aes
            .encrypt_cbc_raw(encryption_key.as_bytes(), &iv)
            .map_err(|e| {
                crate::error::PdfError::EncryptionError(format!("UE encryption failed: {}", e))
            })?;

        // UE is exactly 32 bytes (no padding, 32 bytes = 2 AES blocks)
        Ok(encrypted)
    }

    /// Recover encryption key from R5 UE entry
    ///
    /// # Algorithm
    /// 1. Extract key_salt from U[40..48]
    /// 2. Compute intermediate key: SHA-256(password + key_salt)
    /// 3. Decrypt UE with intermediate_key using AES-256-CBC (zero IV)
    pub fn recover_r5_encryption_key(
        &self,
        user_password: &UserPassword,
        u_entry: &[u8],
        ue_entry: &[u8],
    ) -> Result<EncryptionKey> {
        if ue_entry.len() != UE_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "UE entry must be {} bytes, got {}",
                UE_ENTRY_LENGTH,
                ue_entry.len()
            )));
        }
        if u_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "U entry must be {} bytes",
                U_ENTRY_LENGTH
            )));
        }

        // Extract key_salt from U
        let key_salt = &u_entry[U_KEY_SALT_START..U_KEY_SALT_END];

        // Compute intermediate key: SHA-256(password + key_salt)
        let mut data = Vec::new();
        data.extend_from_slice(user_password.0.as_bytes());
        data.extend_from_slice(key_salt);

        let intermediate_key = sha256(&data);

        // Decrypt UE to get encryption key
        // UE is 32 bytes = 2 AES blocks, encrypted with CBC and zero IV
        let aes_key = AesKey::new_256(intermediate_key)?;
        let aes = Aes::new(aes_key);
        let iv = [0u8; 16];

        let decrypted = aes.decrypt_cbc_raw(ue_entry, &iv).map_err(|e| {
            crate::error::PdfError::EncryptionError(format!("UE decryption failed: {}", e))
        })?;

        Ok(EncryptionKey::new(decrypted))
    }

    // ========================================================================
    // R6 Password Validation (ISO 32000-2 §7.6.4.4)
    // ========================================================================

    /// Compute R6 user password hash (U entry) using SHA-512
    ///
    /// R6 uses SHA-512 (first 32 bytes) instead of SHA-256 for stronger security.
    /// Returns 48 bytes: hash(32) + validation_salt(8) + key_salt(8)
    ///
    /// # Algorithm (ISO 32000-2)
    /// 1. Generate random validation_salt (8 bytes)
    /// 2. Generate random key_salt (8 bytes)
    /// 3. Compute hash using Algorithm 2.B (ISO 32000-2:2020 §7.6.4.3.4)
    /// 4. Return hash[0..32] + validation_salt + key_salt
    pub fn compute_r6_user_hash(&self, user_password: &UserPassword) -> Result<Vec<u8>> {
        if self.revision != SecurityHandlerRevision::R6 {
            return Err(crate::error::PdfError::EncryptionError(
                "R6 user hash only for Revision 6".to_string(),
            ));
        }

        // Generate cryptographically secure random salts
        let validation_salt = generate_salt(R6_SALT_LENGTH);
        let key_salt = generate_salt(R6_SALT_LENGTH);

        // Compute hash using Algorithm 2.B (ISO 32000-2:2020)
        // For user password creation, u_entry is empty
        let hash = compute_hash_r6_algorithm_2b(
            user_password.0.as_bytes(),
            &validation_salt,
            &[], // No U entry for user password creation
        )?;

        // Construct U entry: hash[0..32] + validation_salt + key_salt
        let mut u_entry = Vec::with_capacity(48);
        u_entry.extend_from_slice(&hash[..32]);
        u_entry.extend_from_slice(&validation_salt);
        u_entry.extend_from_slice(&key_salt);

        debug_assert_eq!(u_entry.len(), 48);
        Ok(u_entry)
    }

    /// Validate R6 user password using Algorithm 2.B (ISO 32000-2:2020 §7.6.4.3.4)
    ///
    /// Returns Ok(true) if password is correct, Ok(false) if incorrect.
    ///
    /// # Algorithm
    /// 1. Extract validation_salt from U[32..40]
    /// 2. Compute hash using Algorithm 2.B with the validation_salt
    /// 3. Compare result with U[0..32] using constant-time comparison
    ///
    /// # Security
    /// Uses constant-time comparison (`subtle::ConstantTimeEq`) to prevent
    /// timing side-channel attacks that could leak password information.
    pub fn validate_r6_user_password(
        &self,
        password: &UserPassword,
        u_entry: &[u8],
    ) -> Result<bool> {
        if u_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "R6 U entry must be {} bytes, got {}",
                U_ENTRY_LENGTH,
                u_entry.len()
            )));
        }

        // Extract validation_salt from U[32..40]
        let validation_salt = &u_entry[U_VALIDATION_SALT_START..U_VALIDATION_SALT_END];

        // Compute hash using Algorithm 2.B (ISO 32000-2:2020)
        // For user password validation, u_entry is empty per spec
        let hash = compute_hash_r6_algorithm_2b(password.0.as_bytes(), validation_salt, &[])?;

        // SECURITY: Constant-time comparison prevents timing attacks
        let stored_hash = &u_entry[..U_HASH_LENGTH];
        let computed_hash = &hash[..U_HASH_LENGTH];
        Ok(bool::from(computed_hash.ct_eq(stored_hash)))
    }

    /// Compute R6 UE entry (encrypted encryption key) using Algorithm 2.B (ISO 32000-2:2020 §7.6.4.3.4)
    ///
    /// # Algorithm
    /// 1. Extract key_salt from U[40..48]
    /// 2. Compute intermediate key using Algorithm 2.B(password, key_salt, u_entry)
    /// 3. Encrypt encryption_key using AES-256-CBC with intermediate_key and IV = 0
    pub fn compute_r6_ue_entry(
        &self,
        user_password: &UserPassword,
        u_entry: &[u8],
        encryption_key: &EncryptionKey,
    ) -> Result<Vec<u8>> {
        if u_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "U entry must be {} bytes",
                U_ENTRY_LENGTH
            )));
        }
        if encryption_key.len() != UE_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "Encryption key must be {} bytes for R6",
                UE_ENTRY_LENGTH
            )));
        }

        // Extract key_salt from U[40..48]
        let key_salt = &u_entry[U_KEY_SALT_START..U_KEY_SALT_END];

        // Compute intermediate key using Algorithm 2.B (ISO 32000-2:2020)
        // For key derivation, we pass the full U entry as the third parameter
        let hash = compute_hash_r6_algorithm_2b(user_password.0.as_bytes(), key_salt, u_entry)?;
        let intermediate_key = hash[..U_HASH_LENGTH].to_vec();

        // Encrypt encryption_key with intermediate_key using AES-256-CBC, IV = 0
        let aes_key = AesKey::new_256(intermediate_key)?;
        let aes = Aes::new(aes_key);
        let iv = [0u8; 16];

        let encrypted = aes
            .encrypt_cbc_raw(encryption_key.as_bytes(), &iv)
            .map_err(|e| {
                crate::error::PdfError::EncryptionError(format!("UE encryption failed: {}", e))
            })?;

        Ok(encrypted)
    }

    /// Recover encryption key from R6 UE entry using Algorithm 2.B (ISO 32000-2:2020 §7.6.4.3.4)
    ///
    /// # Algorithm
    /// 1. Extract key_salt from U[40..48]
    /// 2. Compute intermediate key using Algorithm 2.B(password, key_salt, u_entry)
    /// 3. Decrypt UE using AES-256-CBC with intermediate_key and IV = 0
    pub fn recover_r6_encryption_key(
        &self,
        user_password: &UserPassword,
        u_entry: &[u8],
        ue_entry: &[u8],
    ) -> Result<EncryptionKey> {
        if ue_entry.len() != UE_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "UE entry must be {} bytes, got {}",
                UE_ENTRY_LENGTH,
                ue_entry.len()
            )));
        }
        if u_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "U entry must be {} bytes",
                U_ENTRY_LENGTH
            )));
        }

        // Extract key_salt from U[40..48]
        let key_salt = &u_entry[U_KEY_SALT_START..U_KEY_SALT_END];

        // Compute intermediate key using Algorithm 2.B (ISO 32000-2:2020)
        // For key derivation, we pass the full U entry as the third parameter
        let hash = compute_hash_r6_algorithm_2b(user_password.0.as_bytes(), key_salt, u_entry)?;
        let intermediate_key = hash[..U_HASH_LENGTH].to_vec();

        // Decrypt UE to get encryption key using AES-256-CBC with IV = 0
        let aes_key = AesKey::new_256(intermediate_key)?;
        let aes = Aes::new(aes_key);
        let iv = [0u8; 16];

        let decrypted = aes.decrypt_cbc_raw(ue_entry, &iv).map_err(|e| {
            crate::error::PdfError::EncryptionError(format!("UE decryption failed: {}", e))
        })?;

        Ok(EncryptionKey::new(decrypted))
    }

    // ========================================================================
    // R6 Perms Entry (ISO 32000-2 Table 25)
    // ========================================================================

    /// Compute R6 Perms entry (encrypted permissions)
    ///
    /// The Perms entry is a 16-byte value that encrypts permissions using AES-256-ECB.
    /// This allows verification that permissions haven't been tampered with.
    ///
    /// # Plaintext Structure (16 bytes)
    /// - Bytes 0-3: Permissions (P value, little-endian)
    /// - Bytes 4-7: 0xFFFFFFFF (fixed marker)
    /// - Bytes 8-10: "adb" (literal verification string)
    /// - Byte 11: 'T' or 'F' (EncryptMetadata flag)
    /// - Bytes 12-15: 0x00 (padding)
    pub fn compute_r6_perms_entry(
        &self,
        permissions: Permissions,
        encryption_key: &EncryptionKey,
        encrypt_metadata: bool,
    ) -> Result<Vec<u8>> {
        if self.revision != SecurityHandlerRevision::R6 {
            return Err(crate::error::PdfError::EncryptionError(
                "Perms entry only for Revision 6".to_string(),
            ));
        }
        if encryption_key.len() != UE_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "Encryption key must be {} bytes for R6 Perms",
                UE_ENTRY_LENGTH
            )));
        }

        // Construct plaintext: P + 0xFFFFFFFF + "adb" + T/F + padding
        let mut plaintext = vec![0u8; PERMS_ENTRY_LENGTH];

        // Permissions (4 bytes, little-endian)
        let p_bytes = (permissions.bits() as u32).to_le_bytes();
        plaintext[PERMS_P_START..PERMS_P_END].copy_from_slice(&p_bytes);

        // Fixed marker bytes (0xFFFFFFFF)
        plaintext[PERMS_MARKER_START..PERMS_MARKER_END].copy_from_slice(&PERMS_MARKER);

        // Literal "adb" verification string
        plaintext[PERMS_LITERAL_START..PERMS_LITERAL_END].copy_from_slice(PERMS_LITERAL);

        // EncryptMetadata flag
        plaintext[PERMS_ENCRYPT_META_BYTE] = if encrypt_metadata { b'T' } else { b'F' };

        // Bytes 12-15 remain 0x00 (padding)

        // Encrypt with AES-256-ECB
        let aes_key = AesKey::new_256(encryption_key.key.clone())?;
        let aes = Aes::new(aes_key);

        let encrypted = aes.encrypt_ecb(&plaintext).map_err(|e| {
            crate::error::PdfError::EncryptionError(format!("Perms encryption failed: {}", e))
        })?;

        Ok(encrypted)
    }

    /// Validate R6 Perms entry by decrypting and checking structure
    ///
    /// Returns Ok(true) if the Perms entry is valid and matches expected permissions.
    /// Returns Ok(false) if decryption succeeds but structure/permissions don't match.
    /// Returns Err if decryption fails.
    ///
    /// # Security
    /// Uses constant-time comparison (`subtle::ConstantTimeEq`) for permissions
    /// comparison to prevent timing side-channel attacks.
    pub fn validate_r6_perms(
        &self,
        perms_entry: &[u8],
        encryption_key: &EncryptionKey,
        expected_permissions: Permissions,
    ) -> Result<bool> {
        if perms_entry.len() != PERMS_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "Perms entry must be {} bytes, got {}",
                PERMS_ENTRY_LENGTH,
                perms_entry.len()
            )));
        }
        if encryption_key.len() != UE_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "Encryption key must be {} bytes",
                UE_ENTRY_LENGTH
            )));
        }

        // Decrypt with AES-256-ECB
        let aes_key = AesKey::new_256(encryption_key.key.clone())?;
        let aes = Aes::new(aes_key);

        let decrypted = aes.decrypt_ecb(perms_entry).map_err(|e| {
            crate::error::PdfError::EncryptionError(format!("Perms decryption failed: {}", e))
        })?;

        // Verify fixed marker
        if decrypted[PERMS_MARKER_START..PERMS_MARKER_END] != PERMS_MARKER {
            return Ok(false);
        }

        // Verify literal "adb"
        if &decrypted[PERMS_LITERAL_START..PERMS_LITERAL_END] != PERMS_LITERAL {
            return Ok(false);
        }

        // SECURITY: Constant-time comparison for permissions
        let expected_bytes = (expected_permissions.bits() as u32).to_le_bytes();
        let actual_bytes = &decrypted[PERMS_P_START..PERMS_P_END];
        Ok(bool::from(expected_bytes.ct_eq(actual_bytes)))
    }

    /// Extract EncryptMetadata flag from decrypted Perms entry
    ///
    /// Returns Ok(Some(true)) if EncryptMetadata='T', Ok(Some(false)) if 'F',
    /// Ok(None) if Perms structure is invalid.
    pub fn extract_r6_encrypt_metadata(
        &self,
        perms_entry: &[u8],
        encryption_key: &EncryptionKey,
    ) -> Result<Option<bool>> {
        if perms_entry.len() != PERMS_ENTRY_LENGTH || encryption_key.len() != UE_ENTRY_LENGTH {
            return Ok(None);
        }

        let aes_key = AesKey::new_256(encryption_key.key.clone())?;
        let aes = Aes::new(aes_key);

        let decrypted = match aes.decrypt_ecb(perms_entry) {
            Ok(d) => d,
            Err(_) => return Ok(None),
        };

        // Verify structure before extracting flag
        if decrypted[PERMS_MARKER_START..PERMS_MARKER_END] != PERMS_MARKER
            || &decrypted[PERMS_LITERAL_START..PERMS_LITERAL_END] != PERMS_LITERAL
        {
            return Ok(None);
        }

        // Extract EncryptMetadata flag
        match decrypted[PERMS_ENCRYPT_META_BYTE] {
            b'T' => Ok(Some(true)),
            b'F' => Ok(Some(false)),
            _ => Ok(None), // Invalid flag value
        }
    }

    // ========================================================================
    // R5/R6 Owner Password Support (ISO 32000-1 §7.6.4.3.3)
    // ========================================================================

    /// Compute R5 owner password hash (O entry)
    ///
    /// Algorithm 9 (ISO 32000-1): Creates 48-byte O entry
    /// - Bytes 0-31: SHA-256(owner_password || validation_salt)
    /// - Bytes 32-39: validation_salt (8 random bytes)
    /// - Bytes 40-47: key_salt (8 random bytes)
    pub fn compute_r5_owner_hash(
        &self,
        owner_password: &OwnerPassword,
        _user_password: &UserPassword,
    ) -> Result<Vec<u8>> {
        if self.revision != SecurityHandlerRevision::R5 {
            return Err(crate::error::PdfError::EncryptionError(
                "R5 owner hash only for Revision 5".to_string(),
            ));
        }

        // Generate random salts
        let validation_salt = generate_salt(R5_SALT_LENGTH);
        let key_salt = generate_salt(R5_SALT_LENGTH);

        // Compute hash: SHA-256(owner_password || validation_salt)
        let mut data = Vec::new();
        data.extend_from_slice(owner_password.0.as_bytes());
        data.extend_from_slice(&validation_salt);

        let hash = sha256(&data);

        // Construct O entry: hash[0..32] + validation_salt + key_salt
        let mut o_entry = Vec::with_capacity(U_ENTRY_LENGTH);
        o_entry.extend_from_slice(&hash[..U_HASH_LENGTH]);
        o_entry.extend_from_slice(&validation_salt);
        o_entry.extend_from_slice(&key_salt);

        debug_assert_eq!(o_entry.len(), U_ENTRY_LENGTH);
        Ok(o_entry)
    }

    /// Validate R5 owner password
    ///
    /// Algorithm 12 (ISO 32000-1): Validates owner password against O entry
    pub fn validate_r5_owner_password(
        &self,
        owner_password: &OwnerPassword,
        o_entry: &[u8],
    ) -> Result<bool> {
        if o_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "R5 O entry must be {} bytes, got {}",
                U_ENTRY_LENGTH,
                o_entry.len()
            )));
        }

        // Extract validation_salt from O (bytes 32-39)
        let validation_salt = &o_entry[U_VALIDATION_SALT_START..U_VALIDATION_SALT_END];

        // Compute hash: SHA-256(owner_password || validation_salt)
        let mut data = Vec::new();
        data.extend_from_slice(owner_password.0.as_bytes());
        data.extend_from_slice(validation_salt);

        let hash = sha256(&data);

        // SECURITY: Constant-time comparison prevents timing attacks
        let stored_hash = &o_entry[..U_HASH_LENGTH];
        Ok(bool::from(hash[..U_HASH_LENGTH].ct_eq(stored_hash)))
    }

    /// Compute R5 OE entry (encrypted encryption key with owner password)
    ///
    /// OE = AES-256-CBC(encryption_key, key=intermediate_key, iv=zeros)
    /// where intermediate_key = SHA-256(owner_password || key_salt)
    pub fn compute_r5_oe_entry(
        &self,
        owner_password: &OwnerPassword,
        o_entry: &[u8],
        encryption_key: &[u8],
    ) -> Result<Vec<u8>> {
        if o_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "O entry must be {} bytes",
                U_ENTRY_LENGTH
            )));
        }
        if encryption_key.len() != UE_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "Encryption key must be {} bytes",
                UE_ENTRY_LENGTH
            )));
        }

        // Extract key_salt from O (bytes 40-47)
        let key_salt = &o_entry[U_KEY_SALT_START..U_KEY_SALT_END];

        // Compute intermediate key: SHA-256(owner_password || key_salt)
        let mut data = Vec::new();
        data.extend_from_slice(owner_password.0.as_bytes());
        data.extend_from_slice(key_salt);

        let intermediate_key = sha256(&data);

        // Encrypt encryption_key with intermediate_key using AES-256-CBC
        let aes = Aes::new(AesKey::new_256(intermediate_key)?);
        let iv = [0u8; 16];

        let encrypted = aes.encrypt_cbc_raw(encryption_key, &iv).map_err(|e| {
            crate::error::PdfError::EncryptionError(format!("OE encryption failed: {}", e))
        })?;

        // OE is first 32 bytes of encrypted output
        Ok(encrypted[..UE_ENTRY_LENGTH].to_vec())
    }

    /// Recover encryption key from R5 OE entry using owner password
    pub fn recover_r5_owner_encryption_key(
        &self,
        owner_password: &OwnerPassword,
        o_entry: &[u8],
        oe_entry: &[u8],
    ) -> Result<Vec<u8>> {
        if o_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "O entry must be {} bytes",
                U_ENTRY_LENGTH
            )));
        }
        if oe_entry.len() != UE_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "OE entry must be {} bytes",
                UE_ENTRY_LENGTH
            )));
        }

        // Extract key_salt from O (bytes 40-47)
        let key_salt = &o_entry[U_KEY_SALT_START..U_KEY_SALT_END];

        // Compute intermediate key
        let mut data = Vec::new();
        data.extend_from_slice(owner_password.0.as_bytes());
        data.extend_from_slice(key_salt);

        let intermediate_key = sha256(&data);

        // Decrypt OE to get encryption key
        let aes = Aes::new(AesKey::new_256(intermediate_key)?);
        let iv = [0u8; 16];

        let decrypted = aes.decrypt_cbc_raw(oe_entry, &iv).map_err(|e| {
            crate::error::PdfError::EncryptionError(format!("OE decryption failed: {}", e))
        })?;

        Ok(decrypted)
    }

    /// Compute R6 owner password hash (O entry)
    ///
    /// R6 uses Algorithm 2.B (complex hash) for owner password too
    pub fn compute_r6_owner_hash(
        &self,
        owner_password: &OwnerPassword,
        u_entry: &[u8],
    ) -> Result<Vec<u8>> {
        if self.revision != SecurityHandlerRevision::R6 {
            return Err(crate::error::PdfError::EncryptionError(
                "R6 owner hash only for Revision 6".to_string(),
            ));
        }
        if u_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "U entry must be {} bytes for R6 O computation",
                U_ENTRY_LENGTH
            )));
        }

        // Generate random salts
        let validation_salt = generate_salt(R6_SALT_LENGTH);
        let key_salt = generate_salt(R6_SALT_LENGTH);

        // For R6, use Algorithm 2.B: hash = Alg2B(owner_password || validation_salt || U[0..48])
        let mut input = Vec::new();
        input.extend_from_slice(owner_password.0.as_bytes());
        input.extend_from_slice(&validation_salt);
        input.extend_from_slice(u_entry);

        let hash = compute_hash_r6_algorithm_2b(&input, owner_password.0.as_bytes(), u_entry)?;

        // Construct O entry: hash[0..32] + validation_salt + key_salt
        let mut o_entry = Vec::with_capacity(U_ENTRY_LENGTH);
        o_entry.extend_from_slice(&hash[..U_HASH_LENGTH]);
        o_entry.extend_from_slice(&validation_salt);
        o_entry.extend_from_slice(&key_salt);

        debug_assert_eq!(o_entry.len(), U_ENTRY_LENGTH);
        Ok(o_entry)
    }

    /// Validate R6 owner password
    ///
    /// Uses Algorithm 2.B to validate owner password
    pub fn validate_r6_owner_password(
        &self,
        owner_password: &OwnerPassword,
        o_entry: &[u8],
        u_entry: &[u8],
    ) -> Result<bool> {
        if o_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "R6 O entry must be {} bytes",
                U_ENTRY_LENGTH
            )));
        }
        if u_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "R6 U entry must be {} bytes",
                U_ENTRY_LENGTH
            )));
        }

        // Extract validation_salt from O (bytes 32-39)
        let validation_salt = &o_entry[U_VALIDATION_SALT_START..U_VALIDATION_SALT_END];

        // Compute hash using Algorithm 2.B
        let mut input = Vec::new();
        input.extend_from_slice(owner_password.0.as_bytes());
        input.extend_from_slice(validation_salt);
        input.extend_from_slice(u_entry);

        let hash = compute_hash_r6_algorithm_2b(&input, owner_password.0.as_bytes(), u_entry)?;

        // SECURITY: Constant-time comparison prevents timing attacks
        let stored_hash = &o_entry[..U_HASH_LENGTH];
        Ok(bool::from(hash[..U_HASH_LENGTH].ct_eq(stored_hash)))
    }

    /// Compute R6 OE entry (encrypted encryption key with owner password)
    ///
    /// Uses Algorithm 2.B to derive intermediate key
    pub fn compute_r6_oe_entry(
        &self,
        owner_password: &OwnerPassword,
        o_entry: &[u8],
        u_entry: &[u8],
        encryption_key: &[u8],
    ) -> Result<Vec<u8>> {
        if o_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "O entry must be {} bytes",
                U_ENTRY_LENGTH
            )));
        }
        if u_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "U entry must be {} bytes",
                U_ENTRY_LENGTH
            )));
        }
        if encryption_key.len() != UE_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "Encryption key must be {} bytes",
                UE_ENTRY_LENGTH
            )));
        }

        // Extract key_salt from O (bytes 40-47)
        let key_salt = &o_entry[U_KEY_SALT_START..U_KEY_SALT_END];

        // Compute intermediate key using Algorithm 2.B
        let mut input = Vec::new();
        input.extend_from_slice(owner_password.0.as_bytes());
        input.extend_from_slice(key_salt);
        input.extend_from_slice(u_entry);

        let intermediate_key =
            compute_hash_r6_algorithm_2b(&input, owner_password.0.as_bytes(), u_entry)?;

        // Encrypt encryption_key with intermediate_key using AES-256-CBC
        let aes = Aes::new(AesKey::new_256(intermediate_key[..32].to_vec())?);
        let iv = [0u8; 16];

        let encrypted = aes.encrypt_cbc_raw(encryption_key, &iv).map_err(|e| {
            crate::error::PdfError::EncryptionError(format!("OE encryption failed: {}", e))
        })?;

        Ok(encrypted[..UE_ENTRY_LENGTH].to_vec())
    }

    /// Recover encryption key from R6 OE entry using owner password
    pub fn recover_r6_owner_encryption_key(
        &self,
        owner_password: &OwnerPassword,
        o_entry: &[u8],
        u_entry: &[u8],
        oe_entry: &[u8],
    ) -> Result<Vec<u8>> {
        if o_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "O entry must be {} bytes",
                U_ENTRY_LENGTH
            )));
        }
        if u_entry.len() != U_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "U entry must be {} bytes",
                U_ENTRY_LENGTH
            )));
        }
        if oe_entry.len() != UE_ENTRY_LENGTH {
            return Err(crate::error::PdfError::EncryptionError(format!(
                "OE entry must be {} bytes",
                UE_ENTRY_LENGTH
            )));
        }

        // Extract key_salt from O (bytes 40-47)
        let key_salt = &o_entry[U_KEY_SALT_START..U_KEY_SALT_END];

        // Compute intermediate key using Algorithm 2.B
        let mut input = Vec::new();
        input.extend_from_slice(owner_password.0.as_bytes());
        input.extend_from_slice(key_salt);
        input.extend_from_slice(u_entry);

        let intermediate_key =
            compute_hash_r6_algorithm_2b(&input, owner_password.0.as_bytes(), u_entry)?;

        // Decrypt OE to get encryption key
        let aes = Aes::new(AesKey::new_256(intermediate_key[..32].to_vec())?);
        let iv = [0u8; 16];

        let decrypted = aes.decrypt_cbc_raw(oe_entry, &iv).map_err(|e| {
            crate::error::PdfError::EncryptionError(format!("OE decryption failed: {}", e))
        })?;

        Ok(decrypted)
    }

    /// Compute object-specific encryption key (Algorithm 1, ISO 32000-1 §7.6.2)
    pub fn compute_object_key(&self, key: &EncryptionKey, obj_id: &ObjectId) -> Vec<u8> {
        let mut data = Vec::new();
        data.extend_from_slice(&key.key);
        data.extend_from_slice(&obj_id.number().to_le_bytes()[..3]); // Low 3 bytes
        data.extend_from_slice(&obj_id.generation().to_le_bytes()[..2]); // Low 2 bytes

        let hash = md5::compute(&data);
        let key_len = (key.len() + 5).min(16);
        hash[..key_len].to_vec()
    }

    /// Validate user password (Algorithm 6, ISO 32000-1 §7.6.3.4)
    ///
    /// Returns Ok(true) if password is correct, Ok(false) if incorrect.
    /// Returns Err only on internal errors.
    pub fn validate_user_password(
        &self,
        password: &UserPassword,
        user_hash: &[u8],
        owner_hash: &[u8],
        permissions: Permissions,
        file_id: Option<&[u8]>,
    ) -> Result<bool> {
        // Compute encryption key from provided password
        let key = self.compute_encryption_key(password, owner_hash, permissions, file_id)?;

        match self.revision {
            SecurityHandlerRevision::R2 => {
                // For R2: Encrypt padding with key and compare with U
                let rc4_key = Rc4Key::from_slice(&key.key);
                let encrypted_padding = rc4_encrypt(&rc4_key, &PADDING);

                // Compare with stored user hash
                Ok(user_hash.len() >= 32 && encrypted_padding[..] == user_hash[..32])
            }
            SecurityHandlerRevision::R3 | SecurityHandlerRevision::R4 => {
                // For R3/R4: Compute MD5 hash including file ID
                let mut data = Vec::new();
                data.extend_from_slice(&PADDING);

                if let Some(id) = file_id {
                    data.extend_from_slice(id);
                }

                let hash = md5::compute(&data);

                // Encrypt hash with RC4
                let rc4_key = Rc4Key::from_slice(&key.key);
                let mut encrypted = rc4_encrypt(&rc4_key, hash.as_ref());

                // Do 19 additional iterations with modified keys
                for i in 1..=19 {
                    let mut key_bytes = key.key.clone();
                    for byte in &mut key_bytes {
                        *byte ^= i as u8;
                    }
                    let iter_key = Rc4Key::from_slice(&key_bytes);
                    encrypted = rc4_encrypt(&iter_key, &encrypted);
                }

                // Compare first 16 bytes of result with first 16 bytes of U
                Ok(user_hash.len() >= 16 && encrypted[..16] == user_hash[..16])
            }
            SecurityHandlerRevision::R5 | SecurityHandlerRevision::R6 => {
                // For R5/R6, use AES-based validation
                self.validate_aes_user_password(password, user_hash, permissions, file_id)
            }
        }
    }

    /// Validate owner password (Algorithm 7, ISO 32000-1 §7.6.3.4)
    ///
    /// Returns Ok(true) if password is correct, Ok(false) if incorrect.
    /// Returns Err only on internal errors.
    ///
    /// Note: For owner password validation, we first decrypt the user password
    /// from the owner hash, then validate that user password.
    ///
    /// # Parameters
    /// - `owner_password`: The owner password to validate
    /// - `owner_hash`: The O entry from the encryption dictionary
    /// - `_user_password`: Unused for R2-R4 (recovered from owner_hash), ignored for R5/R6
    /// - `_permissions`: Unused for R5/R6 (not part of validation)
    /// - `_file_id`: Unused for R5/R6 (not part of validation)
    /// - `u_entry`: Required for R6 (U entry needed for Algorithm 2.B), ignored for R2-R5
    pub fn validate_owner_password(
        &self,
        owner_password: &OwnerPassword,
        owner_hash: &[u8],
        _user_password: &UserPassword, // Will be recovered from owner_hash
        _permissions: Permissions,
        _file_id: Option<&[u8]>,
        u_entry: Option<&[u8]>,
    ) -> Result<bool> {
        match self.revision {
            SecurityHandlerRevision::R2
            | SecurityHandlerRevision::R3
            | SecurityHandlerRevision::R4 => {
                // Step 1: Pad owner password
                let owner_pad = Self::pad_password(&owner_password.0);

                // Step 2: Create MD5 hash of owner password
                let mut hash = md5::compute(&owner_pad).to_vec();

                // Step 3: For revision 3+, do 50 additional iterations
                if self.revision >= SecurityHandlerRevision::R3 {
                    for _ in 0..50 {
                        hash = md5::compute(&hash).to_vec();
                    }
                }

                // Step 4: Create RC4 key from hash (truncated to key length)
                let rc4_key = Rc4Key::from_slice(&hash[..self.key_length]);

                // Step 5: Decrypt owner hash to get user password
                let mut decrypted = owner_hash[..32].to_vec();

                // For R3+, do 19 iterations in reverse
                if self.revision >= SecurityHandlerRevision::R3 {
                    for i in (0..20).rev() {
                        let mut key_bytes = hash[..self.key_length].to_vec();
                        for byte in &mut key_bytes {
                            *byte ^= i as u8;
                        }
                        let iter_key = Rc4Key::from_slice(&key_bytes);
                        decrypted = rc4_encrypt(&iter_key, &decrypted);
                    }
                } else {
                    // For R2, single decryption
                    decrypted = rc4_encrypt(&rc4_key, &decrypted);
                }

                // Step 6: The decrypted data should be the padded user password
                // Try to validate by computing what the owner hash SHOULD be
                // with this owner password, and compare

                // Extract potential user password (remove padding)
                let user_pwd_bytes = decrypted
                    .iter()
                    .take_while(|&&b| b != 0x28 || decrypted.starts_with(&PADDING))
                    .copied()
                    .collect::<Vec<u8>>();

                let recovered_user =
                    UserPassword(String::from_utf8_lossy(&user_pwd_bytes).to_string());

                // Compute what owner hash should be with this owner password
                let computed_owner = self.compute_owner_hash(owner_password, &recovered_user);

                // Compare with stored owner hash
                Ok(computed_owner[..32] == owner_hash[..32])
            }
            SecurityHandlerRevision::R5 => {
                // R5 uses simple SHA-256 validation (Algorithm 12)
                // owner_hash is the O entry (48 bytes)
                self.validate_r5_owner_password(owner_password, owner_hash)
            }
            SecurityHandlerRevision::R6 => {
                // R6 uses Algorithm 2.B which requires U entry
                let u = u_entry.ok_or_else(|| {
                    crate::error::PdfError::EncryptionError(
                        "R6 owner password validation requires U entry".to_string(),
                    )
                })?;
                self.validate_r6_owner_password(owner_password, owner_hash, u)
            }
        }
    }
}

/// Helper function for RC4 encryption
fn rc4_encrypt(key: &Rc4Key, data: &[u8]) -> Vec<u8> {
    let mut cipher = Rc4::new(key);
    cipher.process(data)
}

// Use the md5 crate for actual MD5 hashing (required for PDF encryption)

/// SHA-256 implementation using RustCrypto (production-grade)
///
/// Returns a 32-byte hash of the input data according to FIPS 180-4.
/// Used for R5 password validation and key derivation.
fn sha256(data: &[u8]) -> Vec<u8> {
    Sha256::digest(data).to_vec()
}

/// SHA-384 implementation using RustCrypto (production-grade)
///
/// Returns a 48-byte hash of the input data according to FIPS 180-4.
/// Used for R6 Algorithm 2.B hash rotation.
fn sha384(data: &[u8]) -> Vec<u8> {
    Sha384::digest(data).to_vec()
}

/// SHA-512 implementation using RustCrypto (production-grade)
///
/// Returns a 64-byte hash of the input data according to FIPS 180-4.
/// Used for R6 password validation and key derivation.
fn sha512(data: &[u8]) -> Vec<u8> {
    Sha512::digest(data).to_vec()
}

// ============================================================================
// Algorithm 2.B - R6 Key Derivation (ISO 32000-2:2020 §7.6.4.3.4)
// ============================================================================

/// Minimum number of rounds for Algorithm 2.B
const ALGORITHM_2B_MIN_ROUNDS: usize = 64;

/// Maximum rounds (DoS protection, not in spec but common implementation)
const ALGORITHM_2B_MAX_ROUNDS: usize = 2048;

/// Maximum password length (ISO 32000-2 §7.6.3.3.2 recommends 127 bytes)
/// This prevents DoS via massive allocation: 1MB password × 64 repetitions = 64MB/round
const ALGORITHM_2B_MAX_PASSWORD_LEN: usize = 127;

/// Number of bytes used for hash function selection (spec: first 16 bytes as BigInteger mod 3)
const HASH_SELECTOR_BYTES: usize = 16;

/// Compute R6 password hash using Algorithm 2.B (ISO 32000-2:2020 §7.6.4.3.4)
///
/// This is the correct R6 key derivation algorithm used by qpdf, Adobe Acrobat,
/// and other compliant PDF processors. It uses AES-128-CBC encryption within
/// the iteration loop and dynamically selects SHA-256/384/512 based on output.
///
/// # Algorithm Overview
/// 1. Initial hash: K = SHA-256(password + salt + U\[0..48\])
/// 2. Loop (minimum 64 rounds):
///    a. Construct k1 = (password + K + U\[0..48\]), repeat 64 times
///    b. E = AES-128-CBC-encrypt(k1, key=K\[0..16\], iv=K\[16..32\])
///    c. Select hash: SHA-256/384/512 based on sum(E\[0..16\]) mod 3
///    d. K = hash(E)
///    e. Check termination: round >= 64 AND E\[last\] <= (round - 32)
/// 3. Return K\[0..32\]
///
/// # Parameters
/// - `password`: User password bytes (UTF-8 encoded)
/// - `salt`: 8-byte salt (validation_salt or key_salt from U entry)
/// - `u_entry`: Full 48-byte U entry (or empty slice for initial computation)
///
/// # Returns
/// 32-byte derived key
///
/// # Security Notes
/// - Maximum 2048 rounds to prevent DoS attacks
/// - Variable iteration count makes brute-force harder
/// - AES encryption + hash rotation provides strong KDF
///
/// # References
/// - ISO 32000-2:2020 §7.6.4.3.4 "Algorithm 2.B: Computing a hash (R6)"
pub fn compute_hash_r6_algorithm_2b(
    password: &[u8],
    salt: &[u8],
    u_entry: &[u8],
) -> Result<Vec<u8>> {
    // Security: Validate password length to prevent DoS via massive allocations
    if password.len() > ALGORITHM_2B_MAX_PASSWORD_LEN {
        return Err(crate::error::PdfError::EncryptionError(format!(
            "Password too long ({} bytes, max {})",
            password.len(),
            ALGORITHM_2B_MAX_PASSWORD_LEN
        )));
    }

    // Step 1: Initial hash K = SHA-256(password + salt + U[0..48])
    let mut input = Vec::with_capacity(password.len() + salt.len() + u_entry.len().min(48));
    input.extend_from_slice(password);
    input.extend_from_slice(salt);
    if !u_entry.is_empty() {
        input.extend_from_slice(&u_entry[..u_entry.len().min(48)]);
    }

    let mut k = sha256(&input);

    // Step 2: Iteration loop
    let mut round: usize = 0;
    loop {
        // 2a. Construct input sequence: password + K + U[0..48], repeated
        // The spec says to create a sequence that will be encrypted
        let mut k1_unit = Vec::new();
        k1_unit.extend_from_slice(password);
        k1_unit.extend_from_slice(&k);
        if !u_entry.is_empty() {
            k1_unit.extend_from_slice(&u_entry[..u_entry.len().min(48)]);
        }

        // Repeat 64 times to create input for AES
        let mut k1 = Vec::with_capacity(k1_unit.len() * 64);
        for _ in 0..64 {
            k1.extend_from_slice(&k1_unit);
        }

        // Zero-pad to AES block size (16 bytes) per ISO 32000-2 §7.6.4.3.4
        // NOTE: This is zero-padding, NOT PKCS#7 - the spec requires raw AES without padding removal
        while k1.len() % 16 != 0 {
            k1.push(0);
        }

        // 2b. AES-128-CBC encryption
        // Key: first 16 bytes of K, IV: next 16 bytes of K
        if k.len() < 32 {
            // Extend K if needed (shouldn't happen with proper hashes)
            while k.len() < 32 {
                k.push(0);
            }
        }

        let aes_key = AesKey::new_128(k[..16].to_vec()).map_err(|e| {
            crate::error::PdfError::EncryptionError(format!(
                "Algorithm 2.B: Failed to create AES key: {}",
                e
            ))
        })?;
        let aes = Aes::new(aes_key);
        let iv = &k[16..32];

        let e = aes.encrypt_cbc_raw(&k1, iv).map_err(|e| {
            crate::error::PdfError::EncryptionError(format!(
                "Algorithm 2.B: AES encryption failed: {}",
                e
            ))
        })?;

        // 2c. Select hash function based on first 16 bytes of E as BigInteger mod 3
        // Per iText/Adobe implementation: interpret E[0..HASH_SELECTOR_BYTES] as big-endian integer
        // Mathematical equivalence: sum(bytes) mod 3 == BigInteger(bytes) mod 3
        // because 256 mod 3 = 1, therefore 256^k mod 3 = 1 for all k
        let hash_selector = {
            let sum: u64 = e[..HASH_SELECTOR_BYTES.min(e.len())]
                .iter()
                .map(|&b| b as u64)
                .sum();
            (sum % 3) as u8
        };

        k = match hash_selector {
            0 => sha256(&e),
            1 => sha384(&e),
            2 => sha512(&e),
            _ => unreachable!("Modulo 3 can only be 0, 1, or 2"),
        };

        // 2d. Check termination condition
        // Terminate when: round >= 64 AND E[last] <= (round - 32)
        let last_byte = *e.last().unwrap_or(&0);
        round += 1;

        if round >= ALGORITHM_2B_MIN_ROUNDS {
            // The termination condition from ISO spec:
            // "the last byte value of the last iteration is less than or equal to
            // the number of iterations minus 32"
            if (last_byte as usize) <= round.saturating_sub(32) {
                break;
            }
        }

        // Safety: Prevent infinite loop (DoS protection)
        if round >= ALGORITHM_2B_MAX_ROUNDS {
            break;
        }
    }

    // Step 3: Return first 32 bytes of final K
    // K might be > 32 bytes if last hash was SHA-384 or SHA-512
    Ok(k[..32.min(k.len())].to_vec())
}

/// R5 salt length in bytes (PDF spec §7.6.4.3.4)
const R5_SALT_LENGTH: usize = 8;

/// R5 SHA-256 iteration count (ISO 32000-2:2020 Algorithm 8/11)
/// NOTE: R5 does NOT use iterations - hash is simply SHA-256(password + salt)
/// The 64 iterations are only for R6 which uses Algorithm 2.B
const R5_HASH_ITERATIONS: usize = 0;

/// R6 salt length in bytes (PDF spec ISO 32000-2)
const R6_SALT_LENGTH: usize = 8;

// ============================================================================
// R5/R6 U Entry Structure Constants (48 bytes total)
// ============================================================================

/// Length of the hash portion in U entry (SHA-256/SHA-512 truncated to 32 bytes)
const U_HASH_LENGTH: usize = 32;

/// Start offset of validation salt in U entry
const U_VALIDATION_SALT_START: usize = 32;

/// End offset of validation salt in U entry
const U_VALIDATION_SALT_END: usize = 40;

/// Start offset of key salt in U entry
const U_KEY_SALT_START: usize = 40;

/// End offset of key salt in U entry
const U_KEY_SALT_END: usize = 48;

/// Total length of U entry for R5/R6
const U_ENTRY_LENGTH: usize = 48;

/// Length of UE entry (encrypted encryption key)
const UE_ENTRY_LENGTH: usize = 32;

// ============================================================================
// R6 Perms Entry Structure Constants (16 bytes total)
// ============================================================================

/// Length of Perms entry
const PERMS_ENTRY_LENGTH: usize = 16;

/// Start offset of permissions value in decrypted Perms (little-endian u32)
const PERMS_P_START: usize = 0;

/// End offset of permissions value in decrypted Perms
const PERMS_P_END: usize = 4;

/// Start offset of fixed marker (0xFFFFFFFF) in decrypted Perms
const PERMS_MARKER_START: usize = 4;

/// End offset of fixed marker in decrypted Perms
const PERMS_MARKER_END: usize = 8;

/// Start offset of "adb" literal in decrypted Perms
const PERMS_LITERAL_START: usize = 8;

/// End offset of "adb" literal in decrypted Perms
const PERMS_LITERAL_END: usize = 11;

/// Offset of EncryptMetadata flag byte ('T' or 'F') in decrypted Perms
const PERMS_ENCRYPT_META_BYTE: usize = 11;

/// Fixed marker value in Perms entry
const PERMS_MARKER: [u8; 4] = [0xFF, 0xFF, 0xFF, 0xFF];

/// Literal verification string in Perms entry
const PERMS_LITERAL: &[u8; 3] = b"adb";

/// Generate cryptographically secure random salt using OS CSPRNG
///
/// Uses `rand::rng()` which provides a thread-local CSPRNG (ChaCha12) seeded
/// from the OS random number generator. This is suitable for PDF encryption salts.
///
/// # Security
/// - Uses ChaCha12 PRNG seeded from OS entropy (rand 0.9 implementation)
/// - Provides cryptographic-quality randomness for salt generation
/// - Each call produces independent random bytes
fn generate_salt(len: usize) -> Vec<u8> {
    let mut salt = vec![0u8; len];
    rand::rng().fill_bytes(&mut salt);
    salt
}

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

    #[test]
    fn test_pad_password() {
        let padded = StandardSecurityHandler::pad_password("test");
        assert_eq!(padded.len(), 32);
        assert_eq!(&padded[..4], b"test");
        assert_eq!(&padded[4..8], &PADDING[..4]);
    }

    #[test]
    fn test_pad_password_long() {
        let long_password = "a".repeat(40);
        let padded = StandardSecurityHandler::pad_password(&long_password);
        assert_eq!(padded.len(), 32);
        assert_eq!(&padded[..32], &long_password.as_bytes()[..32]);
    }

    #[test]
    fn test_rc4_40bit_handler() {
        let handler = StandardSecurityHandler::rc4_40bit();
        assert_eq!(handler.revision, SecurityHandlerRevision::R2);
        assert_eq!(handler.key_length, 5);
    }

    #[test]
    fn test_rc4_128bit_handler() {
        let handler = StandardSecurityHandler::rc4_128bit();
        assert_eq!(handler.revision, SecurityHandlerRevision::R3);
        assert_eq!(handler.key_length, 16);
    }

    #[test]
    fn test_owner_hash_computation() {
        let handler = StandardSecurityHandler::rc4_40bit();
        let owner_pwd = OwnerPassword("owner".to_string());
        let user_pwd = UserPassword("user".to_string());

        let hash = handler.compute_owner_hash(&owner_pwd, &user_pwd);
        assert_eq!(hash.len(), 32);
    }

    #[test]
    fn test_encryption_key_computation() {
        let handler = StandardSecurityHandler::rc4_40bit();
        let user_pwd = UserPassword("user".to_string());
        let owner_hash = vec![0u8; 32];
        let permissions = Permissions::new();

        let key = handler
            .compute_encryption_key(&user_pwd, &owner_hash, permissions, None)
            .unwrap();

        assert_eq!(key.len(), 5);
    }

    #[test]
    fn test_aes_256_r5_handler() {
        let handler = StandardSecurityHandler::aes_256_r5();
        assert_eq!(handler.revision, SecurityHandlerRevision::R5);
        assert_eq!(handler.key_length, 32);
    }

    #[test]
    fn test_aes_256_r6_handler() {
        let handler = StandardSecurityHandler::aes_256_r6();
        assert_eq!(handler.revision, SecurityHandlerRevision::R6);
        assert_eq!(handler.key_length, 32);
    }

    #[test]
    fn test_aes_encryption_key_computation() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let user_pwd = UserPassword("testuser".to_string());
        let owner_hash = vec![0u8; 32];
        let permissions = Permissions::new();

        let key = handler
            .compute_aes_encryption_key(&user_pwd, &owner_hash, permissions, None)
            .unwrap();

        assert_eq!(key.len(), 32);
    }

    #[test]
    fn test_aes_encrypt_decrypt() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let key = EncryptionKey::new(vec![0u8; 32]);
        let obj_id = ObjectId::new(1, 0);
        let data = b"Hello AES encryption!";

        let encrypted = handler.encrypt_aes(data, &key, &obj_id).unwrap();
        assert_ne!(encrypted.as_slice(), data);
        assert!(encrypted.len() > data.len()); // Should include IV

        // Note: This simplified AES implementation is for demonstration only
        let _decrypted = handler.decrypt_aes(&encrypted, &key, &obj_id);
        // For now, just test that the operations complete without panicking
    }

    #[test]
    fn test_aes_with_rc4_handler_fails() {
        let handler = StandardSecurityHandler::rc4_128bit();
        let key = EncryptionKey::new(vec![0u8; 16]);
        let obj_id = ObjectId::new(1, 0);
        let data = b"test data";

        // Should fail because handler is not Rev 5+
        assert!(handler.encrypt_aes(data, &key, &obj_id).is_err());
        assert!(handler.decrypt_aes(data, &key, &obj_id).is_err());
    }

    #[test]
    fn test_aes_decrypt_invalid_data() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let key = EncryptionKey::new(vec![0u8; 32]);
        let obj_id = ObjectId::new(1, 0);

        // Data too short (no IV)
        let short_data = vec![0u8; 10];
        assert!(handler.decrypt_aes(&short_data, &key, &obj_id).is_err());
    }

    #[test]
    fn test_sha256_deterministic() {
        let data1 = b"test data";
        let data2 = b"test data";
        let data3 = b"different data";

        let hash1 = sha256(data1);
        let hash2 = sha256(data2);
        let hash3 = sha256(data3);

        assert_eq!(hash1.len(), 32);
        assert_eq!(hash2.len(), 32);
        assert_eq!(hash3.len(), 32);

        assert_eq!(hash1, hash2); // Same input should give same output
        assert_ne!(hash1, hash3); // Different input should give different output
    }

    #[test]
    fn test_security_handler_revision_ordering() {
        assert!(SecurityHandlerRevision::R2 < SecurityHandlerRevision::R3);
        assert!(SecurityHandlerRevision::R3 < SecurityHandlerRevision::R4);
        assert!(SecurityHandlerRevision::R4 < SecurityHandlerRevision::R5);
        assert!(SecurityHandlerRevision::R5 < SecurityHandlerRevision::R6);
    }

    #[test]
    fn test_aes_password_validation() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let password = UserPassword("testpassword".to_string());
        let user_hash = vec![0u8; 32]; // Simplified hash
        let permissions = Permissions::new();

        // This is a basic test - in practice, the validation would be more complex
        let result = handler.validate_aes_user_password(&password, &user_hash, permissions, None);
        assert!(result.is_ok());
    }

    // ===== Additional Comprehensive Tests =====

    #[test]
    fn test_user_password_debug() {
        let pwd = UserPassword("debug_test".to_string());
        let debug_str = format!("{pwd:?}");
        assert!(debug_str.contains("UserPassword"));
        assert!(debug_str.contains("debug_test"));
    }

    #[test]
    fn test_owner_password_debug() {
        let pwd = OwnerPassword("owner_debug".to_string());
        let debug_str = format!("{pwd:?}");
        assert!(debug_str.contains("OwnerPassword"));
        assert!(debug_str.contains("owner_debug"));
    }

    #[test]
    fn test_encryption_key_debug() {
        let key = EncryptionKey::new(vec![0x01, 0x02, 0x03]);
        let debug_str = format!("{key:?}");
        assert!(debug_str.contains("EncryptionKey"));
    }

    #[test]
    fn test_security_handler_revision_equality() {
        assert_eq!(SecurityHandlerRevision::R2, SecurityHandlerRevision::R2);
        assert_ne!(SecurityHandlerRevision::R2, SecurityHandlerRevision::R3);
    }

    #[test]
    fn test_security_handler_revision_values() {
        assert_eq!(SecurityHandlerRevision::R2 as u8, 2);
        assert_eq!(SecurityHandlerRevision::R3 as u8, 3);
        assert_eq!(SecurityHandlerRevision::R4 as u8, 4);
        assert_eq!(SecurityHandlerRevision::R5 as u8, 5);
        assert_eq!(SecurityHandlerRevision::R6 as u8, 6);
    }

    #[test]
    fn test_pad_password_various_lengths() {
        for len in 0..=40 {
            let password = "x".repeat(len);
            let padded = StandardSecurityHandler::pad_password(&password);
            assert_eq!(padded.len(), 32);

            if len <= 32 {
                assert_eq!(&padded[..len], password.as_bytes());
            } else {
                assert_eq!(&padded[..], &password.as_bytes()[..32]);
            }
        }
    }

    #[test]
    fn test_pad_password_unicode() {
        let padded = StandardSecurityHandler::pad_password("café");
        assert_eq!(padded.len(), 32);
        // UTF-8 encoding of "café" is 5 bytes
        assert_eq!(&padded[..5], "café".as_bytes());
    }

    #[test]
    fn test_compute_owner_hash_different_users() {
        let handler = StandardSecurityHandler::rc4_128bit();
        let owner = OwnerPassword("owner".to_string());
        let user1 = UserPassword("user1".to_string());
        let user2 = UserPassword("user2".to_string());

        let hash1 = handler.compute_owner_hash(&owner, &user1);
        let hash2 = handler.compute_owner_hash(&owner, &user2);

        assert_ne!(hash1, hash2); // Different user passwords should produce different hashes
    }

    #[test]
    fn test_compute_user_hash_r4() {
        let handler = StandardSecurityHandler {
            revision: SecurityHandlerRevision::R4,
            key_length: 16,
        };
        let user = UserPassword("r4test".to_string());
        let owner_hash = vec![0xAA; 32];
        let permissions = Permissions::new();

        let hash = handler
            .compute_user_hash(&user, &owner_hash, permissions, None)
            .unwrap();
        assert_eq!(hash.len(), 32);
    }

    #[test]
    fn test_compute_user_hash_r6() {
        let handler = StandardSecurityHandler::aes_256_r6();
        let user = UserPassword("r6test".to_string());
        let owner_hash = vec![0xBB; 32];
        let permissions = Permissions::all();

        let hash = handler
            .compute_user_hash(&user, &owner_hash, permissions, None)
            .unwrap();
        assert_eq!(hash.len(), 32);
    }

    #[test]
    fn test_encryption_key_with_file_id_affects_result() {
        let handler = StandardSecurityHandler::rc4_128bit();
        let user = UserPassword("test".to_string());
        let owner_hash = vec![0xFF; 32];
        let permissions = Permissions::new();
        let file_id = b"unique_file_id_12345";

        let key_with_id = handler
            .compute_encryption_key(&user, &owner_hash, permissions, Some(file_id))
            .unwrap();
        let key_without_id = handler
            .compute_encryption_key(&user, &owner_hash, permissions, None)
            .unwrap();

        assert_ne!(key_with_id.key, key_without_id.key);
    }

    #[test]
    fn test_encrypt_string_empty() {
        let handler = StandardSecurityHandler::rc4_40bit();
        let key = EncryptionKey::new(vec![0x01, 0x02, 0x03, 0x04, 0x05]);
        let obj_id = ObjectId::new(1, 0);

        let encrypted = handler.encrypt_string(b"", &key, &obj_id);
        assert_eq!(encrypted.len(), 0);
    }

    #[test]
    fn test_encrypt_decrypt_large_data() {
        let handler = StandardSecurityHandler::rc4_128bit();
        let key = EncryptionKey::new(vec![0xAA; 16]);
        let obj_id = ObjectId::new(42, 0);
        let large_data = vec![0x55; 10000]; // 10KB

        let encrypted = handler.encrypt_string(&large_data, &key, &obj_id);
        assert_eq!(encrypted.len(), large_data.len());
        assert_ne!(encrypted, large_data);

        let decrypted = handler.decrypt_string(&encrypted, &key, &obj_id);
        assert_eq!(decrypted, large_data);
    }

    #[test]
    fn test_stream_encryption_different_from_string() {
        // For current implementation they're the same, but test separately
        let handler = StandardSecurityHandler::rc4_128bit();
        let key = EncryptionKey::new(vec![0x11; 16]);
        let obj_id = ObjectId::new(5, 1);
        let data = b"Stream content test";

        let encrypted_string = handler.encrypt_string(data, &key, &obj_id);
        let encrypted_stream = handler.encrypt_stream(data, &key, &obj_id);

        assert_eq!(encrypted_string, encrypted_stream); // Currently same implementation
    }

    #[test]
    fn test_aes_encryption_with_different_object_ids() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let key = EncryptionKey::new(vec![0x77; 32]);
        let obj_id1 = ObjectId::new(10, 0);
        let obj_id2 = ObjectId::new(11, 0);
        let data = b"AES test data";

        let encrypted1 = handler.encrypt_aes(data, &key, &obj_id1).unwrap();
        let encrypted2 = handler.encrypt_aes(data, &key, &obj_id2).unwrap();

        // Different object IDs should produce different ciphertexts
        assert_ne!(encrypted1, encrypted2);
    }

    #[test]
    fn test_aes_decrypt_invalid_iv_length() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let key = EncryptionKey::new(vec![0x88; 32]);
        let obj_id = ObjectId::new(1, 0);

        // Data too short to contain IV
        let short_data = vec![0u8; 10];
        assert!(handler.decrypt_aes(&short_data, &key, &obj_id).is_err());

        // Exactly 16 bytes (only IV, no encrypted data)
        let iv_only = vec![0u8; 16];
        let result = handler.decrypt_aes(&iv_only, &key, &obj_id);
        // This might succeed with empty decrypted data or fail depending on implementation
        if let Ok(decrypted) = result {
            assert_eq!(decrypted.len(), 0);
        }
    }

    #[test]
    fn test_aes_validate_password_wrong_hash_length() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let password = UserPassword("test".to_string());
        let short_hash = vec![0u8; 16]; // Too short
        let permissions = Permissions::new();

        let result = handler
            .validate_aes_user_password(&password, &short_hash, permissions, None)
            .unwrap();
        assert!(!result); // Should return false for invalid hash
    }

    #[test]
    fn test_permissions_affect_encryption_key() {
        let handler = StandardSecurityHandler::rc4_128bit();
        let user = UserPassword("same_user".to_string());
        let owner_hash = vec![0xCC; 32];

        let perms1 = Permissions::new();
        let perms2 = Permissions::all();

        let key1 = handler
            .compute_encryption_key(&user, &owner_hash, perms1, None)
            .unwrap();
        let key2 = handler
            .compute_encryption_key(&user, &owner_hash, perms2, None)
            .unwrap();

        assert_ne!(key1.key, key2.key); // Different permissions should affect the key
    }

    #[test]
    fn test_different_handlers_produce_different_keys() {
        let user = UserPassword("test".to_string());
        let owner_hash = vec![0xDD; 32];
        let permissions = Permissions::new();

        let handler_r2 = StandardSecurityHandler::rc4_40bit();
        let handler_r3 = StandardSecurityHandler::rc4_128bit();

        let key_r2 = handler_r2
            .compute_encryption_key(&user, &owner_hash, permissions, None)
            .unwrap();
        let key_r3 = handler_r3
            .compute_encryption_key(&user, &owner_hash, permissions, None)
            .unwrap();

        assert_ne!(key_r2.len(), key_r3.len()); // Different key lengths
        assert_eq!(key_r2.len(), 5);
        assert_eq!(key_r3.len(), 16);
    }

    #[test]
    fn test_full_workflow_aes_r6() {
        let handler = StandardSecurityHandler::aes_256_r6();
        let user_pwd = UserPassword("user_r6".to_string());
        let permissions = Permissions::new();
        let file_id = b"test_file_r6";

        // For AES R5/R6, owner hash computation is different - use a dummy hash
        let owner_hash = vec![0x42; 32]; // AES uses 32-byte hashes

        // Compute user hash
        let user_hash = handler
            .compute_user_hash(&user_pwd, &owner_hash, permissions, Some(file_id))
            .unwrap();
        assert_eq!(user_hash.len(), 32);

        // Compute encryption key
        let key = handler
            .compute_aes_encryption_key(&user_pwd, &owner_hash, permissions, Some(file_id))
            .unwrap();
        assert_eq!(key.len(), 32);

        // Test string encryption (uses AES for R6)
        let obj_id = ObjectId::new(100, 5);
        let content = b"R6 AES encryption test";
        let encrypted = handler.encrypt_string(content, &key, &obj_id);

        // With AES, encrypted should be empty on error or have data
        if !encrypted.is_empty() {
            assert_ne!(encrypted.as_slice(), content);
        }
    }

    #[test]
    fn test_md5_compute_consistency() {
        let data = b"consistent data for md5";
        let hash1 = md5::compute(data);
        let hash2 = md5::compute(data);

        assert_eq!(hash1, hash2);
        assert_eq!(hash1.len(), 16);
    }

    #[test]
    fn test_sha256_consistency() {
        let data = b"consistent data for sha256";
        let hash1 = sha256(data);
        let hash2 = sha256(data);

        assert_eq!(hash1, hash2);
        assert_eq!(hash1.len(), 32);
    }

    #[test]
    fn test_rc4_encrypt_helper() {
        let key = Rc4Key::from_slice(&[0x01, 0x02, 0x03, 0x04, 0x05]);
        let data = b"test rc4 helper";

        let encrypted = rc4_encrypt(&key, data);
        assert_ne!(encrypted.as_slice(), data);

        // RC4 is symmetric
        let decrypted = rc4_encrypt(&key, &encrypted);
        assert_eq!(decrypted.as_slice(), data);
    }

    #[test]
    fn test_edge_case_max_object_generation() {
        let handler = StandardSecurityHandler::rc4_128bit();
        let key = EncryptionKey::new(vec![0xEE; 16]);
        let obj_id = ObjectId::new(0xFFFFFF, 0xFFFF); // Max values
        let data = b"edge case";

        let encrypted = handler.encrypt_string(data, &key, &obj_id);
        let decrypted = handler.decrypt_string(&encrypted, &key, &obj_id);
        assert_eq!(decrypted.as_slice(), data);
    }

    // ===== SHA-256/512 NIST Vector Tests (Phase 1.3 - RustCrypto Integration) =====

    #[test]
    fn test_sha256_nist_empty_string() {
        // NIST FIPS 180-4 test vector: SHA-256("")
        let hash = sha256(b"");
        let expected: [u8; 32] = [
            0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f,
            0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b,
            0x78, 0x52, 0xb8, 0x55,
        ];
        assert_eq!(
            hash.as_slice(),
            expected.as_slice(),
            "SHA-256('') must match NIST test vector"
        );
    }

    #[test]
    fn test_sha256_nist_abc() {
        // NIST FIPS 180-4 test vector: SHA-256("abc")
        let hash = sha256(b"abc");
        let expected: [u8; 32] = [
            0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae,
            0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61,
            0xf2, 0x00, 0x15, 0xad,
        ];
        assert_eq!(
            hash.as_slice(),
            expected.as_slice(),
            "SHA-256('abc') must match NIST test vector"
        );
    }

    #[test]
    fn test_sha512_nist_abc() {
        // NIST FIPS 180-4 test vector: SHA-512("abc")
        let hash = sha512(b"abc");
        let expected: [u8; 64] = [
            0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba, 0xcc, 0x41, 0x73, 0x49, 0xae, 0x20,
            0x41, 0x31, 0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2, 0x0a, 0x9e, 0xee, 0xe6,
            0x4b, 0x55, 0xd3, 0x9a, 0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8, 0x36, 0xba,
            0x3c, 0x23, 0xa3, 0xfe, 0xeb, 0xbd, 0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e,
            0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f,
        ];
        assert_eq!(
            hash.as_slice(),
            expected.as_slice(),
            "SHA-512('abc') must match NIST test vector"
        );
    }

    #[test]
    fn test_sha512_length() {
        let hash = sha512(b"test data");
        assert_eq!(hash.len(), 64, "SHA-512 must produce 64 bytes");
    }

    #[test]
    fn test_sha512_deterministic() {
        let data1 = b"sha512 test data";
        let data2 = b"sha512 test data";
        let data3 = b"different data";

        let hash1 = sha512(data1);
        let hash2 = sha512(data2);
        let hash3 = sha512(data3);

        assert_eq!(hash1, hash2, "Same input must produce same SHA-512 hash");
        assert_ne!(hash1, hash3, "Different input must produce different hash");
    }

    // ===== Phase 2.1: R5 User Password Tests (Algorithm 8 & 11) =====

    #[test]
    fn test_r5_user_hash_computation() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let password = UserPassword("test_password".to_string());

        let u_entry = handler.compute_r5_user_hash(&password).unwrap();

        // U entry must be exactly 48 bytes: hash(32) + validation_salt(8) + key_salt(8)
        assert_eq!(u_entry.len(), 48, "R5 U entry must be 48 bytes");
    }

    #[test]
    fn test_r5_user_password_validation_correct() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let password = UserPassword("correct_password".to_string());

        // Compute U entry with the password
        let u_entry = handler.compute_r5_user_hash(&password).unwrap();

        // Validate with same password should succeed
        let is_valid = handler
            .validate_r5_user_password(&password, &u_entry)
            .unwrap();
        assert!(is_valid, "Correct password must validate");
    }

    #[test]
    fn test_r5_user_password_validation_incorrect() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let correct_password = UserPassword("correct_password".to_string());
        let wrong_password = UserPassword("wrong_password".to_string());

        // Compute U entry with correct password
        let u_entry = handler.compute_r5_user_hash(&correct_password).unwrap();

        // Validate with wrong password should fail
        let is_valid = handler
            .validate_r5_user_password(&wrong_password, &u_entry)
            .unwrap();
        assert!(!is_valid, "Wrong password must not validate");
    }

    #[test]
    fn test_r5_user_hash_random_salts() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let password = UserPassword("same_password".to_string());

        // Compute U entry twice - salts should be different
        let u_entry1 = handler.compute_r5_user_hash(&password).unwrap();
        let u_entry2 = handler.compute_r5_user_hash(&password).unwrap();

        // Hash portion should be different (due to random salts)
        assert_ne!(
            &u_entry1[..32],
            &u_entry2[..32],
            "Different random salts should produce different hashes"
        );

        // Validation salt should be different
        assert_ne!(
            &u_entry1[32..40],
            &u_entry2[32..40],
            "Validation salts must be random"
        );

        // But both should validate with the same password
        assert!(handler
            .validate_r5_user_password(&password, &u_entry1)
            .unwrap());
        assert!(handler
            .validate_r5_user_password(&password, &u_entry2)
            .unwrap());
    }

    #[test]
    fn test_r5_user_hash_invalid_entry_length() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let password = UserPassword("test".to_string());

        // Try to validate with wrong length U entry
        let short_entry = vec![0u8; 32]; // Too short
        let result = handler.validate_r5_user_password(&password, &short_entry);
        assert!(result.is_err(), "Short U entry must fail");

        let long_entry = vec![0u8; 64]; // Too long
        let result = handler.validate_r5_user_password(&password, &long_entry);
        assert!(result.is_err(), "Long U entry must fail");
    }

    #[test]
    fn test_r5_empty_password() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let empty_password = UserPassword("".to_string());

        // Empty password should work (common for user-only encryption)
        let u_entry = handler.compute_r5_user_hash(&empty_password).unwrap();
        assert_eq!(u_entry.len(), 48);

        let is_valid = handler
            .validate_r5_user_password(&empty_password, &u_entry)
            .unwrap();
        assert!(is_valid, "Empty password must validate correctly");

        // Non-empty password should fail
        let non_empty = UserPassword("not_empty".to_string());
        let is_valid = handler
            .validate_r5_user_password(&non_empty, &u_entry)
            .unwrap();
        assert!(!is_valid, "Non-empty password must not validate");
    }

    // ===== Phase 2.2: R5 UE Entry Tests (Encryption Key Storage) =====

    #[test]
    fn test_r5_ue_entry_computation() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let password = UserPassword("ue_test_password".to_string());
        let encryption_key = EncryptionKey::new(vec![0xAB; 32]);

        // Compute U entry first
        let u_entry = handler.compute_r5_user_hash(&password).unwrap();

        // Compute UE entry
        let ue_entry = handler
            .compute_r5_ue_entry(&password, &u_entry, &encryption_key)
            .unwrap();

        // UE entry must be exactly 32 bytes
        assert_eq!(ue_entry.len(), 32, "R5 UE entry must be 32 bytes");

        // UE should be different from the original key (it's encrypted)
        assert_ne!(
            ue_entry.as_slice(),
            encryption_key.as_bytes(),
            "UE must be encrypted"
        );
    }

    #[test]
    fn test_r5_encryption_key_recovery() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let password = UserPassword("recovery_test".to_string());
        let original_key = EncryptionKey::new(vec![0x42; 32]);

        // Compute U entry
        let u_entry = handler.compute_r5_user_hash(&password).unwrap();

        // Compute UE entry
        let ue_entry = handler
            .compute_r5_ue_entry(&password, &u_entry, &original_key)
            .unwrap();

        // Recover the key
        let recovered_key = handler
            .recover_r5_encryption_key(&password, &u_entry, &ue_entry)
            .unwrap();

        // Recovered key must match original
        assert_eq!(
            recovered_key.as_bytes(),
            original_key.as_bytes(),
            "Recovered key must match original"
        );
    }

    #[test]
    fn test_r5_ue_wrong_password_fails() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let correct_password = UserPassword("correct".to_string());
        let wrong_password = UserPassword("wrong".to_string());
        let original_key = EncryptionKey::new(vec![0x99; 32]);

        // Compute U and UE with correct password
        let u_entry = handler.compute_r5_user_hash(&correct_password).unwrap();
        let ue_entry = handler
            .compute_r5_ue_entry(&correct_password, &u_entry, &original_key)
            .unwrap();

        // Try to recover with wrong password
        let recovered_key = handler
            .recover_r5_encryption_key(&wrong_password, &u_entry, &ue_entry)
            .unwrap();

        // Key should be different (wrong decryption)
        assert_ne!(
            recovered_key.as_bytes(),
            original_key.as_bytes(),
            "Wrong password must produce wrong key"
        );
    }

    #[test]
    fn test_r5_ue_invalid_length() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let password = UserPassword("test".to_string());
        let u_entry = vec![0u8; 48]; // Valid U entry length

        // Try to recover with wrong length UE entry
        let short_ue = vec![0u8; 16]; // Too short
        let result = handler.recover_r5_encryption_key(&password, &u_entry, &short_ue);
        assert!(result.is_err(), "Short UE entry must fail");

        let long_ue = vec![0u8; 64]; // Too long
        let result = handler.recover_r5_encryption_key(&password, &u_entry, &long_ue);
        assert!(result.is_err(), "Long UE entry must fail");
    }

    #[test]
    fn test_r5_ue_invalid_u_length() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let password = UserPassword("test".to_string());
        let encryption_key = EncryptionKey::new(vec![0x11; 32]);

        // Try to compute UE with wrong length U entry
        let short_u = vec![0u8; 32]; // Too short
        let result = handler.compute_r5_ue_entry(&password, &short_u, &encryption_key);
        assert!(
            result.is_err(),
            "Short U entry must fail for UE computation"
        );
    }

    #[test]
    fn test_r5_full_workflow_u_ue() {
        let handler = StandardSecurityHandler::aes_256_r5();
        let password = UserPassword("full_workflow_test".to_string());
        let encryption_key = EncryptionKey::new((0..32).collect::<Vec<u8>>());

        // Step 1: Compute U entry (password verification data)
        let u_entry = handler.compute_r5_user_hash(&password).unwrap();
        assert_eq!(u_entry.len(), 48);

        // Step 2: Verify password validates
        assert!(handler
            .validate_r5_user_password(&password, &u_entry)
            .unwrap());

        // Step 3: Compute UE entry (encrypted key storage)
        let ue_entry = handler
            .compute_r5_ue_entry(&password, &u_entry, &encryption_key)
            .unwrap();
        assert_eq!(ue_entry.len(), 32);

        // Step 4: Recover key from UE
        let recovered = handler
            .recover_r5_encryption_key(&password, &u_entry, &ue_entry)
            .unwrap();

        // Step 5: Verify recovered key matches original
        assert_eq!(
            recovered.as_bytes(),
            encryption_key.as_bytes(),
            "Full R5 workflow: recovered key must match original"
        );
    }

    // ===== Phase 3.1: R6 User Password Tests (SHA-512 based) =====

    #[test]
    fn test_r6_user_hash_computation() {
        let handler = StandardSecurityHandler::aes_256_r6();
        let password = UserPassword("r6_test_password".to_string());

        let u_entry = handler.compute_r6_user_hash(&password).unwrap();

        // U entry must be exactly 48 bytes: hash(32) + validation_salt(8) + key_salt(8)
        assert_eq!(u_entry.len(), 48, "R6 U entry must be 48 bytes");
    }

    #[test]
    fn test_r6_user_password_validation_correct() {
        let handler = StandardSecurityHandler::aes_256_r6();
        let password = UserPassword("r6_correct_password".to_string());

        // Compute U entry with the password
        let u_entry = handler.compute_r6_user_hash(&password).unwrap();

        // Validate with same password should succeed
        let is_valid = handler
            .validate_r6_user_password(&password, &u_entry)
            .unwrap();
        assert!(is_valid, "Correct R6 password must validate");
    }

    #[test]
    fn test_r6_user_password_validation_incorrect() {
        let handler = StandardSecurityHandler::aes_256_r6();
        let correct_password = UserPassword("r6_correct".to_string());
        let wrong_password = UserPassword("r6_wrong".to_string());

        // Compute U entry with correct password
        let u_entry = handler.compute_r6_user_hash(&correct_password).unwrap();

        // Validate with wrong password should fail
        let is_valid = handler
            .validate_r6_user_password(&wrong_password, &u_entry)
            .unwrap();
        assert!(!is_valid, "Wrong R6 password must not validate");
    }

    #[test]
    fn test_r6_uses_sha512_not_sha256() {
        // Verify R6 produces different hash than R5 for same password
        let handler_r5 = StandardSecurityHandler::aes_256_r5();
        let handler_r6 = StandardSecurityHandler::aes_256_r6();
        let password = UserPassword("same_password_both_revisions".to_string());

        let u_r5 = handler_r5.compute_r5_user_hash(&password).unwrap();
        let u_r6 = handler_r6.compute_r6_user_hash(&password).unwrap();

        // Hash portions (first 32 bytes) should be different
        // Note: Salts are random, but even with same salt the hash algorithm differs
        assert_ne!(
            &u_r5[..32],
            &u_r6[..32],
            "R5 (SHA-256) and R6 (SHA-512) must produce different hashes"
        );
    }

    #[test]
    fn test_r6_unicode_password() {
        let handler = StandardSecurityHandler::aes_256_r6();
        let unicode_password = UserPassword("café🔒日本語".to_string());

        let u_entry = handler.compute_r6_user_hash(&unicode_password).unwrap();
        assert_eq!(u_entry.len(), 48);

        // Validate with same Unicode password
        let is_valid = handler
            .validate_r6_user_password(&unicode_password, &u_entry)
            .unwrap();
        assert!(is_valid, "Unicode password must validate");

        // Different Unicode password should fail
        let different_unicode = UserPassword("café🔓日本語".to_string()); // Different emoji
        let is_valid = handler
            .validate_r6_user_password(&different_unicode, &u_entry)
            .unwrap();
        assert!(!is_valid, "Different Unicode password must not validate");
    }

    // ===== Phase 3.1: R6 UE Entry Tests =====

    #[test]
    fn test_r6_ue_entry_computation() {
        let handler = StandardSecurityHandler::aes_256_r6();
        let password = UserPassword("r6_ue_test".to_string());
        let encryption_key = EncryptionKey::new(vec![0xCD; 32]);

        let u_entry = handler.compute_r6_user_hash(&password).unwrap();
        let ue_entry = handler
            .compute_r6_ue_entry(&password, &u_entry, &encryption_key)
            .unwrap();

        assert_eq!(ue_entry.len(), 32, "R6 UE entry must be 32 bytes");
    }

    #[test]
    fn test_r6_encryption_key_recovery() {
        let handler = StandardSecurityHandler::aes_256_r6();
        let password = UserPassword("r6_recovery_test".to_string());
        let original_key = EncryptionKey::new(vec![0xEF; 32]);

        let u_entry = handler.compute_r6_user_hash(&password).unwrap();
        let ue_entry = handler
            .compute_r6_ue_entry(&password, &u_entry, &original_key)
            .unwrap();

        let recovered_key = handler
            .recover_r6_encryption_key(&password, &u_entry, &ue_entry)
            .unwrap();

        assert_eq!(
            recovered_key.as_bytes(),
            original_key.as_bytes(),
            "R6: Recovered key must match original"
        );
    }

    // ===== Phase 3.2: R6 Perms Entry Tests =====

    #[test]
    fn test_r6_perms_entry_computation() {
        let handler = StandardSecurityHandler::aes_256_r6();
        let permissions = Permissions::all();
        let key = EncryptionKey::new(vec![0x42; 32]);

        let perms = handler
            .compute_r6_perms_entry(permissions, &key, true)
            .unwrap();

        assert_eq!(perms.len(), 16, "Perms entry must be 16 bytes");
    }

    #[test]
    fn test_r6_perms_validation() {
        let handler = StandardSecurityHandler::aes_256_r6();
        let permissions = Permissions::new();
        let key = EncryptionKey::new(vec![0x55; 32]);

        let perms = handler
            .compute_r6_perms_entry(permissions, &key, false)
            .unwrap();

        let is_valid = handler
            .validate_r6_perms(&perms, &key, permissions)
            .unwrap();
        assert!(is_valid, "Perms validation must succeed with correct key");
    }

    #[test]
    fn test_r6_perms_wrong_key_fails() {
        let handler = StandardSecurityHandler::aes_256_r6();
        let permissions = Permissions::all();
        let correct_key = EncryptionKey::new(vec![0xAA; 32]);
        let wrong_key = EncryptionKey::new(vec![0xBB; 32]);

        let perms = handler
            .compute_r6_perms_entry(permissions, &correct_key, true)
            .unwrap();

        // Validation with wrong key should fail (structure won't match)
        let result = handler.validate_r6_perms(&perms, &wrong_key, permissions);
        assert!(result.is_ok()); // No error
        assert!(!result.unwrap()); // But validation fails
    }

    #[test]
    fn test_r6_perms_encrypt_metadata_flag() {
        let handler = StandardSecurityHandler::aes_256_r6();
        let permissions = Permissions::new();
        let key = EncryptionKey::new(vec![0x33; 32]);

        let perms_true = handler
            .compute_r6_perms_entry(permissions, &key, true)
            .unwrap();
        let perms_false = handler
            .compute_r6_perms_entry(permissions, &key, false)
            .unwrap();

        // Different encrypt_metadata flag should produce different Perms
        assert_ne!(
            perms_true, perms_false,
            "Different EncryptMetadata must produce different Perms"
        );

        // Extract and verify flags
        let flag_true = handler
            .extract_r6_encrypt_metadata(&perms_true, &key)
            .unwrap();
        assert_eq!(flag_true, Some(true));

        let flag_false = handler
            .extract_r6_encrypt_metadata(&perms_false, &key)
            .unwrap();
        assert_eq!(flag_false, Some(false));
    }

    #[test]
    fn test_r6_perms_invalid_length() {
        let handler = StandardSecurityHandler::aes_256_r6();
        let key = EncryptionKey::new(vec![0x44; 32]);
        let permissions = Permissions::new();

        let invalid_perms = vec![0u8; 12]; // Too short
        let result = handler.validate_r6_perms(&invalid_perms, &key, permissions);
        assert!(result.is_err(), "Short Perms entry must fail");
    }

    #[test]
    fn test_r6_full_workflow_with_perms() {
        // Complete R6 integration test: U + UE + Perms
        let handler = StandardSecurityHandler::aes_256_r6();
        let password = UserPassword("r6_full_workflow".to_string());
        let permissions = Permissions::all();
        let encryption_key = EncryptionKey::new((0..32).map(|i| (i * 3) as u8).collect());

        // Step 1: Compute U entry (password verification)
        let u_entry = handler.compute_r6_user_hash(&password).unwrap();
        assert_eq!(u_entry.len(), 48);

        // Step 2: Validate password
        assert!(handler
            .validate_r6_user_password(&password, &u_entry)
            .unwrap());

        // Step 3: Compute UE entry (encrypted key)
        let ue_entry = handler
            .compute_r6_ue_entry(&password, &u_entry, &encryption_key)
            .unwrap();
        assert_eq!(ue_entry.len(), 32);

        // Step 4: Compute Perms entry (encrypted permissions)
        let perms = handler
            .compute_r6_perms_entry(permissions, &encryption_key, true)
            .unwrap();
        assert_eq!(perms.len(), 16);

        // Step 5: Recover encryption key from UE
        let recovered_key = handler
            .recover_r6_encryption_key(&password, &u_entry, &ue_entry)
            .unwrap();
        assert_eq!(
            recovered_key.as_bytes(),
            encryption_key.as_bytes(),
            "Recovered key must match original"
        );

        // Step 6: Validate Perms with recovered key
        let perms_valid = handler
            .validate_r6_perms(&perms, &recovered_key, permissions)
            .unwrap();
        assert!(perms_valid, "Perms must validate with recovered key");

        // Step 7: Extract EncryptMetadata flag
        let encrypt_meta = handler
            .extract_r6_encrypt_metadata(&perms, &recovered_key)
            .unwrap();
        assert_eq!(encrypt_meta, Some(true), "EncryptMetadata must be true");
    }

    // ===== AES-128 R4 Tests =====

    #[test]
    fn test_r4_aes_object_key_is_16_bytes() {
        let handler = StandardSecurityHandler::aes_128_r4();
        let key = EncryptionKey::new(vec![0xAB; 16]);
        let obj_id = ObjectId::new(7, 0);

        let obj_key = handler.compute_r4_aes_object_key(&key, &obj_id);
        assert_eq!(obj_key.len(), 16);
    }

    #[test]
    fn test_r4_aes_object_key_includes_salt() {
        // R4 AES key differs from RC4 key because of "sAlT" suffix
        let handler_r4 = StandardSecurityHandler::aes_128_r4();
        let handler_rc4 = StandardSecurityHandler::rc4_128bit();
        let key = EncryptionKey::new(vec![0xCD; 16]);
        let obj_id = ObjectId::new(3, 0);

        let aes_key = handler_r4.compute_r4_aes_object_key(&key, &obj_id);
        let rc4_key = handler_rc4.compute_object_key(&key, &obj_id);

        assert_ne!(
            aes_key, rc4_key,
            "AES R4 key must differ from RC4 key due to sAlT"
        );
    }

    #[test]
    fn test_r4_aes_object_key_deterministic() {
        let handler = StandardSecurityHandler::aes_128_r4();
        let key = EncryptionKey::new(vec![0x42; 16]);
        let obj_id = ObjectId::new(5, 2);

        let key1 = handler.compute_r4_aes_object_key(&key, &obj_id);
        let key2 = handler.compute_r4_aes_object_key(&key, &obj_id);
        assert_eq!(key1, key2);
    }

    #[test]
    fn test_r4_encrypt_decrypt_roundtrip() {
        let handler = StandardSecurityHandler::aes_128_r4();
        let key = EncryptionKey::new(vec![0x55; 16]);
        let obj_id = ObjectId::new(1, 0);
        let plaintext = b"Hello AES-128 R4 encryption!";

        let encrypted = handler.encrypt_aes(plaintext, &key, &obj_id).unwrap();
        assert_ne!(&encrypted[16..], plaintext.as_slice()); // ciphertext != plaintext
        assert!(encrypted.len() > 16); // IV + ciphertext

        let decrypted = handler.decrypt_aes(&encrypted, &key, &obj_id).unwrap();
        assert_eq!(decrypted, plaintext);
    }

    #[test]
    fn test_r4_encrypt_output_has_iv_prefix() {
        let handler = StandardSecurityHandler::aes_128_r4();
        let key = EncryptionKey::new(vec![0x77; 16]);
        let obj_id = ObjectId::new(2, 0);
        let data = b"test";

        let encrypted = handler.encrypt_aes(data, &key, &obj_id).unwrap();
        // Output = 16-byte IV + AES-CBC ciphertext (multiple of 16)
        assert!(encrypted.len() >= 32); // 16 IV + at least 16 ciphertext
        assert_eq!((encrypted.len() - 16) % 16, 0);
    }

    #[test]
    fn test_r4_decrypt_rejects_short_data() {
        let handler = StandardSecurityHandler::aes_128_r4();
        let key = EncryptionKey::new(vec![0x99; 16]);
        let obj_id = ObjectId::new(1, 0);

        let short = vec![0u8; 10];
        assert!(handler.decrypt_aes(&short, &key, &obj_id).is_err());
    }

    #[test]
    fn test_r4_inherent_encrypt_string_uses_aes() {
        // Verify that the inherent encrypt_string routes R4 through AES, not RC4
        let handler = StandardSecurityHandler::aes_128_r4();
        let key = EncryptionKey::new(vec![0x33; 16]);
        let obj_id = ObjectId::new(1, 0);
        let data = b"R4 string encryption";

        let encrypted = handler.encrypt_string(data, &key, &obj_id);
        // AES output = IV(16) + ciphertext(≥16), so always > input for small inputs
        assert!(encrypted.len() >= 32);

        // Decrypt via inherent method must also work
        let decrypted = handler.decrypt_string(&encrypted, &key, &obj_id);
        assert_eq!(decrypted, data);
    }

    #[test]
    fn test_r4_inherent_stream_uses_aes() {
        let handler = StandardSecurityHandler::aes_128_r4();
        let key = EncryptionKey::new(vec![0x44; 16]);
        let obj_id = ObjectId::new(3, 0);
        let data = b"R4 stream content";

        let encrypted = handler.encrypt_stream(data, &key, &obj_id);
        assert!(encrypted.len() >= 32);

        let decrypted = handler.decrypt_stream(&encrypted, &key, &obj_id);
        assert_eq!(decrypted, data);
    }
}