yubikit 1.0.0-beta.0

YubiKey management library
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
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
// Copyright 2026 Yubico AB
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! OpenPGP smart card application for YubiKeys.
//!
//! This module implements the OpenPGP card specification (ISO/IEC 7816) for
//! managing keys, PINs, certificates, and performing cryptographic operations
//! (signing, decryption, authentication) via the YubiKey's OpenPGP applet.
//!
//! The main entry point is [`OpenPgpSession`](crate::openpgp::OpenPgpSession),
//! which wraps a smart card connection and exposes high-level operations such
//! as key generation, key import, PIN management, and KDF configuration.
//!
//! # Example
//!
//! ```no_run
//! use yubikit::platform::device::list_devices;
//! use yubikit::management::UsbInterface;
//! use yubikit::openpgp::OpenPgpSession;
//!
//! let devices = list_devices(UsbInterface::CCID)?;
//! let dev = devices.first().expect("no YubiKey found");
//! let conn = dev.open_smartcard()?;
//! let mut session = OpenPgpSession::new(conn).map_err(|(e, _)| e)?;
//!
//! let app_data = session.get_application_related_data()?;
//! println!("AID: {:?}", app_data.aid);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::collections::HashMap;
use std::fmt;

use sha2::Digest;
use thiserror::Error;
use zeroize::Zeroizing;

use crate::__internal::padding::Hash;
use crate::__internal::tlv::{
    TlvError, parse_tlv_dict, parse_tlv_list, tlv_append, tlv_encode, tlv_unpack,
};
use crate::core::Version;
use crate::core::{bytes2int, int2bytes, patch_version};
use crate::keys::{
    EcCurve, EcPublicKey, Ed25519PublicKey, PrivateKey, PublicKey, RsaKeySize, RsaPublicKey,
    X25519PublicKey,
};
use crate::keys::{
    OID_BRAINPOOL_P256R1, OID_BRAINPOOL_P384R1, OID_BRAINPOOL_P512R1, OID_SECP256K1, OID_SECP256R1,
    OID_SECP384R1, OID_SECP521R1,
};
use crate::smartcard::{Aid, SmartCardConnection, SmartCardError, SmartCardProtocol, Sw};
use x509_cert::spki::ObjectIdentifier;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Default user PIN for a factory-reset OpenPGP applet (`"123456"`).
pub const DEFAULT_USER_PIN: &str = "123456";
/// Default admin PIN for a factory-reset OpenPGP applet (`"12345678"`).
pub const DEFAULT_ADMIN_PIN: &str = "12345678";

const INVALID_PIN: &[u8] = &[0; 8];

// INS bytes
const INS_VERIFY: u8 = 0x20;
const INS_CHANGE_PIN: u8 = 0x24;
const INS_RESET_RETRY_COUNTER: u8 = 0x2C;
const INS_PSO: u8 = 0x2A;
const INS_ACTIVATE: u8 = 0x44;
const INS_GENERATE_ASYM: u8 = 0x47;
const INS_GET_CHALLENGE: u8 = 0x84;
const INS_INTERNAL_AUTHENTICATE: u8 = 0x88;
const INS_SELECT_DATA: u8 = 0xA5;
const INS_GET_DATA: u8 = 0xCA;
const INS_PUT_DATA: u8 = 0xDA;
const INS_PUT_DATA_ODD: u8 = 0xDB;
const INS_TERMINATE: u8 = 0xE6;
const INS_GET_VERSION: u8 = 0xF1;
const INS_SET_PIN_RETRIES: u8 = 0xF2;
const INS_GET_ATTESTATION: u8 = 0xFB;

// TLV tags used in parsing
const TAG_DISCRETIONARY: u32 = 0x73;
const TAG_EXTENDED_CAPABILITIES: u32 = 0xC0;
const TAG_FINGERPRINTS: u32 = 0xC5;
const TAG_CA_FINGERPRINTS: u32 = 0xC6;
const TAG_GENERATION_TIMES: u32 = 0xCD;
const TAG_SIGNATURE_COUNTER: u32 = 0x93;
const TAG_KEY_INFORMATION: u32 = 0xDE;
const TAG_PUBLIC_KEY: u32 = 0x7F49;

const BUTTON_FLAG: u8 = 0x20;

// ---------------------------------------------------------------------------
// Error
// ---------------------------------------------------------------------------

/// Errors returned by OpenPGP session operations.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum OpenPgpError {
    /// The requested feature is not supported by this YubiKey firmware version.
    #[error("Not supported: {0}")]
    NotSupported(String),
    /// The data provided or received was malformed or out of range.
    #[error("Invalid data: {0}")]
    InvalidData(String),
    /// PIN verification failed; the inner value is the number of remaining attempts.
    #[error("Invalid PIN, {0} attempts remaining")]
    InvalidPin(u32),
    /// The PIN has been blocked after too many failed attempts.
    #[error("PIN blocked")]
    PinBlocked,
    /// An underlying smart card transport error occurred.
    #[error("Connection error: {0}")]
    Connection(SmartCardError),
}

impl From<SmartCardError> for OpenPgpError {
    fn from(e: SmartCardError) -> Self {
        match e {
            SmartCardError::NotSupported(msg) => OpenPgpError::NotSupported(msg),
            SmartCardError::InvalidData(msg) => OpenPgpError::InvalidData(msg),
            other => OpenPgpError::Connection(other),
        }
    }
}

impl From<TlvError> for OpenPgpError {
    fn from(e: TlvError) -> Self {
        OpenPgpError::InvalidData(e.to_string())
    }
}

// ---------------------------------------------------------------------------
// Enums
// ---------------------------------------------------------------------------

/// User Interaction Flag (UIF) setting for a key slot.
///
/// Controls whether the YubiKey requires a physical touch for operations
/// using the associated key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u8)]
pub enum Uif {
    /// Touch is not required.
    Off = 0x00,
    /// Touch is required for each operation.
    On = 0x01,
    /// Touch is permanently required and cannot be changed.
    Fixed = 0x02,
    /// Touch is required but cached for a short period after use.
    Cached = 0x03,
    /// Touch is permanently required with caching; cannot be changed.
    CachedFixed = 0x04,
}

impl Uif {
    /// Convert a raw byte value to a [`Uif`] variant, if valid.
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0x00 => Some(Self::Off),
            0x01 => Some(Self::On),
            0x02 => Some(Self::Fixed),
            0x03 => Some(Self::Cached),
            0x04 => Some(Self::CachedFixed),
            _ => None,
        }
    }

    /// Parse a UIF value from its encoded byte representation.
    pub fn parse(encoded: &[u8]) -> Option<Self> {
        encoded.first().and_then(|&v| Self::from_u8(v))
    }

    /// Returns `true` if this UIF setting is permanent and cannot be changed.
    pub fn is_fixed(self) -> bool {
        matches!(self, Uif::Fixed | Uif::CachedFixed)
    }

    /// Returns `true` if touch confirmation is cached for a short period.
    pub fn is_cached(self) -> bool {
        matches!(self, Uif::Cached | Uif::CachedFixed)
    }

    /// Encode this UIF value as a two-byte array (value byte + button flag).
    pub fn to_bytes(self) -> [u8; 2] {
        [self as u8, BUTTON_FLAG]
    }
}

/// PIN verification policy for the user (signature) PIN.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u8)]
pub enum PinPolicy {
    /// PIN must be verified before every signature operation.
    Always = 0x00,
    /// PIN verification is valid for the entire session after first use.
    Once = 0x01,
}

impl PinPolicy {
    /// Convert a byte value to a [`PinPolicy`], defaulting to [`PinPolicy::Always`].
    pub fn from_u8(v: u8) -> Self {
        match v {
            0x01 => Self::Once,
            _ => Self::Always,
        }
    }
}

/// Password reference identifying which PIN to operate on.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Pw {
    /// User PIN (PW1), used for signing and decryption.
    User = 0x81,
    /// Reset code, used to unblock the user PIN.
    Reset = 0x82,
    /// Admin PIN (PW3), used for card administration.
    Admin = 0x83,
}

/// OpenPGP Data Object (DO) tags used for reading and writing card data.
///
/// Each variant's discriminant encodes the P1/P2 bytes of the GET DATA /
/// PUT DATA APDU commands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u16)]
pub enum Do {
    /// Private use data object 1 (read/write with user PIN).
    PrivateUse1 = 0x0101,
    /// Private use data object 2 (read/write with user PIN).
    PrivateUse2 = 0x0102,
    /// Private use data object 3 (read/write with admin PIN).
    PrivateUse3 = 0x0103,
    /// Private use data object 4 (read/write with admin PIN).
    PrivateUse4 = 0x0104,
    /// Application identifier (AID).
    Aid = 0x4F,
    /// Cardholder name.
    Name = 0x5B,
    /// Login data (e.g. a username).
    LoginData = 0x5E,
    /// Preferred language(s) of the cardholder.
    Language = 0xEF2D,
    /// Sex of the cardholder.
    Sex = 0x5F35,
    /// URL (e.g. for public key retrieval).
    Url = 0x5F50,
    /// Historical bytes from the ATR.
    HistoricalBytes = 0x5F52,
    /// Extended length information.
    ExtendedLengthInfo = 0x7F66,
    /// General feature management DO.
    GeneralFeatureManagement = 0x7F74,
    /// Cardholder related data (composite DO).
    CardholderRelatedData = 0x65,
    /// Application related data (composite DO).
    ApplicationRelatedData = 0x6E,
    /// Algorithm attributes for the signature key slot.
    AlgorithmAttributesSig = 0xC1,
    /// Algorithm attributes for the decryption key slot.
    AlgorithmAttributesDec = 0xC2,
    /// Algorithm attributes for the authentication key slot.
    AlgorithmAttributesAut = 0xC3,
    /// Algorithm attributes for the attestation key slot.
    AlgorithmAttributesAtt = 0xDA,
    /// PW status bytes (PIN lengths, retry counters, policy).
    PwStatusBytes = 0xC4,
    /// Fingerprint of the signature key.
    FingerprintSig = 0xC7,
    /// Fingerprint of the decryption key.
    FingerprintDec = 0xC8,
    /// Fingerprint of the authentication key.
    FingerprintAut = 0xC9,
    /// Fingerprint of the attestation key.
    FingerprintAtt = 0xDB,
    /// CA fingerprint 1 (associated with signature key).
    CaFingerprint1 = 0xCA,
    /// CA fingerprint 2 (associated with decryption key).
    CaFingerprint2 = 0xCB,
    /// CA fingerprint 3 (associated with authentication key).
    CaFingerprint3 = 0xCC,
    /// CA fingerprint 4 (associated with attestation key).
    CaFingerprint4 = 0xDC,
    /// Generation timestamp for the signature key.
    GenerationTimeSig = 0xCE,
    /// Generation timestamp for the decryption key.
    GenerationTimeDec = 0xCF,
    /// Generation timestamp for the authentication key.
    GenerationTimeAut = 0xD0,
    /// Generation timestamp for the attestation key.
    GenerationTimeAtt = 0xDD,
    /// Resetting code for unblocking the user PIN.
    ResettingCode = 0xD3,
    /// User Interaction Flag for the signature key.
    UifSig = 0xD6,
    /// User Interaction Flag for the decryption key.
    UifDec = 0xD7,
    /// User Interaction Flag for the authentication key.
    UifAut = 0xD8,
    /// User Interaction Flag for the attestation key.
    UifAtt = 0xD9,
    /// Security support template (contains the signature counter).
    SecuritySupportTemplate = 0x7A,
    /// Cardholder certificate.
    CardholderCertificate = 0x7F21,
    /// Key Derivation Function (KDF) data object.
    Kdf = 0xF9,
    /// Algorithm information (list of supported algorithms per slot).
    AlgorithmInformation = 0xFA,
    /// Attestation certificate.
    AttCertificate = 0xFC,
    /// Key information (generation status of each key slot).
    KeyInformation = 0xDE,
}

impl Do {
    /// Returns the P1 byte (high byte of the DO tag) for APDU commands.
    pub fn p1(self) -> u8 {
        ((self as u16) >> 8) as u8
    }

    /// Returns the P2 byte (low byte of the DO tag) for APDU commands.
    pub fn p2(self) -> u8 {
        (self as u16) as u8
    }
}

/// Reference to one of the four OpenPGP key slots on the card.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum KeyRef {
    /// Signature key slot.
    Sig = 0x01,
    /// Decryption key slot.
    Dec = 0x02,
    /// Authentication key slot.
    Aut = 0x03,
    /// Attestation key slot (YubiKey 5.2+).
    Att = 0x81,
}

impl KeyRef {
    /// Convert a raw byte value to a [`KeyRef`], if valid.
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0x01 => Some(Self::Sig),
            0x02 => Some(Self::Dec),
            0x03 => Some(Self::Aut),
            0x81 => Some(Self::Att),
            _ => None,
        }
    }

    /// All four key slot references.
    pub const ALL: &[KeyRef] = &[KeyRef::Sig, KeyRef::Dec, KeyRef::Aut, KeyRef::Att];

    /// Returns the algorithm attributes [`Do`] tag for this key slot.
    pub fn algorithm_attributes_do(self) -> Do {
        match self {
            Self::Sig => Do::AlgorithmAttributesSig,
            Self::Dec => Do::AlgorithmAttributesDec,
            Self::Aut => Do::AlgorithmAttributesAut,
            Self::Att => Do::AlgorithmAttributesAtt,
        }
    }

    /// Returns the UIF (touch policy) [`Do`] tag for this key slot.
    pub fn uif_do(self) -> Do {
        match self {
            Self::Sig => Do::UifSig,
            Self::Dec => Do::UifDec,
            Self::Aut => Do::UifAut,
            Self::Att => Do::UifAtt,
        }
    }

    /// Returns the generation time [`Do`] tag for this key slot.
    pub fn generation_time_do(self) -> Do {
        match self {
            Self::Sig => Do::GenerationTimeSig,
            Self::Dec => Do::GenerationTimeDec,
            Self::Aut => Do::GenerationTimeAut,
            Self::Att => Do::GenerationTimeAtt,
        }
    }

    /// Returns the fingerprint [`Do`] tag for this key slot.
    pub fn fingerprint_do(self) -> Do {
        match self {
            Self::Sig => Do::FingerprintSig,
            Self::Dec => Do::FingerprintDec,
            Self::Aut => Do::FingerprintAut,
            Self::Att => Do::FingerprintAtt,
        }
    }

    /// Control Reference Template bytes for this key slot.
    pub fn crt(self) -> Vec<u8> {
        match self {
            Self::Sig => tlv_encode(0xB6, &[]),
            Self::Dec => tlv_encode(0xB8, &[]),
            Self::Aut => tlv_encode(0xA4, &[]),
            Self::Att => {
                let inner = tlv_encode(0x84, &[0x81]);
                tlv_encode(0xB6, &inner)
            }
        }
    }
}

/// Status of a key slot (whether a key has been generated, imported, or is absent).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum KeyStatus {
    /// No key is present in this slot.
    None = 0,
    /// A key was generated on-card.
    Generated = 1,
    /// A key was imported from an external source.
    Imported = 2,
}

impl KeyStatus {
    /// Convert a raw byte value to a [`KeyStatus`], if valid.
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0 => Some(Self::None),
            1 => Some(Self::Generated),
            2 => Some(Self::Imported),
            _ => Option::None,
        }
    }
}

/// RSA private key import format as indicated in the algorithm attributes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum RsaImportFormat {
    /// Standard format: (e, p, q).
    Standard = 0,
    /// Standard format with modulus: (e, p, q, n).
    StandardWMod = 1,
    /// CRT (Chinese Remainder Theorem) format: (e, p, q, iqmp, dmp1, dmq1).
    Crt = 2,
    /// CRT format with modulus: (e, p, q, iqmp, dmp1, dmq1, n).
    CrtWMod = 3,
}

impl RsaImportFormat {
    /// Convert a raw byte value to an [`RsaImportFormat`], if valid.
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0 => Some(Self::Standard),
            1 => Some(Self::StandardWMod),
            2 => Some(Self::Crt),
            3 => Some(Self::CrtWMod),
            _ => None,
        }
    }
}

/// Elliptic curve private key import format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum EcImportFormat {
    /// Standard format: private scalar only.
    Standard = 0,
    /// Standard format with public key included.
    StandardWPubkey = 0xFF,
}

impl EcImportFormat {
    /// Convert a raw byte value to an [`EcImportFormat`], if valid.
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0x00 => Some(Self::Standard),
            0xFF => Some(Self::StandardWPubkey),
            _ => None,
        }
    }
}

/// Hash algorithm identifier used in KDF (Key Derivation Function) configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
#[non_exhaustive]
pub enum HashAlgorithm {
    /// SHA-256 (OpenPGP hash algorithm ID `0x08`).
    Sha256 = 0x08,
    /// SHA-512 (OpenPGP hash algorithm ID `0x0A`).
    Sha512 = 0x0A,
}

impl HashAlgorithm {
    /// Convert a raw byte value to a [`HashAlgorithm`], if valid.
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0x08 => Some(Self::Sha256),
            0x0A => Some(Self::Sha512),
            _ => None,
        }
    }
}

/// Extended capability flags (bitfield).
pub mod extended_capability_flags {
    /// Device supports Key Derivation Function (KDF) for PIN hashing.
    pub const KDF: u8 = 1 << 0;
    /// Device supports PSO:DEC/ENC with AES.
    pub const PSO_DEC_ENC_AES: u8 = 1 << 1;
    /// Algorithm attributes of key slots can be changed.
    pub const ALGORITHM_ATTRIBUTES_CHANGEABLE: u8 = 1 << 2;
    /// Private use data objects are supported.
    pub const PRIVATE_USE: u8 = 1 << 3;
    /// PW status bytes (PIN policy) can be changed.
    pub const PW_STATUS_CHANGEABLE: u8 = 1 << 4;
    /// Private key import is supported.
    pub const KEY_IMPORT: u8 = 1 << 5;
    /// GET CHALLENGE command is supported.
    pub const GET_CHALLENGE: u8 = 1 << 6;
    /// Secure messaging is supported.
    pub const SECURE_MESSAGING: u8 = 1 << 7;
}

/// Curve25519 for ECDH (X25519) — OpenPGP card OID.
const OID_X25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.4.1.3029.1.5.1");
/// Curve25519 for EdDSA signatures (Ed25519) — OpenPGP card OID.
const OID_ED25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.4.1.11591.15.1");

// EC algorithm IDs
const EC_ALG_ECDH: u8 = 0x12;
const EC_ALG_ECDSA: u8 = 0x13;
const EC_ALG_EDDSA: u8 = 0x16;

// RSA algorithm ID
const RSA_ALG_ID: u8 = 0x01;

// ---------------------------------------------------------------------------
// Secret value types
// ---------------------------------------------------------------------------

/// An OpenPGP PIN, admin PIN, or reset code.
///
/// OpenPGP PINs are UTF-8 strings. Length validation is deferred to the session
/// methods since limits depend on the card's configuration. The value is
/// automatically zeroized when dropped.
///
/// # Examples
///
/// ```
/// use yubikit::openpgp::OpenPgpPin;
///
/// let pin = OpenPgpPin::new("123456");
/// ```
#[derive(Clone)]
pub struct OpenPgpPin(crate::__internal::SecretValue<Vec<u8>>);

impl OpenPgpPin {
    /// Create a new OpenPGP PIN from a string value.
    pub fn new(pin: &str) -> Self {
        Self(crate::__internal::SecretValue::new(pin.as_bytes().to_vec()))
    }

    /// Access the raw PIN bytes (internal use only).
    #[allow(dead_code)]
    pub(crate) fn as_bytes(&self) -> &[u8] {
        self.0.expose_secret()
    }

    /// Access the PIN as a UTF-8 string (for KDF processing).
    pub(crate) fn as_str(&self) -> &str {
        // Safety: we only construct from &str in new()
        std::str::from_utf8(self.0.expose_secret()).expect("OpenPgpPin is always valid UTF-8")
    }
}

impl fmt::Debug for OpenPgpPin {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("OpenPgpPin([REDACTED])")
    }
}

// ---------------------------------------------------------------------------
// Data types
// ---------------------------------------------------------------------------

/// Algorithm attributes for an OpenPGP key slot (RSA or elliptic curve).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum AlgorithmAttributes {
    /// RSA algorithm attributes.
    Rsa(RsaAttributes),
    /// Elliptic curve algorithm attributes.
    Ec(EcAttributes),
}

impl AlgorithmAttributes {
    /// Parse algorithm attributes from their TLV-encoded representation.
    pub fn parse(encoded: &[u8]) -> Result<Self, OpenPgpError> {
        if encoded.is_empty() {
            return Err(OpenPgpError::InvalidData(
                "Empty algorithm attributes".into(),
            ));
        }
        let algorithm_id = encoded[0];
        match algorithm_id {
            RSA_ALG_ID => Ok(Self::Rsa(RsaAttributes::parse_data(&encoded[1..])?)),
            EC_ALG_ECDH | EC_ALG_ECDSA | EC_ALG_EDDSA => Ok(Self::Ec(EcAttributes::parse_data(
                algorithm_id,
                &encoded[1..],
            )?)),
            _ => Err(OpenPgpError::InvalidData(format!(
                "Unsupported algorithm ID: 0x{algorithm_id:02X}"
            ))),
        }
    }

    /// Serialize these algorithm attributes to bytes for storage on the card.
    pub fn to_bytes(&self) -> Vec<u8> {
        match self {
            Self::Rsa(a) => a.to_bytes(),
            Self::Ec(a) => a.to_bytes(),
        }
    }

    /// Returns the algorithm identifier byte (RSA = 0x01, EC varies).
    /// Returns the OpenPGP algorithm identifier byte.
    pub fn algorithm_id(&self) -> u8 {
        match self {
            Self::Rsa(_) => RSA_ALG_ID,
            Self::Ec(a) => a.algorithm_id,
        }
    }
}

/// RSA algorithm attributes stored on the card.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RsaAttributes {
    /// Length of the RSA modulus (n) in bits.
    pub n_len: u16,
    /// Length of the public exponent (e) in bits.
    pub e_len: u16,
    /// Private key import format.
    pub import_format: RsaImportFormat,
}

impl RsaAttributes {
    /// Create RSA attributes with the given key size and import format.
    /// Creates RSA attributes with the given key size and import format.
    pub fn create(n_len: RsaKeySize, import_format: RsaImportFormat) -> Self {
        Self {
            n_len: n_len as u16,
            e_len: 17,
            import_format,
        }
    }

    fn parse_data(data: &[u8]) -> Result<Self, OpenPgpError> {
        if data.len() < 5 {
            return Err(OpenPgpError::InvalidData("RSA attributes too short".into()));
        }
        let n_len = u16::from_be_bytes([data[0], data[1]]);
        let e_len = u16::from_be_bytes([data[2], data[3]]);
        let import_format = RsaImportFormat::from_u8(data[4]).ok_or_else(|| {
            OpenPgpError::InvalidData(format!("Unknown RSA import format: {}", data[4]))
        })?;
        Ok(Self {
            n_len,
            e_len,
            import_format,
        })
    }

    fn to_bytes(&self) -> Vec<u8> {
        let mut buf = vec![RSA_ALG_ID];
        buf.extend_from_slice(&self.n_len.to_be_bytes());
        buf.extend_from_slice(&self.e_len.to_be_bytes());
        buf.push(self.import_format as u8);
        buf
    }
}

/// Elliptic curve OIDs supported by the OpenPGP card.
#[non_exhaustive]
pub enum OpenPgpCurve {
    /// NIST P-256 (secp256r1).
    P256,
    /// NIST P-384 (secp384r1).
    P384,
    /// NIST P-521 (secp521r1).
    P521,
    /// secp256k1.
    Secp256k1,
    /// Brainpool P-256r1.
    BrainpoolP256r1,
    /// Brainpool P-384r1.
    BrainpoolP384r1,
    /// Brainpool P-512r1.
    BrainpoolP512r1,
    /// Curve25519 for EdDSA signatures (Ed25519).
    Ed25519,
    /// Curve25519 for ECDH (X25519).
    X25519,
}

impl OpenPgpCurve {
    /// Returns the OID for this curve as a byte vector.
    fn oid(&self) -> ObjectIdentifier {
        match self {
            Self::P256 => OID_SECP256R1,
            Self::P384 => OID_SECP384R1,
            Self::P521 => OID_SECP521R1,
            Self::Secp256k1 => OID_SECP256K1,
            Self::BrainpoolP256r1 => OID_BRAINPOOL_P256R1,
            Self::BrainpoolP384r1 => OID_BRAINPOOL_P384R1,
            Self::BrainpoolP512r1 => OID_BRAINPOOL_P512R1,
            Self::Ed25519 => OID_ED25519,
            Self::X25519 => OID_X25519,
        }
    }

    /// Convert an OID string to an `OpenPgpCurve`, if it matches a supported curve.
    pub fn from_oid(oid_str: &str) -> Result<Self, OpenPgpError> {
        let oid = ObjectIdentifier::new(oid_str)
            .map_err(|_| OpenPgpError::InvalidData(format!("Invalid OID string: {}", oid_str)))?;
        match oid {
            OID_SECP256R1 => Ok(Self::P256),
            OID_SECP384R1 => Ok(Self::P384),
            OID_SECP521R1 => Ok(Self::P521),
            OID_SECP256K1 => Ok(Self::Secp256k1),
            OID_BRAINPOOL_P256R1 => Ok(Self::BrainpoolP256r1),
            OID_BRAINPOOL_P384R1 => Ok(Self::BrainpoolP384r1),
            OID_BRAINPOOL_P512R1 => Ok(Self::BrainpoolP512r1),
            OID_ED25519 => Ok(Self::Ed25519),
            OID_X25519 => Ok(Self::X25519),
            _ => Err(OpenPgpError::InvalidData(format!(
                "Unsupported OID: {}",
                oid_str
            ))),
        }
    }
}

/// Elliptic curve algorithm attributes stored on the OpenPGP card.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EcAttributes {
    /// EC algorithm identifier (ECDH, ECDSA, or EdDSA).
    pub algorithm_id: u8,
    /// DER-encoded curve OID bytes.
    pub oid: Vec<u8>,
    /// Private key import format.
    pub import_format: EcImportFormat,
}

impl EcAttributes {
    /// Create EC attributes for the given key slot and curve OID string.
    ///
    /// The algorithm ID is inferred automatically: EdDSA for Ed25519,
    /// ECDH for the decryption slot, and ECDSA otherwise.
    pub fn create(key_ref: KeyRef, curve: &OpenPgpCurve) -> Result<Self, OpenPgpError> {
        let oid = curve.oid();
        let algorithm_id = if oid == OID_ED25519 {
            EC_ALG_EDDSA
        } else if key_ref == KeyRef::Dec {
            EC_ALG_ECDH
        } else {
            EC_ALG_ECDSA
        };
        Ok(Self {
            algorithm_id,
            oid: oid.as_bytes().to_vec(),
            import_format: EcImportFormat::Standard,
        })
    }

    fn parse_data(algorithm_id: u8, data: &[u8]) -> Result<Self, OpenPgpError> {
        if data.is_empty() {
            return Err(OpenPgpError::InvalidData("EC attributes too short".into()));
        }
        let (oid, import_format) = if *data.last().unwrap() == 0xFF {
            (&data[..data.len() - 1], EcImportFormat::StandardWPubkey)
        } else {
            (data, EcImportFormat::Standard)
        };
        Ok(Self {
            algorithm_id,
            oid: oid.to_vec(),
            import_format,
        })
    }

    fn to_bytes(&self) -> Vec<u8> {
        let mut buf = vec![self.algorithm_id];
        buf.extend_from_slice(&self.oid);
        if self.import_format == EcImportFormat::StandardWPubkey {
            buf.push(0xFF);
        }
        buf
    }

    /// Returns the curve OID as a dotted-decimal string.
    pub fn oid_str(&self) -> Result<String, OpenPgpError> {
        ObjectIdentifier::from_bytes(&self.oid)
            .map(|o| o.to_string())
            .map_err(|e| OpenPgpError::InvalidData(format!("Invalid curve OID: {e}")))
    }

    fn oid(&self) -> Result<ObjectIdentifier, OpenPgpError> {
        ObjectIdentifier::from_bytes(&self.oid)
            .map_err(|e| OpenPgpError::InvalidData(format!("Invalid curve OID: {e}")))
    }
}

// ---------------------------------------------------------------------------
// Parsed data objects
// ---------------------------------------------------------------------------

fn bcd(value: u8) -> u8 {
    10 * (value >> 4) + (value & 0x0F)
}

/// Parsed OpenPGP Application Identifier.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenPgpAid {
    /// Raw AID bytes as returned by the card.
    pub raw: Vec<u8>,
}

impl OpenPgpAid {
    /// Parse an AID from raw bytes.
    pub fn parse(data: &[u8]) -> Self {
        Self { raw: data.to_vec() }
    }

    /// Returns the OpenPGP specification version as `(major, minor)`.
    pub fn version(&self) -> (u8, u8) {
        (
            bcd(*self.raw.get(6).unwrap_or(&0)),
            bcd(*self.raw.get(7).unwrap_or(&0)),
        )
    }

    /// Returns the manufacturer ID from the AID.
    pub fn manufacturer(&self) -> u16 {
        if self.raw.len() >= 10 {
            u16::from_be_bytes([self.raw[8], self.raw[9]])
        } else {
            0
        }
    }

    /// Returns the card serial number decoded from BCD.
    pub fn serial(&self) -> i64 {
        if self.raw.len() >= 14 {
            let bytes = &self.raw[10..14];
            // Try BCD decode
            let hex_str = format!(
                "{:02X}{:02X}{:02X}{:02X}",
                bytes[0], bytes[1], bytes[2], bytes[3]
            );
            if let Ok(val) = hex_str.parse::<i64>() {
                val
            } else {
                // Not valid BCD: return unsigned int negated
                -(u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as i64)
            }
        } else {
            0
        }
    }
}

/// PIN/password status bytes describing lengths, retry counters, and policy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PwStatus {
    /// User PIN verification policy (once per session vs. every operation).
    pub pin_policy_user: PinPolicy,
    /// Maximum allowed length for the user PIN.
    pub max_len_user: u8,
    /// Maximum allowed length for the reset code.
    pub max_len_reset: u8,
    /// Maximum allowed length for the admin PIN.
    pub max_len_admin: u8,
    /// Remaining verification attempts for the user PIN.
    pub attempts_user: u8,
    /// Remaining verification attempts for the reset code.
    pub attempts_reset: u8,
    /// Remaining verification attempts for the admin PIN.
    pub attempts_admin: u8,
}

impl PwStatus {
    /// Parse PW status bytes from the card's encoded response (at least 7 bytes).
    pub fn parse(encoded: &[u8]) -> Result<Self, OpenPgpError> {
        if encoded.len() < 7 {
            return Err(OpenPgpError::InvalidData("PwStatus too short".into()));
        }
        Ok(Self {
            pin_policy_user: PinPolicy::from_u8(encoded[0]),
            max_len_user: encoded[1],
            max_len_reset: encoded[2],
            max_len_admin: encoded[3],
            attempts_user: encoded[4],
            attempts_reset: encoded[5],
            attempts_admin: encoded[6],
        })
    }

    /// Returns the maximum PIN length for the given password reference.
    pub fn get_max_len(&self, pw: Pw) -> u8 {
        match pw {
            Pw::User => self.max_len_user,
            Pw::Reset => self.max_len_reset,
            Pw::Admin => self.max_len_admin,
        }
    }

    /// Returns the remaining verification attempts for the given password reference.
    pub fn get_attempts(&self, pw: Pw) -> u8 {
        match pw {
            Pw::User => self.attempts_user,
            Pw::Reset => self.attempts_reset,
            Pw::Admin => self.attempts_admin,
        }
    }
}

/// Extended capabilities of the OpenPGP card, describing supported features and limits.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtendedCapabilities {
    /// Bitfield of capability flags (see [`extended_capability_flags`]).
    pub flags: u8,
    /// Secure messaging algorithm identifier.
    pub sm_algorithm: u8,
    /// Maximum number of bytes that GET CHALLENGE can return.
    pub challenge_max_length: u16,
    /// Maximum certificate storage size in bytes.
    pub certificate_max_length: u16,
    /// Maximum size of special data objects in bytes.
    pub special_do_max_length: u16,
    /// Whether PIN block 2 format is supported.
    pub pin_block_2_format: bool,
    /// Whether the MSE (Manage Security Environment) command is supported.
    pub mse_command: bool,
}

impl ExtendedCapabilities {
    /// Parse extended capabilities from the card's encoded response (at least 10 bytes).
    pub fn parse(encoded: &[u8]) -> Result<Self, OpenPgpError> {
        if encoded.len() < 10 {
            return Err(OpenPgpError::InvalidData(
                "ExtendedCapabilities too short".into(),
            ));
        }
        Ok(Self {
            flags: encoded[0],
            sm_algorithm: encoded[1],
            challenge_max_length: u16::from_be_bytes([encoded[2], encoded[3]]),
            certificate_max_length: u16::from_be_bytes([encoded[4], encoded[5]]),
            special_do_max_length: u16::from_be_bytes([encoded[6], encoded[7]]),
            pin_block_2_format: encoded[8] == 1,
            mse_command: encoded[9] == 1,
        })
    }

    /// Check whether a specific capability flag is set.
    pub fn has_flag(&self, flag: u8) -> bool {
        self.flags & flag != 0
    }
}

/// Map of key slot references to their 20-byte SHA-1 fingerprints.
pub type Fingerprints = HashMap<KeyRef, Vec<u8>>;
/// Map of key slot references to their generation timestamps (Unix epoch seconds).
pub type GenerationTimes = HashMap<KeyRef, u32>;
/// Map of key slot references to their key status (none, generated, or imported).
pub type KeyInformation = HashMap<KeyRef, KeyStatus>;

fn parse_fingerprints(encoded: &[u8]) -> Fingerprints {
    let mut map = HashMap::new();
    for (i, key) in KeyRef::ALL.iter().enumerate() {
        let start = i * 20;
        if start + 20 <= encoded.len() {
            map.insert(*key, encoded[start..start + 20].to_vec());
        }
    }
    map
}

fn parse_timestamps(encoded: &[u8]) -> GenerationTimes {
    let mut map = HashMap::new();
    for (i, key) in KeyRef::ALL.iter().enumerate() {
        let start = i * 4;
        if start + 4 <= encoded.len() {
            let ts = u32::from_be_bytes([
                encoded[start],
                encoded[start + 1],
                encoded[start + 2],
                encoded[start + 3],
            ]);
            map.insert(*key, ts);
        }
    }
    map
}

fn parse_key_information(encoded: &[u8]) -> KeyInformation {
    let mut map = HashMap::new();
    let mut i = 0;
    while i + 1 < encoded.len() {
        if let (Some(key), Some(status)) = (
            KeyRef::from_u8(encoded[i]),
            KeyStatus::from_u8(encoded[i + 1]),
        ) {
            map.insert(key, status);
        }
        i += 2;
    }
    map
}

// ---------------------------------------------------------------------------
// Discretionary and ApplicationRelatedData
// ---------------------------------------------------------------------------

/// Parsed discretionary data objects from the application related data DO.
///
/// Contains the algorithm attributes, PIN status, key fingerprints,
/// generation timestamps, key status, and UIF settings for all key slots.
#[derive(Debug, Clone)]
pub struct DiscretionaryDataObjects {
    /// Extended capabilities of the card.
    pub extended_capabilities: ExtendedCapabilities,
    /// Algorithm attributes for the signature key slot.
    pub attributes_sig: AlgorithmAttributes,
    /// Algorithm attributes for the decryption key slot.
    pub attributes_dec: AlgorithmAttributes,
    /// Algorithm attributes for the authentication key slot.
    pub attributes_aut: AlgorithmAttributes,
    /// Algorithm attributes for the attestation key slot (if supported).
    pub attributes_att: Option<AlgorithmAttributes>,
    /// Current PIN/password status bytes.
    pub pw_status: PwStatus,
    /// SHA-1 fingerprints for each key slot.
    pub fingerprints: Fingerprints,
    /// CA fingerprints for each key slot.
    pub ca_fingerprints: Fingerprints,
    /// Key generation timestamps for each key slot.
    pub generation_times: GenerationTimes,
    /// Key status (none/generated/imported) for each key slot.
    pub key_information: KeyInformation,
    /// User Interaction Flag for the signature key.
    pub uif_sig: Option<Uif>,
    /// User Interaction Flag for the decryption key.
    pub uif_dec: Option<Uif>,
    /// User Interaction Flag for the authentication key.
    pub uif_aut: Option<Uif>,
    /// User Interaction Flag for the attestation key.
    pub uif_att: Option<Uif>,
}

impl DiscretionaryDataObjects {
    /// Parse discretionary data objects from TLV-encoded bytes.
    pub fn parse(encoded: &[u8]) -> Result<Self, OpenPgpError> {
        let data = parse_tlv_dict(encoded)?;
        Ok(Self {
            extended_capabilities: ExtendedCapabilities::parse(
                data.get(&TAG_EXTENDED_CAPABILITIES).ok_or_else(|| {
                    OpenPgpError::InvalidData("Missing extended capabilities".into())
                })?,
            )?,
            attributes_sig: AlgorithmAttributes::parse(
                data.get(&(Do::AlgorithmAttributesSig as u32))
                    .ok_or_else(|| {
                        OpenPgpError::InvalidData("Missing SIG algorithm attributes".into())
                    })?,
            )?,
            attributes_dec: AlgorithmAttributes::parse(
                data.get(&(Do::AlgorithmAttributesDec as u32))
                    .ok_or_else(|| {
                        OpenPgpError::InvalidData("Missing DEC algorithm attributes".into())
                    })?,
            )?,
            attributes_aut: AlgorithmAttributes::parse(
                data.get(&(Do::AlgorithmAttributesAut as u32))
                    .ok_or_else(|| {
                        OpenPgpError::InvalidData("Missing AUT algorithm attributes".into())
                    })?,
            )?,
            attributes_att: data
                .get(&(Do::AlgorithmAttributesAtt as u32))
                .map(|v| AlgorithmAttributes::parse(v))
                .transpose()?,
            pw_status: PwStatus::parse(
                data.get(&(Do::PwStatusBytes as u32))
                    .ok_or_else(|| OpenPgpError::InvalidData("Missing PW status bytes".into()))?,
            )?,
            fingerprints: parse_fingerprints(
                data.get(&TAG_FINGERPRINTS)
                    .map(|v| v.as_slice())
                    .unwrap_or(&[]),
            ),
            ca_fingerprints: parse_fingerprints(
                data.get(&TAG_CA_FINGERPRINTS)
                    .map(|v| v.as_slice())
                    .unwrap_or(&[]),
            ),
            generation_times: parse_timestamps(
                data.get(&TAG_GENERATION_TIMES)
                    .map(|v| v.as_slice())
                    .unwrap_or(&[]),
            ),
            key_information: parse_key_information(
                data.get(&TAG_KEY_INFORMATION)
                    .map(|v| v.as_slice())
                    .unwrap_or(&[]),
            ),
            uif_sig: data.get(&(Do::UifSig as u32)).and_then(|v| Uif::parse(v)),
            uif_dec: data.get(&(Do::UifDec as u32)).and_then(|v| Uif::parse(v)),
            uif_aut: data.get(&(Do::UifAut as u32)).and_then(|v| Uif::parse(v)),
            uif_att: data.get(&(Do::UifAtt as u32)).and_then(|v| Uif::parse(v)),
        })
    }

    /// Returns the algorithm attributes for the given key slot, if present.
    pub fn get_algorithm_attributes(&self, key_ref: KeyRef) -> Option<&AlgorithmAttributes> {
        match key_ref {
            KeyRef::Sig => Some(&self.attributes_sig),
            KeyRef::Dec => Some(&self.attributes_dec),
            KeyRef::Aut => Some(&self.attributes_aut),
            KeyRef::Att => self.attributes_att.as_ref(),
        }
    }

    /// Returns the UIF (touch policy) for the given key slot, if set.
    pub fn get_uif(&self, key_ref: KeyRef) -> Option<Uif> {
        match key_ref {
            KeyRef::Sig => self.uif_sig,
            KeyRef::Dec => self.uif_dec,
            KeyRef::Aut => self.uif_aut,
            KeyRef::Att => self.uif_att,
        }
    }
}

/// Parsed application related data (DO `0x6E`), the top-level composite
/// data object returned by the OpenPGP applet.
#[derive(Debug, Clone)]
pub struct ApplicationRelatedData {
    /// The application identifier.
    pub aid: OpenPgpAid,
    /// Historical bytes from the ATR.
    pub historical: Vec<u8>,
    /// Discretionary data objects (algorithm attributes, PIN status, etc.).
    pub discretionary: DiscretionaryDataObjects,
}

impl ApplicationRelatedData {
    /// Parse the application related data from TLV-encoded bytes.
    pub fn parse(encoded: &[u8]) -> Result<Self, OpenPgpError> {
        let outer = tlv_unpack(Do::ApplicationRelatedData as u32, encoded)?;
        let data = parse_tlv_dict(&outer)?;
        let aid_bytes = data
            .get(&(Do::Aid as u32))
            .ok_or_else(|| OpenPgpError::InvalidData("Missing AID".into()))?;
        let historical = data
            .get(&(Do::HistoricalBytes as u32))
            .cloned()
            .unwrap_or_default();

        // Discretionary data: try tag 0x73, fall back to outer dict
        // NEO (OpenPGP v2.0) has tag 0x73 with empty content, so check for that
        let disc_data = data
            .get(&TAG_DISCRETIONARY)
            .filter(|v| !v.is_empty())
            .map(|v| v.as_slice())
            .unwrap_or(&outer);
        let discretionary = DiscretionaryDataObjects::parse(disc_data)?;

        Ok(Self {
            aid: OpenPgpAid::parse(aid_bytes),
            historical,
            discretionary,
        })
    }
}

// ---------------------------------------------------------------------------
// KDF
// ---------------------------------------------------------------------------

/// Key Derivation Function (KDF) configuration for PIN hashing.
///
/// When KDF is enabled, PINs are hashed on the host before being sent to the
/// card, improving resistance to passive eavesdropping.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Kdf {
    /// KDF is disabled; PINs are sent in plaintext.
    None,
    /// Iterated-salted S2K (string-to-key) as defined in OpenPGP.
    IterSaltedS2k {
        /// Hash algorithm used for key derivation.
        hash_algorithm: HashAlgorithm,
        /// Requested byte count; at least one full salt-and-PIN sequence is hashed.
        iteration_count: u32,
        /// Salt for deriving the user PIN.
        salt_user: Vec<u8>,
        /// Salt for deriving the reset code.
        salt_reset: Option<Vec<u8>>,
        /// Salt for deriving the admin PIN.
        salt_admin: Option<Vec<u8>>,
        /// Pre-computed hash of the default user PIN (for initial setup).
        initial_hash_user: Option<Vec<u8>>,
        /// Pre-computed hash of the default admin PIN (for initial setup).
        initial_hash_admin: Option<Vec<u8>>,
    },
}

impl Kdf {
    /// Parse KDF configuration from TLV-encoded bytes.
    pub fn parse(encoded: &[u8]) -> Result<Self, OpenPgpError> {
        let data = parse_tlv_dict(encoded)?;
        let algorithm = data.get(&0x81).map(|v| bytes2int(v) as u8).unwrap_or(0);

        if algorithm == 3 {
            let hash_algorithm =
                HashAlgorithm::from_u8(data.get(&0x82).map(|v| bytes2int(v) as u8).unwrap_or(0x08))
                    .unwrap_or(HashAlgorithm::Sha256);

            let iteration_count = data.get(&0x83).map(|v| bytes2int(v) as u32).unwrap_or(0);

            Ok(Kdf::IterSaltedS2k {
                hash_algorithm,
                iteration_count,
                salt_user: data.get(&0x84).cloned().unwrap_or_default(),
                salt_reset: data.get(&0x85).cloned(),
                salt_admin: data.get(&0x86).cloned(),
                initial_hash_user: data.get(&0x87).cloned(),
                initial_hash_admin: data.get(&0x88).cloned(),
            })
        } else {
            Ok(Kdf::None)
        }
    }

    /// Serialize this KDF configuration to bytes for storage on the card.
    pub fn to_bytes(&self) -> Vec<u8> {
        match self {
            Kdf::None => tlv_encode(0x81, &[0x00]),
            Kdf::IterSaltedS2k {
                hash_algorithm,
                iteration_count,
                salt_user,
                salt_reset,
                salt_admin,
                initial_hash_user,
                initial_hash_admin,
            } => {
                let mut buf = Vec::new();
                buf.extend_from_slice(&tlv_encode(0x81, &[0x03]));
                buf.extend_from_slice(&tlv_encode(0x82, &[*hash_algorithm as u8]));
                buf.extend_from_slice(&tlv_encode(0x83, &iteration_count.to_be_bytes()));
                buf.extend_from_slice(&tlv_encode(0x84, salt_user));
                if let Some(sr) = salt_reset {
                    buf.extend_from_slice(&tlv_encode(0x85, sr));
                }
                if let Some(sa) = salt_admin {
                    buf.extend_from_slice(&tlv_encode(0x86, sa));
                }
                if let Some(ih) = initial_hash_user {
                    buf.extend_from_slice(&tlv_encode(0x87, ih));
                }
                if let Some(ia) = initial_hash_admin {
                    buf.extend_from_slice(&tlv_encode(0x88, ia));
                }
                buf
            }
        }
    }

    /// Create a new KdfIterSaltedS2k with random salts and default PIN hashes.
    pub fn create_iter_salted_s2k(
        hash_algorithm: HashAlgorithm,
        iteration_count: u32,
    ) -> Result<Self, OpenPgpError> {
        let mut salt_user = [0u8; 8];
        let mut salt_reset = [0u8; 8];
        let mut salt_admin = [0u8; 8];
        getrandom::fill(&mut salt_user)
            .map_err(|e| OpenPgpError::InvalidData(format!("RNG error: {e}")))?;
        getrandom::fill(&mut salt_reset)
            .map_err(|e| OpenPgpError::InvalidData(format!("RNG error: {e}")))?;
        getrandom::fill(&mut salt_admin)
            .map_err(|e| OpenPgpError::InvalidData(format!("RNG error: {e}")))?;

        let initial_hash_user = std::mem::take(&mut *kdf_s2k_hash(
            hash_algorithm,
            iteration_count,
            &salt_user,
            DEFAULT_USER_PIN,
        ));
        let initial_hash_admin = std::mem::take(&mut *kdf_s2k_hash(
            hash_algorithm,
            iteration_count,
            &salt_admin,
            DEFAULT_ADMIN_PIN,
        ));

        Ok(Kdf::IterSaltedS2k {
            hash_algorithm,
            iteration_count,
            salt_user: salt_user.to_vec(),
            salt_reset: Some(salt_reset.to_vec()),
            salt_admin: Some(salt_admin.to_vec()),
            initial_hash_user: Some(initial_hash_user),
            initial_hash_admin: Some(initial_hash_admin),
        })
    }

    /// Apply KDF processing to a PIN for the given password reference.
    ///
    /// When KDF is [`Kdf::None`], the raw PIN bytes are returned.
    /// Otherwise the PIN is hashed with the appropriate salt.
    fn process(&self, pw: Pw, pin: &str) -> Zeroizing<Vec<u8>> {
        match self {
            Kdf::None => Zeroizing::new(pin.as_bytes().to_vec()),
            Kdf::IterSaltedS2k {
                hash_algorithm,
                iteration_count,
                salt_user,
                salt_reset,
                salt_admin,
                ..
            } => {
                let salt = match pw {
                    Pw::User => salt_user.as_slice(),
                    Pw::Reset => salt_reset.as_deref().unwrap_or(salt_user.as_slice()),
                    Pw::Admin => salt_admin.as_deref().unwrap_or(salt_user.as_slice()),
                };
                kdf_s2k_hash(*hash_algorithm, *iteration_count, salt, pin)
            }
        }
    }
}

/// Iterated-salted S2K hash: repeat (salt || pin) up to the requested byte count,
/// always hashing at least one complete sequence (RFC 4880, section 3.7.1.3).
fn kdf_s2k_hash(
    hash_algorithm: HashAlgorithm,
    iteration_count: u32,
    salt: &[u8],
    pin: &str,
) -> Zeroizing<Vec<u8>> {
    let data = Zeroizing::new([salt, pin.as_bytes()].concat());
    let count = (iteration_count as usize).max(data.len());
    let (full_rounds, trailing) = if data.is_empty() {
        (0, 0)
    } else {
        (count / data.len(), count % data.len())
    };

    match hash_algorithm {
        HashAlgorithm::Sha256 => {
            let mut digest = sha2::Sha256::new();
            for _ in 0..full_rounds {
                digest.update(data.as_slice());
            }
            if trailing > 0 {
                digest.update(&data[..trailing]);
            }
            Zeroizing::new(digest.finalize().to_vec())
        }
        HashAlgorithm::Sha512 => {
            let mut digest = sha2::Sha512::new();
            for _ in 0..full_rounds {
                digest.update(data.as_slice());
            }
            if trailing > 0 {
                digest.update(&data[..trailing]);
            }
            Zeroizing::new(digest.finalize().to_vec())
        }
    }
}

// ---------------------------------------------------------------------------
// Private Key Template (for import)
// ---------------------------------------------------------------------------

/// Derive algorithm attributes from a private key and key slot.
fn algorithm_attributes_for_key(
    key_ref: KeyRef,
    private_key: &PrivateKey,
) -> Result<AlgorithmAttributes, OpenPgpError> {
    match private_key {
        PrivateKey::Rsa(rsa) => {
            match rsa.key_size {
                RsaKeySize::Rsa2048 | RsaKeySize::Rsa3072 | RsaKeySize::Rsa4096 => {}
                _ => {
                    return Err(OpenPgpError::InvalidData(format!(
                        "Unsupported RSA key size for OpenPGP: {:?}",
                        rsa.key_size
                    )));
                }
            };
            let import_format = if !rsa.dp.expose_secret().is_empty() && !rsa.n.is_empty() {
                RsaImportFormat::CrtWMod
            } else if !rsa.dp.expose_secret().is_empty() {
                RsaImportFormat::Crt
            } else if !rsa.n.is_empty() {
                RsaImportFormat::StandardWMod
            } else {
                RsaImportFormat::Standard
            };
            Ok(AlgorithmAttributes::Rsa(RsaAttributes::create(
                rsa.key_size,
                import_format,
            )))
        }
        PrivateKey::Ec(ec) => {
            let curve = match ec.curve {
                EcCurve::P256 => OpenPgpCurve::P256,
                EcCurve::P384 => OpenPgpCurve::P384,
                EcCurve::P521 => OpenPgpCurve::P521,
                EcCurve::Secp256k1 => OpenPgpCurve::Secp256k1,
                EcCurve::BrainpoolP256r1 => OpenPgpCurve::BrainpoolP256r1,
                EcCurve::BrainpoolP384r1 => OpenPgpCurve::BrainpoolP384r1,
                EcCurve::BrainpoolP512r1 => OpenPgpCurve::BrainpoolP512r1,
            };
            Ok(AlgorithmAttributes::Ec(EcAttributes::create(
                key_ref, &curve,
            )?))
        }
        PrivateKey::Ed25519(_) => Ok(AlgorithmAttributes::Ec(EcAttributes::create(
            key_ref,
            &OpenPgpCurve::Ed25519,
        )?)),
        PrivateKey::X25519(_) => Ok(AlgorithmAttributes::Ec(EcAttributes::create(
            key_ref,
            &OpenPgpCurve::X25519,
        )?)),
        _ => Err(OpenPgpError::NotSupported(
            "Key type not supported for OpenPGP import".into(),
        )),
    }
}

/// Build the private key template for PUT_DATA_ODD (tag 0x4D).
fn build_private_key_template(
    key_ref: KeyRef,
    private_key: &PrivateKey,
) -> Result<Zeroizing<Vec<u8>>, OpenPgpError> {
    let mut temp = Zeroizing::new(Vec::new());
    let component_tlvs: Vec<(u32, &[u8])> = match private_key {
        PrivateKey::Rsa(rsa) => {
            let mut v = vec![
                (0x91, rsa.e.as_slice()),
                (0x92, rsa.p.expose_secret().as_slice()),
                (0x93, rsa.q.expose_secret().as_slice()),
            ];
            if !rsa.qinv.expose_secret().is_empty() {
                v.push((0x94, rsa.qinv.expose_secret().as_slice()));
            }
            if !rsa.dp.expose_secret().is_empty() {
                v.push((0x95, rsa.dp.expose_secret().as_slice()));
            }
            if !rsa.dq.expose_secret().is_empty() {
                v.push((0x96, rsa.dq.expose_secret().as_slice()));
            }
            if !rsa.n.is_empty() {
                v.push((0x97, rsa.n.as_slice()));
            }
            v
        }
        PrivateKey::Ec(ec) => {
            let mut v = vec![(0x92, ec.scalar.expose_secret().as_slice())];
            if let Some(pk) = &ec.public_key {
                v.push((0x99, pk.as_slice()));
            }
            v
        }
        PrivateKey::Ed25519(k) => {
            vec![(0x92, k.secret.expose_secret().as_slice())]
        }
        PrivateKey::X25519(k) => {
            // X25519 uses little-endian; OpenPGP card expects big-endian
            temp.extend(k.secret.expose_secret());
            temp.reverse();
            vec![(0x92, temp.as_slice())]
        }
        _ => {
            return Err(OpenPgpError::NotSupported(
                "Key type not supported for OpenPGP import".into(),
            ));
        }
    };

    // 0x7F48: concatenated tag+length headers (no values)
    let mut headers = Vec::new();
    // 0x5F48: concatenated values (contains secret key material)
    let mut values = Zeroizing::new(Vec::new());
    for (tag, value) in &component_tlvs {
        let encoded = Zeroizing::new(tlv_encode(*tag, value));
        let header_len = encoded.len() - value.len();
        headers.extend_from_slice(&encoded[..header_len]);
        values.extend_from_slice(value);
    }

    let mut inner = Zeroizing::new(key_ref.crt());
    tlv_append(&mut inner, 0x7F48, &headers);
    tlv_append(&mut inner, 0x5F48, &values);

    Ok(Zeroizing::new(tlv_encode(0x4D, &inner)))
}

// ---------------------------------------------------------------------------
// Public key parsing from OpenPGP card response
// ---------------------------------------------------------------------------

/// Parse the raw public key TLV data (contents of 0x7F49) returned by the OpenPGP
/// card into a [`PublicKey`].
fn parse_rsa_public_key(pk_data: &[u8]) -> Result<PublicKey, OpenPgpError> {
    let tlvs = parse_tlv_list(pk_data)?;
    let n = crate::__internal::tlv::tlv_get(&tlvs, 0x81)
        .ok_or_else(|| OpenPgpError::InvalidData("Missing RSA modulus (tag 0x81)".into()))?;
    let e = crate::__internal::tlv::tlv_get(&tlvs, 0x82)
        .ok_or_else(|| OpenPgpError::InvalidData("Missing RSA exponent (tag 0x82)".into()))?;
    // Strip leading zero byte from modulus if present
    let n = if !n.is_empty() && n[0] == 0 {
        n[1..].to_vec()
    } else {
        n.to_vec()
    };
    let key_size = RsaKeySize::from_bit_len(n.len() * 8).ok_or_else(|| {
        OpenPgpError::InvalidData(format!("Unsupported RSA key size: {} bits", n.len() * 8))
    })?;
    let public_key = RsaPublicKey::new(n, e.to_vec())
        .map_err(|e| OpenPgpError::InvalidData(format!("Invalid RSA public key: {e}")))?;
    if public_key.key_size != key_size {
        return Err(OpenPgpError::InvalidData(
            "RSA public key size mismatch".into(),
        ));
    }
    Ok(PublicKey::Rsa(public_key))
}

fn parse_ec_public_key(pk_data: &[u8], oid: &ObjectIdentifier) -> Result<PublicKey, OpenPgpError> {
    let point = tlv_unpack(0x86, pk_data)?;
    if *oid == OID_ED25519 {
        Ok(PublicKey::Ed25519(Ed25519PublicKey::new(point).map_err(
            |e| OpenPgpError::InvalidData(format!("Invalid Ed25519 public key: {e}")),
        )?))
    } else if *oid == OID_X25519 {
        Ok(PublicKey::X25519(X25519PublicKey::new(point).map_err(
            |e| OpenPgpError::InvalidData(format!("Invalid X25519 public key: {e}")),
        )?))
    } else {
        let curve = EcCurve::from_oid(oid)
            .ok_or_else(|| OpenPgpError::InvalidData("Unsupported EC curve".into()))?;
        Ok(PublicKey::Ec(EcPublicKey::new(curve, point).map_err(
            |e| OpenPgpError::InvalidData(format!("Invalid EC public key: {e}")),
        )?))
    }
}

// ---------------------------------------------------------------------------
// Padding helpers for sign/authenticate
// ---------------------------------------------------------------------------

/// Hash algorithm enum for sign/authenticate operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SignHashAlgorithm {
    /// SHA-1 hash (legacy; 160-bit digest).
    Sha1,
    /// SHA-256 hash (256-bit digest).
    Sha256,
    /// SHA-384 hash (384-bit digest).
    Sha384,
    /// SHA-512 hash (512-bit digest).
    Sha512,
    /// Data is already hashed. RSA and ECDSA require the exact digest length
    /// of the wrapped algorithm, which also selects the DigestInfo header for RSA.
    Prehashed(PrehashAlgorithm),
    /// EdDSA: no hashing, pass message directly.
    None,
}

/// The hash algorithm used to produce a prehashed digest.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PrehashAlgorithm {
    /// SHA-1 was used to produce the digest.
    Sha1,
    /// SHA-256 was used to produce the digest.
    Sha256,
    /// SHA-384 was used to produce the digest.
    Sha384,
    /// SHA-512 was used to produce the digest.
    Sha512,
}

fn pad_message(
    attributes: &AlgorithmAttributes,
    message: &[u8],
    hash_algorithm: SignHashAlgorithm,
) -> Result<Vec<u8>, OpenPgpError> {
    // EdDSA: never hash
    if attributes.algorithm_id() == EC_ALG_EDDSA {
        return Ok(message.to_vec());
    }

    let hash = match hash_algorithm {
        SignHashAlgorithm::Sha1 | SignHashAlgorithm::Prehashed(PrehashAlgorithm::Sha1) => {
            Some(Hash::Sha1)
        }
        SignHashAlgorithm::Sha256 | SignHashAlgorithm::Prehashed(PrehashAlgorithm::Sha256) => {
            Some(Hash::Sha256)
        }
        SignHashAlgorithm::Sha384 | SignHashAlgorithm::Prehashed(PrehashAlgorithm::Sha384) => {
            Some(Hash::Sha384)
        }
        SignHashAlgorithm::Sha512 | SignHashAlgorithm::Prehashed(PrehashAlgorithm::Sha512) => {
            Some(Hash::Sha512)
        }
        SignHashAlgorithm::None => None,
    };
    let hashed = match (hash_algorithm, hash) {
        (SignHashAlgorithm::Prehashed(_), Some(hash)) => {
            if message.len() != hash.output_len() {
                return Err(OpenPgpError::InvalidData(format!(
                    "Prehashed input must contain exactly {} bytes.",
                    hash.output_len()
                )));
            }
            message.to_vec()
        }
        (_, None) => message.to_vec(),
        (_, Some(hash)) => hash.digest(message).to_vec(),
    };

    match attributes {
        AlgorithmAttributes::Ec(_) => Ok(hashed),
        AlgorithmAttributes::Rsa(_) => hash
            .ok_or_else(|| OpenPgpError::InvalidData("Hash algorithm required for RSA".into()))?
            .digest_info(&hashed)
            .map_err(|e| OpenPgpError::InvalidData(e.to_string())),
    }
}

// ---------------------------------------------------------------------------
// Session
// ---------------------------------------------------------------------------

/// An active session with the OpenPGP applet on a YubiKey.
///
/// Provides methods for PIN management, key generation and import,
/// cryptographic operations (sign, decrypt, authenticate), certificate
/// management, and card configuration.
pub struct OpenPgpSession<C: SmartCardConnection> {
    protocol: SmartCardProtocol<C>,
    version: Version,
    app_data: ApplicationRelatedData,
}

impl<C: SmartCardConnection> OpenPgpSession<C> {
    /// Open an OpenPGP session on the given connection.
    ///
    /// On error, returns the connection so the caller can recover it.
    pub fn new(connection: C) -> Result<Self, (OpenPgpError, C)> {
        let mut protocol = SmartCardProtocol::new(connection);

        // SELECT OpenPGP application; auto-activate if needed
        match protocol.select(Aid::OPENPGP) {
            Ok(_) => {}
            Err(SmartCardError::Apdu { sw, .. }) if sw == 0x6285 || sw == 0x6985 => {
                if let Err(e) = protocol.send_apdu(0, INS_ACTIVATE, 0, 0, &[]) {
                    return Err((e.into(), protocol.into_connection()));
                }
                if let Err(e) = protocol.select(Aid::OPENPGP) {
                    return Err((e.into(), protocol.into_connection()));
                }
            }
            Err(e) => return Err((e.into(), protocol.into_connection())),
        }

        Self::init(protocol)
    }

    /// Open an OpenPGP session with SCP (Secure Channel Protocol).
    ///
    /// On error, returns the connection so the caller can recover it.
    pub fn new_with_scp(
        connection: C,
        scp_key_params: &crate::smartcard::ScpKeyParams,
    ) -> Result<Self, (OpenPgpError, C)> {
        let mut protocol = SmartCardProtocol::new(connection);

        // SELECT OpenPGP application; auto-activate if needed
        match protocol.select(Aid::OPENPGP) {
            Ok(_) => {}
            Err(SmartCardError::Apdu { sw, .. }) if sw == 0x6285 || sw == 0x6985 => {
                if let Err(e) = protocol.send_apdu(0, INS_ACTIVATE, 0, 0, &[]) {
                    return Err((e.into(), protocol.into_connection()));
                }
                if let Err(e) = protocol.select(Aid::OPENPGP) {
                    return Err((e.into(), protocol.into_connection()));
                }
            }
            Err(e) => return Err((e.into(), protocol.into_connection())),
        }

        if let Err(e) = protocol.init_scp(scp_key_params) {
            return Err((e.into(), protocol.into_connection()));
        }
        Self::init(protocol)
    }

    fn init(mut protocol: SmartCardProtocol<C>) -> Result<Self, (OpenPgpError, C)> {
        log::debug!("Opening OpenPgpSession");
        // Read version (BCD encoded)
        let version = match protocol.send_apdu(0, INS_GET_VERSION, 0, 0, &[]) {
            Ok(bcd_bytes) => Version(
                bcd(*bcd_bytes.first().unwrap_or(&0)),
                bcd(*bcd_bytes.get(1).unwrap_or(&0)),
                bcd(*bcd_bytes.get(2).unwrap_or(&0)),
            ),
            Err(SmartCardError::Apdu { sw: 0x6985, .. }) => Version(1, 0, 0),
            Err(e) => return Err((e.into(), protocol.into_connection())),
        };
        let version = patch_version(version);

        protocol.configure(version);

        // Cache application related data
        let app_data_raw = match protocol.send_apdu(
            0,
            INS_GET_DATA,
            Do::ApplicationRelatedData.p1(),
            Do::ApplicationRelatedData.p2(),
            &[],
        ) {
            Ok(v) => v,
            Err(e) => return Err((e.into(), protocol.into_connection())),
        };
        let app_data = match ApplicationRelatedData::parse(&app_data_raw) {
            Ok(v) => v,
            Err(e) => return Err((e, protocol.into_connection())),
        };

        Ok(Self {
            protocol,
            version,
            app_data,
        })
    }

    // -- Accessors --

    /// Returns the application identifier for this OpenPGP session.
    pub fn aid(&self) -> &OpenPgpAid {
        &self.app_data.aid
    }

    /// Returns the YubiKey firmware version.
    pub fn version(&self) -> Version {
        self.version
    }

    /// Returns the card's extended capabilities.
    pub fn extended_capabilities(&self) -> &ExtendedCapabilities {
        &self.app_data.discretionary.extended_capabilities
    }

    /// Returns a reference to the underlying smart card protocol.
    pub fn protocol(&self) -> &SmartCardProtocol<C> {
        &self.protocol
    }

    /// Returns a mutable reference to the underlying smart card protocol.
    pub fn protocol_mut(&mut self) -> &mut SmartCardProtocol<C> {
        &mut self.protocol
    }

    /// Consume the session, returning the underlying connection.
    pub fn into_connection(self) -> C {
        self.protocol.into_connection()
    }

    // -- Data Object I/O --

    /// Read a data object from the card by its [`Do`] tag.
    pub fn get_data(&mut self, data_object: Do) -> Result<Vec<u8>, OpenPgpError> {
        Ok(self
            .protocol
            .send_apdu(0, INS_GET_DATA, data_object.p1(), data_object.p2(), &[])?)
    }

    /// Write a data object to the card by its [`Do`] tag.
    pub fn put_data(&mut self, data_object: Do, data: &[u8]) -> Result<(), OpenPgpError> {
        self.protocol
            .send_apdu(0, INS_PUT_DATA, data_object.p1(), data_object.p2(), data)?;
        Ok(())
    }

    // -- Status / Metadata --

    /// Read the current PIN status (retry counters, max lengths, and policy).
    pub fn get_pin_status(&mut self) -> Result<PwStatus, OpenPgpError> {
        let data = self.get_data(Do::PwStatusBytes)?;
        PwStatus::parse(&data)
    }

    /// Read the global signature counter from the security support template.
    pub fn get_signature_counter(&mut self) -> Result<u32, OpenPgpError> {
        let data = self.get_data(Do::SecuritySupportTemplate)?;
        let inner = tlv_unpack(Do::SecuritySupportTemplate as u32, &data)?;
        let dict = parse_tlv_dict(&inner)?;
        let counter_bytes = dict
            .get(&TAG_SIGNATURE_COUNTER)
            .ok_or_else(|| OpenPgpError::InvalidData("Missing signature counter".into()))?;
        Ok(bytes2int(counter_bytes) as u32)
    }

    /// Read and parse the full application related data from the card.
    pub fn get_application_related_data(&mut self) -> Result<ApplicationRelatedData, OpenPgpError> {
        let data = self.get_data(Do::ApplicationRelatedData)?;
        let mut app_data = ApplicationRelatedData::parse(&data)?;
        // Pre 3.0: UIF readable separately but missing from discretionary
        if app_data.aid.version() < (3, 0) {
            app_data.discretionary.uif_sig = self.get_uif(KeyRef::Sig).ok();
            app_data.discretionary.uif_dec = self.get_uif(KeyRef::Dec).ok();
            app_data.discretionary.uif_aut = self.get_uif(KeyRef::Aut).ok();
        }
        Ok(app_data)
    }

    /// Read the key information (status of each key slot) from the card.
    pub fn get_key_information(&mut self) -> Result<KeyInformation, OpenPgpError> {
        Ok(self
            .get_application_related_data()?
            .discretionary
            .key_information)
    }

    /// Read the key generation timestamps for all key slots.
    pub fn get_generation_times(&mut self) -> Result<GenerationTimes, OpenPgpError> {
        Ok(self
            .get_application_related_data()?
            .discretionary
            .generation_times)
    }

    /// Read the key fingerprints for all key slots.
    pub fn get_fingerprints(&mut self) -> Result<Fingerprints, OpenPgpError> {
        Ok(self
            .get_application_related_data()?
            .discretionary
            .fingerprints)
    }

    // -- PIN Management --

    fn process_pin(
        &self,
        kdf: &Kdf,
        pw: Pw,
        pin: &str,
    ) -> Result<Zeroizing<Vec<u8>>, OpenPgpError> {
        if matches!(kdf, Kdf::None) {
            let pin_len = pin.len();
            let min_len: usize = if matches!(pw, Pw::User) { 6 } else { 8 };
            let max_len = self.app_data.discretionary.pw_status.get_max_len(pw) as usize;
            if pin_len < min_len || pin_len > max_len {
                return Err(OpenPgpError::InvalidData(format!(
                    "PIN length must be in the range {min_len}-{max_len}"
                )));
            }
        }
        Ok(kdf.process(pw, pin))
    }

    fn verify_inner(&mut self, pw: Pw, pin: &OpenPgpPin, mode: u8) -> Result<(), OpenPgpError> {
        let kdf = self.get_kdf()?;
        let pin_enc = self.process_pin(&kdf, pw, pin.as_str())?;
        match self
            .protocol
            .send_apdu(0, INS_VERIFY, 0, pw as u8 + mode, &pin_enc)
        {
            Ok(_) => Ok(()),
            Err(SmartCardError::Apdu { sw, .. })
                if sw == 0x6982 || (sw >> 8 == 0x63 && self.version < Version(4, 0, 0)) =>
            {
                let attempts = self.get_pin_status()?.get_attempts(pw) as u32;
                Err(OpenPgpError::InvalidPin(attempts))
            }
            Err(SmartCardError::Apdu { sw: 0x6983, .. }) => Err(OpenPgpError::PinBlocked),
            Err(e) => Err(e.into()),
        }
    }

    /// Verify the user PIN. If `extended` is true, uses extended mode (PW1 for signing).
    pub fn verify_pin(&mut self, pin: &OpenPgpPin, extended: bool) -> Result<(), OpenPgpError> {
        log::debug!("Verifying OpenPGP PIN");
        let mode = if extended { 1 } else { 0 };
        self.verify_inner(Pw::User, pin, mode)
    }

    /// Verify the admin PIN.
    pub fn verify_admin(&mut self, admin_pin: &OpenPgpPin) -> Result<(), OpenPgpError> {
        log::debug!("Verifying OpenPGP admin PIN");
        self.verify_inner(Pw::Admin, admin_pin, 0)
    }

    /// Clear the verification state of the given PIN (requires YubiKey 5.6.0+).
    pub fn unverify_pin(&mut self, pw: Pw) -> Result<(), OpenPgpError> {
        log::debug!("Clearing PIN verification");
        require_version(self.version, Version(5, 6, 0), "unverify_pin")?;
        self.protocol
            .send_apdu(0, INS_VERIFY, 0xFF, pw as u8, &[])?;
        Ok(())
    }

    fn change_inner(
        &mut self,
        pw: Pw,
        pin: &OpenPgpPin,
        new_pin: &OpenPgpPin,
    ) -> Result<(), OpenPgpError> {
        let kdf = self.get_kdf()?;
        let mut data = Zeroizing::new(self.process_pin(&kdf, pw, pin.as_str())?.to_vec());
        data.extend_from_slice(&self.process_pin(&kdf, pw, new_pin.as_str())?);
        match self
            .protocol
            .send_apdu(0, INS_CHANGE_PIN, 0, pw as u8, &data)
        {
            Ok(_) => Ok(()),
            Err(SmartCardError::Apdu { sw, .. })
                if sw == 0x6982 || (sw == 0x6985 && self.version < Version(4, 0, 0)) =>
            {
                let attempts = self.get_pin_status()?.get_attempts(pw) as u32;
                Err(OpenPgpError::InvalidPin(attempts))
            }
            Err(SmartCardError::Apdu { sw: 0x6983, .. }) => Err(OpenPgpError::PinBlocked),
            Err(e) => Err(e.into()),
        }
    }

    /// Change the user PIN from `pin` to `new_pin`.
    pub fn change_pin(
        &mut self,
        pin: &OpenPgpPin,
        new_pin: &OpenPgpPin,
    ) -> Result<(), OpenPgpError> {
        log::debug!("Changing OpenPGP PIN");
        self.change_inner(Pw::User, pin, new_pin)?;
        log::info!("OpenPGP PIN changed");
        Ok(())
    }

    /// Change the admin PIN from `admin_pin` to `new_admin_pin`.
    pub fn change_admin(
        &mut self,
        admin_pin: &OpenPgpPin,
        new_admin_pin: &OpenPgpPin,
    ) -> Result<(), OpenPgpError> {
        log::debug!("Changing OpenPGP admin PIN");
        self.change_inner(Pw::Admin, admin_pin, new_admin_pin)?;
        log::info!("OpenPGP admin PIN changed");
        Ok(())
    }

    /// Set the resetting code used to unblock the user PIN.
    pub fn set_reset_code(&mut self, reset_code: &OpenPgpPin) -> Result<(), OpenPgpError> {
        log::debug!("Setting OpenPGP reset code");
        let kdf = self.get_kdf()?;
        let data = self.process_pin(&kdf, Pw::Reset, reset_code.as_str())?;
        self.put_data(Do::ResettingCode, &data)?;
        log::info!("OpenPGP reset code set");
        Ok(())
    }

    /// Reset the user PIN to `new_pin`, optionally using a reset code.
    ///
    /// If `reset_code` is `None`, the admin PIN must have been verified first.
    pub fn reset_pin(
        &mut self,
        new_pin: &OpenPgpPin,
        reset_code: Option<&OpenPgpPin>,
    ) -> Result<(), OpenPgpError> {
        log::debug!("Resetting OpenPGP PIN");
        let kdf = self.get_kdf()?;
        let new_pin_data = self.process_pin(&kdf, Pw::User, new_pin.as_str())?;
        let (p1, data): (u8, Zeroizing<Vec<u8>>) = if let Some(code) = reset_code {
            let mut d = Zeroizing::new(self.process_pin(&kdf, Pw::Reset, code.as_str())?.to_vec());
            d.extend_from_slice(&new_pin_data);
            (0, d)
        } else {
            (2, new_pin_data)
        };

        match self
            .protocol
            .send_apdu(0, INS_RESET_RETRY_COUNTER, p1, Pw::User as u8, &data)
        {
            Ok(_) => {
                log::info!("OpenPGP PIN reset");
                Ok(())
            }
            Err(SmartCardError::Apdu { sw, .. }) if sw == 0x6982 && reset_code.is_some() => {
                let attempts = self.get_pin_status()?.attempts_reset as u32;
                Err(OpenPgpError::InvalidPin(attempts))
            }
            Err(SmartCardError::Apdu { sw, .. })
                if (sw == 0x6983 || sw == 0x6A80) && reset_code.is_some() =>
            {
                Err(OpenPgpError::PinBlocked)
            }
            Err(e) => Err(e.into()),
        }
    }

    /// Set the signature PIN policy (verify once per session or every operation).
    pub fn set_signature_pin_policy(&mut self, pin_policy: PinPolicy) -> Result<(), OpenPgpError> {
        log::debug!("Setting signature PIN policy");
        self.put_data(Do::PwStatusBytes, &[pin_policy as u8])?;
        log::info!("Signature PIN policy set");
        Ok(())
    }

    /// Set the maximum retry attempts for user PIN, reset code, and admin PIN.
    pub fn set_pin_attempts(
        &mut self,
        user_attempts: u8,
        reset_attempts: u8,
        admin_attempts: u8,
    ) -> Result<(), OpenPgpError> {
        log::debug!("Setting OpenPGP PIN attempts");
        if self.version.0 == 1 {
            require_version(self.version, Version(1, 0, 7), "set_pin_attempts")?;
        } else {
            require_version(self.version, Version(4, 3, 1), "set_pin_attempts")?;
        }
        self.protocol.send_apdu(
            0,
            INS_SET_PIN_RETRIES,
            0,
            0,
            &[user_attempts, reset_attempts, admin_attempts],
        )?;
        log::info!("OpenPGP PIN attempts set");
        Ok(())
    }

    // -- KDF --

    /// Read the current KDF configuration from the card.
    pub fn get_kdf(&mut self) -> Result<Kdf, OpenPgpError> {
        if !self
            .app_data
            .discretionary
            .extended_capabilities
            .has_flag(extended_capability_flags::KDF)
        {
            return Ok(Kdf::None);
        }
        let data = self.get_data(Do::Kdf)?;
        Kdf::parse(&data)
    }

    /// Write a new KDF configuration to the card.
    pub fn set_kdf(&mut self, kdf: &Kdf) -> Result<(), OpenPgpError> {
        log::debug!("Setting OpenPGP KDF");
        if !self
            .app_data
            .discretionary
            .extended_capabilities
            .has_flag(extended_capability_flags::KDF)
        {
            return Err(OpenPgpError::NotSupported("KDF is not supported".into()));
        }
        self.put_data(Do::Kdf, &kdf.to_bytes())?;
        log::info!("OpenPGP KDF configured");
        Ok(())
    }

    // -- Factory Reset --

    /// Perform a factory reset of the OpenPGP applet, erasing all keys and settings.
    pub fn reset(&mut self) -> Result<(), OpenPgpError> {
        log::debug!("Resetting OpenPGP application");
        require_version(self.version, Version(1, 0, 6), "reset")?;

        // Block PINs by sending invalid PINs
        let status = self.get_pin_status()?;
        for pw in [Pw::User, Pw::Admin] {
            let attempts = status.get_attempts(pw);
            for _ in 0..attempts {
                let _ = self
                    .protocol
                    .send_apdu(0, INS_VERIFY, 0, pw as u8, INVALID_PIN);
            }
        }

        // TERMINATE + ACTIVATE
        self.protocol.send_apdu(0, INS_TERMINATE, 0, 0, &[])?;
        self.protocol.send_apdu(0, INS_ACTIVATE, 0, 0, &[])?;
        log::info!("OpenPGP application reset");
        Ok(())
    }

    // -- Algorithm Attributes --

    /// Read the current algorithm attributes for a key slot.
    pub fn get_algorithm_attributes(
        &mut self,
        key_ref: KeyRef,
    ) -> Result<AlgorithmAttributes, OpenPgpError> {
        let data = self.get_application_related_data()?;
        data.discretionary
            .get_algorithm_attributes(key_ref)
            .cloned()
            .ok_or_else(|| {
                OpenPgpError::InvalidData(format!("No algorithm attributes for key {:?}", key_ref))
            })
    }

    /// Read the list of supported algorithms for each key slot.
    pub fn get_algorithm_information(
        &mut self,
    ) -> Result<HashMap<KeyRef, Vec<AlgorithmAttributes>>, OpenPgpError> {
        if !self
            .app_data
            .discretionary
            .extended_capabilities
            .has_flag(extended_capability_flags::ALGORITHM_ATTRIBUTES_CHANGEABLE)
        {
            return Err(OpenPgpError::NotSupported(
                "Writing Algorithm Attributes is not supported".into(),
            ));
        }

        if self.version < Version(5, 2, 0) && self.version.0 > 0 {
            // Pre-5.2 hardcoded support
            let fmt = if 0 < self.version.0 && self.version.0 < 4 {
                RsaImportFormat::CrtWMod
            } else {
                RsaImportFormat::Standard
            };
            let mut sizes = vec![RsaKeySize::Rsa2048];
            if self.version.0 >= 4 && (self.version.0, self.version.1) != (4, 4) {
                sizes.push(RsaKeySize::Rsa3072);
                sizes.push(RsaKeySize::Rsa4096);
            }
            let attrs: Vec<AlgorithmAttributes> = sizes
                .iter()
                .map(|&s| AlgorithmAttributes::Rsa(RsaAttributes::create(s, fmt)))
                .collect();
            let mut map = HashMap::new();
            map.insert(KeyRef::Sig, attrs.clone());
            map.insert(KeyRef::Dec, attrs.clone());
            map.insert(KeyRef::Aut, attrs);
            return Ok(map);
        }

        let buf = self.get_data(Do::AlgorithmInformation)?;
        // Try to unpack outer TLV; handle trailing-zero quirk
        let inner = match tlv_unpack(Do::AlgorithmInformation as u32, &buf) {
            Ok(v) => v,
            Err(_) => {
                let mut padded = buf.clone();
                padded.extend_from_slice(&[0, 0]);
                let v = tlv_unpack(Do::AlgorithmInformation as u32, &padded)?;
                if v.len() >= 2 {
                    v[..v.len() - 2].to_vec()
                } else {
                    v
                }
            }
        };

        let entries = parse_tlv_list(&inner)?;
        let slot_map: HashMap<u32, KeyRef> = [
            (Do::AlgorithmAttributesSig as u32, KeyRef::Sig),
            (Do::AlgorithmAttributesDec as u32, KeyRef::Dec),
            (Do::AlgorithmAttributesAut as u32, KeyRef::Aut),
            (Do::AlgorithmAttributesAtt as u32, KeyRef::Att),
        ]
        .into();

        let mut result: HashMap<KeyRef, Vec<AlgorithmAttributes>> = HashMap::new();
        for (tag, value) in &entries {
            if let Some(&key) = slot_map.get(tag)
                && let Ok(attrs) = AlgorithmAttributes::parse(value)
            {
                result.entry(key).or_default().push(attrs);
            }
        }

        Ok(result)
    }

    /// Set the algorithm attributes for a key slot.
    ///
    /// # Warning
    ///
    /// Changing the algorithm attributes deletes any key already stored in the slot.
    pub fn set_algorithm_attributes(
        &mut self,
        key_ref: KeyRef,
        attributes: &AlgorithmAttributes,
    ) -> Result<(), OpenPgpError> {
        log::debug!("Setting algorithm attributes for {:?}", key_ref);
        self.put_data(key_ref.algorithm_attributes_do(), &attributes.to_bytes())?;
        log::info!("Algorithm attributes set for {:?}", key_ref);
        Ok(())
    }

    // -- UIF (Touch) --

    /// Read the User Interaction Flag (touch policy) for a key slot.
    pub fn get_uif(&mut self, key_ref: KeyRef) -> Result<Uif, OpenPgpError> {
        if self.version >= Version(4, 2, 0) {
            let data = self.get_data(key_ref.uif_do())?;
            Uif::parse(&data).ok_or_else(|| OpenPgpError::InvalidData("Invalid UIF value".into()))
        } else {
            Ok(Uif::Off)
        }
    }

    /// Set the User Interaction Flag (touch policy) for a key slot.
    pub fn set_uif(&mut self, key_ref: KeyRef, uif: Uif) -> Result<(), OpenPgpError> {
        log::debug!("Setting UIF for {:?}", key_ref);
        require_version(self.version, Version(4, 2, 0), "set_uif")?;
        if key_ref == KeyRef::Att {
            require_version(self.version, Version(5, 2, 1), "set_uif for ATT key")?;
        }
        if uif.is_cached() {
            require_version(self.version, Version(5, 2, 1), "cached UIF")?;
        }

        let current = self.get_uif(key_ref)?;
        if current.is_fixed() {
            return Err(OpenPgpError::InvalidData(
                "Cannot change UIF when set to FIXED".into(),
            ));
        }

        self.put_data(key_ref.uif_do(), &uif.to_bytes())?;
        log::info!("UIF configured for {:?}", key_ref);
        Ok(())
    }

    // -- Key Metadata --

    /// Set the key generation timestamp for a key slot (Unix epoch seconds).
    pub fn set_generation_time(
        &mut self,
        key_ref: KeyRef,
        timestamp: u32,
    ) -> Result<(), OpenPgpError> {
        self.put_data(key_ref.generation_time_do(), &timestamp.to_be_bytes())
    }

    /// Set the key fingerprint for a key slot.
    pub fn set_fingerprint(
        &mut self,
        key_ref: KeyRef,
        fingerprint: &[u8],
    ) -> Result<(), OpenPgpError> {
        self.put_data(key_ref.fingerprint_do(), fingerprint)
    }

    // -- Key Generation --

    /// Generate an RSA key pair on-card and return the raw public key data.
    pub fn generate_rsa_key(
        &mut self,
        key_ref: KeyRef,
        key_size: RsaKeySize,
    ) -> Result<PublicKey, OpenPgpError> {
        log::debug!("Generating RSA key for {:?}", key_ref);
        if self.version >= Version(4, 2, 0) && self.version < Version(4, 3, 5) {
            return Err(OpenPgpError::NotSupported(
                "RSA key generation not supported on this YubiKey".into(),
            ));
        }

        if self
            .app_data
            .discretionary
            .extended_capabilities
            .has_flag(extended_capability_flags::ALGORITHM_ATTRIBUTES_CHANGEABLE)
        {
            let import_format = if 0 < self.version.0 && self.version.0 < 4 {
                RsaImportFormat::CrtWMod
            } else {
                RsaImportFormat::Standard
            };
            let attributes =
                AlgorithmAttributes::Rsa(RsaAttributes::create(key_size, import_format));
            self.set_algorithm_attributes(key_ref, &attributes)?;
        } else if key_size != RsaKeySize::Rsa2048 {
            return Err(OpenPgpError::NotSupported(
                "Algorithm attributes not supported".into(),
            ));
        }

        let crt = key_ref.crt();
        let resp = self
            .protocol
            .send_apdu(0, INS_GENERATE_ASYM, 0x80, 0x00, &crt)?;
        let pk_data = tlv_unpack(TAG_PUBLIC_KEY, &resp)?;
        log::info!("RSA key generated");
        parse_rsa_public_key(&pk_data)
    }

    /// Generate an EC key pair on-card for the given curve and return the public key.
    pub fn generate_ec_key(
        &mut self,
        key_ref: KeyRef,
        curve: OpenPgpCurve,
    ) -> Result<PublicKey, OpenPgpError> {
        log::debug!("Generating EC key for {:?}", key_ref);
        require_version(self.version, Version(5, 2, 0), "generate_ec_key")?;

        let attributes = AlgorithmAttributes::Ec(EcAttributes::create(key_ref, &curve)?);
        self.set_algorithm_attributes(key_ref, &attributes)?;

        let crt = key_ref.crt();
        let resp = self
            .protocol
            .send_apdu(0, INS_GENERATE_ASYM, 0x80, 0x00, &crt)?;
        let pk_data = tlv_unpack(TAG_PUBLIC_KEY, &resp)?;
        log::info!("EC key generated");
        parse_ec_public_key(&pk_data, &curve.oid())
    }

    /// Read the public key from a key slot without generating a new one.
    pub fn get_public_key(&mut self, key_ref: KeyRef) -> Result<PublicKey, OpenPgpError> {
        let attributes = self.get_algorithm_attributes(key_ref)?;
        let crt = key_ref.crt();
        let resp = self
            .protocol
            .send_apdu(0, INS_GENERATE_ASYM, 0x81, 0x00, &crt)?;
        let pk_data = tlv_unpack(TAG_PUBLIC_KEY, &resp)?;
        match &attributes {
            AlgorithmAttributes::Rsa(_) => parse_rsa_public_key(&pk_data),
            AlgorithmAttributes::Ec(ec) => {
                let oid = ec.oid()?;
                parse_ec_public_key(&pk_data, &oid)
            }
        }
    }

    // -- Key Import / Delete --

    /// Import a private key into a key slot.
    ///
    /// Automatically sets the algorithm attributes on the card before importing.
    pub fn put_key(
        &mut self,
        key_ref: KeyRef,
        private_key: &PrivateKey,
    ) -> Result<(), OpenPgpError> {
        log::debug!("Importing key for {:?}", key_ref);
        let attributes = algorithm_attributes_for_key(key_ref, private_key)?;
        self.set_algorithm_attributes(key_ref, &attributes)?;
        let template = build_private_key_template(key_ref, private_key)?;
        self.protocol
            .send_apdu(0, INS_PUT_DATA_ODD, 0x3F, 0xFF, &template)?;
        log::info!("Key imported");
        Ok(())
    }

    /// Delete the key in a slot by resetting its algorithm attributes.
    pub fn delete_key(&mut self, key_ref: KeyRef) -> Result<(), OpenPgpError> {
        log::debug!("Deleting key for {:?}", key_ref);
        if 0 < self.version.0 && self.version.0 < 4 {
            // NEO: overwrite with a dummy RSA key import is not easily supported
            // without generating a real key; use put_data to change attributes instead
            return Err(OpenPgpError::NotSupported(
                "delete_key on NEO requires full key import".into(),
            ));
        }
        // Delete by changing key attributes twice
        self.put_data(
            key_ref.algorithm_attributes_do(),
            &AlgorithmAttributes::Rsa(RsaAttributes::create(
                RsaKeySize::Rsa4096,
                RsaImportFormat::Standard,
            ))
            .to_bytes(),
        )?;
        self.set_algorithm_attributes(
            key_ref,
            &AlgorithmAttributes::Rsa(RsaAttributes::create(
                RsaKeySize::Rsa2048,
                RsaImportFormat::Standard,
            )),
        )?;
        log::info!("Key deleted for {:?}", key_ref);
        Ok(())
    }

    // -- Crypto Operations --

    /// Perform a signing operation using the SIG key slot (PSO: COMPUTE DIGITAL SIGNATURE).
    pub fn sign(
        &mut self,
        message: &[u8],
        hash_algorithm: SignHashAlgorithm,
    ) -> Result<Vec<u8>, OpenPgpError> {
        log::debug!("Signing with {:?}", KeyRef::Sig);
        let attributes = self.get_algorithm_attributes(KeyRef::Sig)?;
        let padded = pad_message(&attributes, message, hash_algorithm)?;
        let response = self.protocol.send_apdu(0, INS_PSO, 0x9E, 0x9A, &padded)?;
        Ok(response)
    }

    /// Perform a decryption operation using the DEC key slot (PSO: DECIPHER).
    pub fn decrypt(&mut self, value: &[u8]) -> Result<Vec<u8>, OpenPgpError> {
        log::debug!("Decrypting with key");
        let attributes = self.get_algorithm_attributes(KeyRef::Dec)?;
        let data = match &attributes {
            AlgorithmAttributes::Rsa(_) => {
                let mut d = vec![0x00];
                d.extend_from_slice(value);
                d
            }
            AlgorithmAttributes::Ec(_) => {
                let inner = tlv_encode(0x86, value);
                let mid = tlv_encode(0x7F49, &inner);
                tlv_encode(0xA6, &mid)
            }
        };
        let response = self.protocol.send_apdu(0, INS_PSO, 0x80, 0x86, &data)?;
        Ok(response)
    }

    /// Perform an authentication operation using the AUT key slot (INTERNAL AUTHENTICATE).
    pub fn authenticate(
        &mut self,
        message: &[u8],
        hash_algorithm: SignHashAlgorithm,
    ) -> Result<Vec<u8>, OpenPgpError> {
        log::debug!("Authenticating with {:?}", KeyRef::Aut);
        let attributes = self.get_algorithm_attributes(KeyRef::Aut)?;
        let padded = pad_message(&attributes, message, hash_algorithm)?;
        let response =
            self.protocol
                .send_apdu(0, INS_INTERNAL_AUTHENTICATE, 0x00, 0x00, &padded)?;
        Ok(response)
    }

    // -- Certificate Management --

    fn select_certificate(&mut self, key_ref: KeyRef) -> Result<(), OpenPgpError> {
        if self.version >= Version(5, 2, 0) {
            let do_bytes = int2bytes(Do::CardholderCertificate as u64);
            let inner = tlv_encode(0x5C, &do_bytes);
            let mut outer = tlv_encode(0x60, &inner);
            if self.version <= Version(5, 4, 3) {
                // Non-standard leading byte
                let mut patched = vec![0x06];
                patched.extend_from_slice(&outer);
                outer = patched;
            }
            // Index: 3 - key_ref for SIG(1)→2, DEC(2)→1, AUT(3)→0
            let index = 3u8.saturating_sub(key_ref as u8);
            self.protocol
                .send_apdu(0, INS_SELECT_DATA, index, 0x04, &outer)?;
        } else if key_ref != KeyRef::Aut {
            return Err(OpenPgpError::NotSupported(
                "Certificate slot selection requires v5.2.0+".into(),
            ));
        }
        Ok(())
    }

    /// Read the certificate stored for a key slot (DER-encoded X.509).
    pub fn get_certificate(&mut self, key_ref: KeyRef) -> Result<Vec<u8>, OpenPgpError> {
        if key_ref == KeyRef::Att {
            require_version(self.version, Version(5, 2, 0), "ATT certificate")?;
            let data = self.get_data(Do::AttCertificate)?;
            if data.is_empty() {
                return Err(OpenPgpError::InvalidData("No certificate found".into()));
            }
            return Ok(data);
        }
        self.select_certificate(key_ref)?;
        let data = self.get_data(Do::CardholderCertificate)?;
        if data.is_empty() {
            return Err(OpenPgpError::InvalidData("No certificate found".into()));
        }
        Ok(data)
    }

    /// Write a DER-encoded X.509 certificate to a key slot.
    pub fn put_certificate(
        &mut self,
        key_ref: KeyRef,
        cert_der: &[u8],
    ) -> Result<(), OpenPgpError> {
        log::debug!("Importing certificate for {:?}", key_ref);
        if key_ref == KeyRef::Att {
            require_version(self.version, Version(5, 2, 0), "ATT certificate")?;
            self.put_data(Do::AttCertificate, cert_der)?;
            log::info!("Certificate imported");
            return Ok(());
        }
        self.select_certificate(key_ref)?;
        self.put_data(Do::CardholderCertificate, cert_der)?;
        log::info!("Certificate imported");
        Ok(())
    }

    /// Delete the certificate stored for a key slot.
    pub fn delete_certificate(&mut self, key_ref: KeyRef) -> Result<(), OpenPgpError> {
        log::debug!("Deleting certificate for {:?}", key_ref);
        if key_ref == KeyRef::Att {
            require_version(self.version, Version(5, 2, 0), "ATT certificate")?;
            self.put_data(Do::AttCertificate, &[])?;
            log::info!("Certificate deleted");
            return Ok(());
        }
        self.select_certificate(key_ref)?;
        self.put_data(Do::CardholderCertificate, &[])?;
        log::info!("Certificate deleted");
        Ok(())
    }

    /// Generate an attestation certificate for a key slot (YubiKey 5.2+).
    pub fn attest_key(&mut self, key_ref: KeyRef) -> Result<Vec<u8>, OpenPgpError> {
        log::debug!("Attesting key for {:?}", key_ref);
        require_version(self.version, Version(5, 2, 0), "attest_key")?;
        self.protocol
            .send_apdu(0x80, INS_GET_ATTESTATION, key_ref as u8, 0, &[])?;
        self.get_certificate(key_ref)
    }

    // -- Challenge --

    /// Request random bytes from the card's RNG (GET CHALLENGE).
    pub fn get_challenge(&mut self, length: u16) -> Result<Vec<u8>, OpenPgpError> {
        let ec = &self.app_data.discretionary.extended_capabilities;
        if !ec.has_flag(extended_capability_flags::GET_CHALLENGE) {
            return Err(OpenPgpError::NotSupported(
                "GET_CHALLENGE is not supported".into(),
            ));
        }
        if length == 0 || length > ec.challenge_max_length {
            return Err(OpenPgpError::InvalidData(
                "Unsupported challenge length".into(),
            ));
        }
        // Send GET CHALLENGE with Le = length
        // The protocol's send_apdu uses data=[], so Le is handled by providing empty data
        // and the card returns `length` random bytes.
        // We pass length in P1/P2=0 and rely on card behavior.
        let resp = self
            .protocol
            .send_apdu_with_le(0, INS_GET_CHALLENGE, 0, 0, &[], length)?;
        Ok(resp)
    }
}

// ---------------------------------------------------------------------------
// Safe Reset
// ---------------------------------------------------------------------------

/// Performs an OpenPGP factory reset without requiring a working session.
///
/// Unlike [`OpenPgpSession::reset`], this operates directly on a connection
/// and avoids reading application data that may be corrupted. It blocks all
/// PINs by repeatedly verifying with invalid values, then issues TERMINATE
/// and ACTIVATE to restore the application to its factory state.
pub fn safe_reset<C: SmartCardConnection>(connection: C) -> Result<(), SmartCardError> {
    let mut protocol = SmartCardProtocol::new(connection);
    protocol.select(Aid::OPENPGP)?;

    for pw in [Pw::User, Pw::Admin] {
        loop {
            match protocol.send_apdu(0, INS_VERIFY, 0, pw as u8, INVALID_PIN) {
                Err(SmartCardError::Apdu { sw, .. })
                    if sw == Sw::SecurityConditionNotSatisfied as u16 =>
                {
                    // PIN not yet blocked, try again
                    continue;
                }
                _ => break,
            }
        }
    }

    protocol.send_apdu(0, INS_TERMINATE, 0, 0, &[])?;
    protocol.send_apdu(0, INS_ACTIVATE, 0, 0, &[])?;
    Ok(())
}

fn require_version(current: Version, required: Version, feature: &str) -> Result<(), OpenPgpError> {
    crate::core::require_version(current, required, feature).map_err(OpenPgpError::NotSupported)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::__internal::tlv::tlv_parse;

    #[test]
    fn test_uif_properties() {
        assert!(!Uif::Off.is_fixed());
        assert!(!Uif::Off.is_cached());
        assert!(!Uif::On.is_fixed());
        assert!(Uif::Fixed.is_fixed());
        assert!(Uif::Cached.is_cached());
        assert!(Uif::CachedFixed.is_fixed());
        assert!(Uif::CachedFixed.is_cached());
    }

    #[test]
    fn test_uif_to_bytes() {
        assert_eq!(Uif::Off.to_bytes(), [0x00, 0x20]);
        assert_eq!(Uif::On.to_bytes(), [0x01, 0x20]);
        assert_eq!(Uif::Fixed.to_bytes(), [0x02, 0x20]);
    }

    #[test]
    fn test_uif_parse() {
        assert_eq!(Uif::parse(&[0x00, 0x20]), Some(Uif::Off));
        assert_eq!(Uif::parse(&[0x03, 0x20]), Some(Uif::Cached));
        assert_eq!(Uif::parse(&[]), None);
    }

    #[test]
    fn test_do_p1_p2() {
        assert_eq!(Do::ApplicationRelatedData.p1(), 0x00);
        assert_eq!(Do::ApplicationRelatedData.p2(), 0x6E);
        assert_eq!(Do::PrivateUse1.p1(), 0x01);
        assert_eq!(Do::PrivateUse1.p2(), 0x01);
        assert_eq!(Do::Language.p1(), 0xEF);
        assert_eq!(Do::Language.p2(), 0x2D);
    }

    #[test]
    fn test_key_ref_crt() {
        let sig_crt = KeyRef::Sig.crt();
        // Should be TLV(0xB6, empty)
        assert_eq!(sig_crt, vec![0xB6, 0x00]);

        let att_crt = KeyRef::Att.crt();
        // TLV(0xB6, TLV(0x84, [0x81]))
        assert_eq!(att_crt, vec![0xB6, 0x03, 0x84, 0x01, 0x81]);
    }

    #[test]
    fn test_rsa_attributes_roundtrip() {
        let attrs = RsaAttributes::create(RsaKeySize::Rsa2048, RsaImportFormat::Standard);
        let bytes = attrs.to_bytes();
        assert_eq!(bytes, vec![0x01, 0x08, 0x00, 0x00, 0x11, 0x00]);
        let parsed = AlgorithmAttributes::parse(&bytes).unwrap();
        match parsed {
            AlgorithmAttributes::Rsa(r) => {
                assert_eq!(r.n_len, 2048);
                assert_eq!(r.e_len, 17);
                assert_eq!(r.import_format, RsaImportFormat::Standard);
            }
            _ => panic!("Expected RSA"),
        }
    }

    #[test]
    fn test_ec_attributes_roundtrip() {
        let attrs = EcAttributes::create(KeyRef::Sig, &OpenPgpCurve::Ed25519).unwrap();
        assert_eq!(attrs.algorithm_id, EC_ALG_EDDSA);
        let bytes = attrs.to_bytes();
        let parsed = AlgorithmAttributes::parse(&bytes).unwrap();
        match parsed {
            AlgorithmAttributes::Ec(e) => {
                assert_eq!(e.algorithm_id, EC_ALG_EDDSA);
                assert_eq!(e.import_format, EcImportFormat::Standard);
                assert_eq!(e.oid().unwrap(), OID_ED25519);
            }
            _ => panic!("Expected EC"),
        }
    }

    #[test]
    fn test_ec_attributes_ecdh_for_dec() {
        let attrs = EcAttributes::create(KeyRef::Dec, &OpenPgpCurve::P256).unwrap();
        assert_eq!(attrs.algorithm_id, EC_ALG_ECDH);
    }

    #[test]
    fn test_ec_attributes_ecdsa_for_sig() {
        let attrs = EcAttributes::create(KeyRef::Sig, &OpenPgpCurve::P256).unwrap();
        assert_eq!(attrs.algorithm_id, EC_ALG_ECDSA);
    }

    #[test]
    fn test_pw_status_parse() {
        let data = [0x01, 127, 127, 127, 3, 0, 3];
        let status = PwStatus::parse(&data).unwrap();
        assert_eq!(status.pin_policy_user, PinPolicy::Once);
        assert_eq!(status.max_len_user, 127);
        assert_eq!(status.attempts_user, 3);
        assert_eq!(status.attempts_admin, 3);
    }

    #[test]
    fn test_extended_capabilities_parse() {
        let data = [0xFF, 0x01, 0x00, 0x80, 0x04, 0x00, 0x04, 0x00, 0x01, 0x01];
        let ec = ExtendedCapabilities::parse(&data).unwrap();
        assert!(ec.has_flag(extended_capability_flags::KDF));
        assert!(ec.has_flag(extended_capability_flags::SECURE_MESSAGING));
        assert_eq!(ec.challenge_max_length, 128);
        assert_eq!(ec.certificate_max_length, 1024);
        assert!(ec.pin_block_2_format);
        assert!(ec.mse_command);
    }

    #[test]
    fn test_openpgp_aid_parse() {
        // Minimal 16-byte AID
        let mut raw = vec![0xD2, 0x76, 0x00, 0x01, 0x24, 0x01];
        raw.push(0x03); // version major BCD 03 → 3
        raw.push(0x04); // version minor BCD 04 → 4
        raw.push(0x00); // manufacturer high
        raw.push(0x06); // manufacturer low = 6 (Yubico)
        raw.extend_from_slice(&[0x12, 0x34, 0x56, 0x78]); // serial BCD
        raw.extend_from_slice(&[0x00, 0x00]); // padding

        let aid = OpenPgpAid::parse(&raw);
        assert_eq!(aid.version(), (3, 4));
        assert_eq!(aid.manufacturer(), 6);
        assert_eq!(aid.serial(), 12345678);
    }

    #[test]
    fn test_kdf_none_roundtrip() {
        let kdf = Kdf::None;
        let bytes = kdf.to_bytes();
        assert_eq!(bytes, vec![0x81, 0x01, 0x00]);
        let parsed = Kdf::parse(&bytes).unwrap();
        assert_eq!(parsed, Kdf::None);
    }

    #[test]
    fn test_kdf_none_process() {
        let kdf = Kdf::None;
        assert_eq!(kdf.process(Pw::User, "123456").as_slice(), b"123456");
    }

    #[test]
    fn test_kdf_s2k_hash_minimum_and_repetition() {
        for algorithm in [HashAlgorithm::Sha256, HashAlgorithm::Sha512] {
            for pin in ["123456", "12345678", "12345\u{e9}"] {
                let data = [b"12345678".as_slice(), pin.as_bytes()].concat();
                for count in [0, 1, 7, 8, 9, 13, 14, 15, 16, 27, 28, 29, 1024] {
                    let mut input = data.clone();
                    while input.len() < count as usize {
                        let remaining = count as usize - input.len();
                        input.extend_from_slice(&data[..remaining.min(data.len())]);
                    }
                    let expected = match algorithm {
                        HashAlgorithm::Sha256 => sha2::Sha256::digest(&input).to_vec(),
                        HashAlgorithm::Sha512 => sha2::Sha512::digest(&input).to_vec(),
                    };
                    assert_eq!(
                        kdf_s2k_hash(algorithm, count, b"12345678", pin).as_slice(),
                        expected,
                        "{algorithm:?}, count={count}, pin={pin:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn test_kdf_initial_hashes_include_full_default_pins() {
        for algorithm in [HashAlgorithm::Sha256, HashAlgorithm::Sha512] {
            let kdf = Kdf::create_iter_salted_s2k(algorithm, 8).unwrap();
            let Kdf::IterSaltedS2k {
                salt_user,
                salt_admin: Some(salt_admin),
                initial_hash_user: Some(initial_user),
                initial_hash_admin: Some(initial_admin),
                ..
            } = &kdf
            else {
                panic!("Missing initial KDF hashes");
            };
            for (pw, salt, pin, initial) in [
                (Pw::User, salt_user, DEFAULT_USER_PIN, initial_user),
                (Pw::Admin, salt_admin, DEFAULT_ADMIN_PIN, initial_admin),
            ] {
                let input = [salt.as_slice(), pin.as_bytes()].concat();
                let expected = match algorithm {
                    HashAlgorithm::Sha256 => sha2::Sha256::digest(&input).to_vec(),
                    HashAlgorithm::Sha512 => sha2::Sha512::digest(&input).to_vec(),
                };
                assert_eq!(*initial, expected);
                assert_eq!(kdf.process(pw, pin).as_slice(), expected);
            }
        }
    }

    #[test]
    fn test_kdf_iter_salted_s2k_roundtrip() {
        let kdf = Kdf::IterSaltedS2k {
            hash_algorithm: HashAlgorithm::Sha256,
            iteration_count: 0x780000,
            salt_user: vec![1, 2, 3, 4, 5, 6, 7, 8],
            salt_reset: Some(vec![9, 10, 11, 12, 13, 14, 15, 16]),
            salt_admin: Some(vec![17, 18, 19, 20, 21, 22, 23, 24]),
            initial_hash_user: None,
            initial_hash_admin: None,
        };
        let bytes = kdf.to_bytes();
        let parsed = Kdf::parse(&bytes).unwrap();
        assert_eq!(parsed, kdf);
    }

    #[test]
    fn test_parse_fingerprints() {
        let mut data = vec![0u8; 80]; // 4 * 20 bytes
        data[0] = 0xAA; // SIG fingerprint first byte
        data[20] = 0xBB; // DEC fingerprint first byte
        let fps = parse_fingerprints(&data);
        assert_eq!(fps[&KeyRef::Sig][0], 0xAA);
        assert_eq!(fps[&KeyRef::Dec][0], 0xBB);
        assert_eq!(fps.len(), 4);
    }

    #[test]
    fn test_parse_timestamps() {
        let data = [
            0x00, 0x00, 0x00, 0x01, // SIG = 1
            0x00, 0x00, 0x00, 0x02, // DEC = 2
            0x00, 0x00, 0x00, 0x03, // AUT = 3
            0x00, 0x00, 0x00, 0x04, // ATT = 4
        ];
        let ts = parse_timestamps(&data);
        assert_eq!(ts[&KeyRef::Sig], 1);
        assert_eq!(ts[&KeyRef::Dec], 2);
        assert_eq!(ts[&KeyRef::Aut], 3);
        assert_eq!(ts[&KeyRef::Att], 4);
    }

    #[test]
    fn test_parse_key_information() {
        let data = [0x01, 0x01, 0x02, 0x02, 0x03, 0x00];
        let ki = parse_key_information(&data);
        assert_eq!(ki[&KeyRef::Sig], KeyStatus::Generated);
        assert_eq!(ki[&KeyRef::Dec], KeyStatus::Imported);
        assert_eq!(ki[&KeyRef::Aut], KeyStatus::None);
    }

    #[test]
    fn test_build_private_key_template_ec() {
        use crate::keys::{EcCurve, EcPrivateKey};
        let key =
            PrivateKey::Ec(EcPrivateKey::new(EcCurve::P256, vec![0x01, 0x02, 0x03], None).unwrap());
        let template = build_private_key_template(KeyRef::Sig, &key).unwrap();
        // Should start with 0x4D tag
        assert_eq!(template[0], 0x4D);
    }

    #[test]
    fn test_build_private_key_template_rsa() {
        use crate::keys::{RsaKeySize, RsaPrivateKey};
        let key = PrivateKey::Rsa(
            RsaPrivateKey::new(
                RsaKeySize::Rsa2048,
                vec![0xFF; 256],
                vec![0x01, 0x00, 0x01],
                vec![0xAA; 128],
                vec![0xBB; 128],
                vec![0xDD; 128],
                vec![0xEE; 128],
                vec![0xCC; 128],
            )
            .unwrap(),
        );
        let template = build_private_key_template(KeyRef::Sig, &key).unwrap();
        assert_eq!(template[0], 0x4D);
    }

    #[test]
    fn test_build_private_key_template_rsa_crt() {
        use crate::keys::{RsaKeySize, RsaPrivateKey};
        let key = PrivateKey::Rsa(
            RsaPrivateKey::new(
                RsaKeySize::Rsa2048,
                vec![0xFF; 256],
                vec![0x01, 0x00, 0x01],
                vec![0xAA; 128],
                vec![0xBB; 128],
                vec![0xDD; 128],
                vec![0xEE; 128],
                vec![0xCC; 128],
            )
            .unwrap(),
        );
        let template = build_private_key_template(KeyRef::Sig, &key).unwrap();
        assert_eq!(template[0], 0x4D);
        // Parse outer TLV to verify structure
        let (tag, val_off, val_len, _) = tlv_parse(&template, 0).unwrap();
        assert_eq!(tag, 0x4D);
        let inner = &template[val_off..val_off + val_len];
        // Inner starts with CRT (B6 00)
        assert!(inner.starts_with(&[0xB6, 0x00]));
    }

    #[test]
    fn test_pad_message_eddsa_no_hash() {
        let attrs = AlgorithmAttributes::Ec(EcAttributes {
            algorithm_id: EC_ALG_EDDSA,
            oid: OpenPgpCurve::Ed25519.oid().as_bytes().to_vec(),
            import_format: EcImportFormat::Standard,
        });
        let msg = b"hello world";
        let padded = pad_message(&attrs, msg, SignHashAlgorithm::None).unwrap();
        assert_eq!(padded, msg);
    }

    #[test]
    fn test_pad_message_rsa_sha256() {
        let attrs = AlgorithmAttributes::Rsa(RsaAttributes::create(
            RsaKeySize::Rsa2048,
            RsaImportFormat::Standard,
        ));
        let msg = b"test message";
        let padded = pad_message(&attrs, msg, SignHashAlgorithm::Sha256).unwrap();
        // DigestInfo header (19 bytes) + SHA256 hash (32 bytes) = 51 bytes
        assert_eq!(padded.len(), 19 + 32);
        assert!(padded.starts_with(&[
            0x30, 0x31, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
            0x01, 0x05, 0x00, 0x04, 0x20
        ]));
        let prehashed = pad_message(
            &attrs,
            &padded[19..],
            SignHashAlgorithm::Prehashed(PrehashAlgorithm::Sha256),
        )
        .unwrap();
        assert_eq!(prehashed, padded);
        let sha1 = pad_message(&attrs, msg, SignHashAlgorithm::Sha1).unwrap();
        assert_eq!(sha1.len(), 15 + 20);
        assert!(pad_message(&attrs, msg, SignHashAlgorithm::None).is_err());
    }

    #[test]
    fn test_pad_message_ec_sha256() {
        let attrs = AlgorithmAttributes::Ec(EcAttributes {
            algorithm_id: EC_ALG_ECDSA,
            oid: OpenPgpCurve::Ed25519.oid().as_bytes().to_vec(), // any valid OID; test only checks hash output
            import_format: EcImportFormat::Standard,
        });
        let msg = b"test message";
        let padded = pad_message(&attrs, msg, SignHashAlgorithm::Sha256).unwrap();
        // EC just returns the hash, SHA256 = 32 bytes
        assert_eq!(padded.len(), 32);
    }

    #[test]
    fn test_pad_message_prehashed_digest_lengths() {
        let attributes = [
            AlgorithmAttributes::Rsa(RsaAttributes::create(
                RsaKeySize::Rsa2048,
                RsaImportFormat::Standard,
            )),
            AlgorithmAttributes::Ec(
                EcAttributes::create(KeyRef::Sig, &OpenPgpCurve::P256).unwrap(),
            ),
        ];
        for attributes in attributes {
            for (algorithm, length) in [
                (PrehashAlgorithm::Sha1, 20),
                (PrehashAlgorithm::Sha256, 32),
                (PrehashAlgorithm::Sha384, 48),
                (PrehashAlgorithm::Sha512, 64),
            ] {
                for size in [0, length - 1, length, length + 1] {
                    let digest = vec![0x11; size];
                    let result = pad_message(
                        &attributes,
                        &digest,
                        SignHashAlgorithm::Prehashed(algorithm),
                    );
                    if size == length {
                        let padded = result.unwrap();
                        assert!(padded.ends_with(&digest));
                        if matches!(attributes, AlgorithmAttributes::Ec(_)) {
                            assert_eq!(padded, digest);
                        }
                    } else {
                        assert!(matches!(
                            result,
                            Err(OpenPgpError::InvalidData(message))
                                if message == format!(
                                    "Prehashed input must contain exactly {length} bytes."
                                )
                        ));
                    }
                }
            }
        }
    }

    #[test]
    fn test_pad_message_preserves_raw_ec_and_eddsa_input() {
        let message = b"not a digest";
        for curve in [OpenPgpCurve::P256, OpenPgpCurve::Ed25519] {
            let attributes =
                AlgorithmAttributes::Ec(EcAttributes::create(KeyRef::Sig, &curve).unwrap());
            assert_eq!(
                pad_message(&attributes, message, SignHashAlgorithm::None).unwrap(),
                message
            );
            if matches!(curve, OpenPgpCurve::Ed25519) {
                assert_eq!(
                    pad_message(
                        &attributes,
                        message,
                        SignHashAlgorithm::Prehashed(PrehashAlgorithm::Sha256)
                    )
                    .unwrap(),
                    message
                );
            }
        }
    }

    #[test]
    fn test_require_version_ok() {
        assert!(require_version(Version(5, 3, 0), Version(5, 2, 0), "test").is_ok());
    }

    #[test]
    fn test_require_version_fail() {
        let err = require_version(Version(4, 1, 0), Version(5, 2, 0), "test").unwrap_err();
        match err {
            OpenPgpError::NotSupported(msg) => assert!(msg.contains("test")),
            _ => panic!("Expected NotSupported"),
        }
    }

    #[test]
    fn test_bytes2int() {
        assert_eq!(bytes2int(&[]), 0);
        assert_eq!(bytes2int(&[0x01]), 1);
        assert_eq!(bytes2int(&[0x01, 0x00]), 256);
        assert_eq!(bytes2int(&[0xFF, 0xFF]), 65535);
    }

    #[test]
    fn test_key_ref_all() {
        assert_eq!(KeyRef::ALL.len(), 4);
        assert_eq!(KeyRef::ALL[0], KeyRef::Sig);
        assert_eq!(KeyRef::ALL[3], KeyRef::Att);
    }

    #[test]
    fn test_pin_policy_from_u8() {
        assert_eq!(PinPolicy::from_u8(0x00), PinPolicy::Always);
        assert_eq!(PinPolicy::from_u8(0x01), PinPolicy::Once);
        assert_eq!(PinPolicy::from_u8(0xFF), PinPolicy::Always); // fallback
    }

    #[test]
    fn test_key_ref_associated_dos() {
        assert_eq!(
            KeyRef::Sig.algorithm_attributes_do() as u16,
            Do::AlgorithmAttributesSig as u16
        );
        assert_eq!(KeyRef::Dec.uif_do() as u16, Do::UifDec as u16);
        assert_eq!(
            KeyRef::Aut.generation_time_do() as u16,
            Do::GenerationTimeAut as u16
        );
        assert_eq!(
            KeyRef::Att.fingerprint_do() as u16,
            Do::FingerprintAtt as u16
        );
    }
}