summaryrefslogtreecommitdiffstats
path: root/grub-core/lib/libgcrypt/cipher/pubkey.c
blob: ca087ad75b9310d2e99d1d51cd0cffe7957cab43 (plain)
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
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
/* pubkey.c  -	pubkey dispatcher
 * Copyright (C) 1998, 1999, 2000, 2002, 2003, 2005,
 *               2007, 2008, 2011 Free Software Foundation, Inc.
 *
 * This file is part of Libgcrypt.
 *
 * Libgcrypt is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser general Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * Libgcrypt is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "g10lib.h"
#include "mpi.h"
#include "cipher.h"
#include "ath.h"


static gcry_err_code_t pubkey_decrypt (int algo, gcry_mpi_t *result,
                                       gcry_mpi_t *data, gcry_mpi_t *skey,
                                       int flags);
static gcry_err_code_t pubkey_sign (int algo, gcry_mpi_t *resarr,
                                    gcry_mpi_t hash, gcry_mpi_t *skey);
static gcry_err_code_t pubkey_verify (int algo, gcry_mpi_t hash,
                                      gcry_mpi_t *data, gcry_mpi_t *pkey,
				     int (*cmp) (void *, gcry_mpi_t),
                                      void *opaque);


/* A dummy extraspec so that we do not need to tests the extraspec
   field from the module specification against NULL and instead
   directly test the respective fields of extraspecs.  */
static pk_extra_spec_t dummy_extra_spec;


/* This is the list of the default public-key ciphers included in
   libgcrypt.  FIPS_ALLOWED indicated whether the algorithm is used in
   FIPS mode. */
static struct pubkey_table_entry
{
  gcry_pk_spec_t *pubkey;
  pk_extra_spec_t *extraspec;
  unsigned int algorithm;
  int fips_allowed;
} pubkey_table[] =
  {
#if USE_RSA
    { &_gcry_pubkey_spec_rsa,
      &_gcry_pubkey_extraspec_rsa,   GCRY_PK_RSA, 1},
#endif
#if USE_ELGAMAL
    { &_gcry_pubkey_spec_elg,
      &_gcry_pubkey_extraspec_elg,    GCRY_PK_ELG   },
    { &_gcry_pubkey_spec_elg,
      &_gcry_pubkey_extraspec_elg,    GCRY_PK_ELG_E },
#endif
#if USE_DSA
    { &_gcry_pubkey_spec_dsa,
      &_gcry_pubkey_extraspec_dsa,   GCRY_PK_DSA, 1   },
#endif
#if USE_ECC
    { &_gcry_pubkey_spec_ecdsa,
      &_gcry_pubkey_extraspec_ecdsa, GCRY_PK_ECDSA, 0 },
    { &_gcry_pubkey_spec_ecdh,
      &_gcry_pubkey_extraspec_ecdsa, GCRY_PK_ECDH, 0 },
#endif
    { NULL, 0 },
  };

/* List of registered ciphers.  */
static gcry_module_t pubkeys_registered;

/* This is the lock protecting PUBKEYS_REGISTERED.  */
static ath_mutex_t pubkeys_registered_lock = ATH_MUTEX_INITIALIZER;;

/* Flag to check whether the default pubkeys have already been
   registered.  */
static int default_pubkeys_registered;

/* Convenient macro for registering the default digests.  */
#define REGISTER_DEFAULT_PUBKEYS                   \
  do                                               \
    {                                              \
      ath_mutex_lock (&pubkeys_registered_lock);   \
      if (! default_pubkeys_registered)            \
        {                                          \
          pk_register_default ();                  \
          default_pubkeys_registered = 1;          \
        }                                          \
      ath_mutex_unlock (&pubkeys_registered_lock); \
    }                                              \
  while (0)

/* These dummy functions are used in case a cipher implementation
   refuses to provide it's own functions.  */

static gcry_err_code_t
dummy_generate (int algorithm, unsigned int nbits, unsigned long dummy,
                gcry_mpi_t *skey, gcry_mpi_t **retfactors)
{
  (void)algorithm;
  (void)nbits;
  (void)dummy;
  (void)skey;
  (void)retfactors;
  fips_signal_error ("using dummy public key function");
  return GPG_ERR_NOT_IMPLEMENTED;
}

static gcry_err_code_t
dummy_check_secret_key (int algorithm, gcry_mpi_t *skey)
{
  (void)algorithm;
  (void)skey;
  fips_signal_error ("using dummy public key function");
  return GPG_ERR_NOT_IMPLEMENTED;
}

static gcry_err_code_t
dummy_encrypt (int algorithm, gcry_mpi_t *resarr, gcry_mpi_t data,
               gcry_mpi_t *pkey, int flags)
{
  (void)algorithm;
  (void)resarr;
  (void)data;
  (void)pkey;
  (void)flags;
  fips_signal_error ("using dummy public key function");
  return GPG_ERR_NOT_IMPLEMENTED;
}

static gcry_err_code_t
dummy_decrypt (int algorithm, gcry_mpi_t *result, gcry_mpi_t *data,
               gcry_mpi_t *skey, int flags)
{
  (void)algorithm;
  (void)result;
  (void)data;
  (void)skey;
  (void)flags;
  fips_signal_error ("using dummy public key function");
  return GPG_ERR_NOT_IMPLEMENTED;
}

static gcry_err_code_t
dummy_sign (int algorithm, gcry_mpi_t *resarr, gcry_mpi_t data,
            gcry_mpi_t *skey)
{
  (void)algorithm;
  (void)resarr;
  (void)data;
  (void)skey;
  fips_signal_error ("using dummy public key function");
  return GPG_ERR_NOT_IMPLEMENTED;
}

static gcry_err_code_t
dummy_verify (int algorithm, gcry_mpi_t hash, gcry_mpi_t *data,
              gcry_mpi_t *pkey,
	      int (*cmp) (void *, gcry_mpi_t), void *opaquev)
{
  (void)algorithm;
  (void)hash;
  (void)data;
  (void)pkey;
  (void)cmp;
  (void)opaquev;
  fips_signal_error ("using dummy public key function");
  return GPG_ERR_NOT_IMPLEMENTED;
}

static unsigned
dummy_get_nbits (int algorithm, gcry_mpi_t *pkey)
{
  (void)algorithm;
  (void)pkey;
  fips_signal_error ("using dummy public key function");
  return 0;
}

/* Internal function.  Register all the pubkeys included in
   PUBKEY_TABLE.  Returns zero on success or an error code.  */
static void
pk_register_default (void)
{
  gcry_err_code_t err = 0;
  int i;

  for (i = 0; (! err) && pubkey_table[i].pubkey; i++)
    {
#define pubkey_use_dummy(func)                       \
      if (! pubkey_table[i].pubkey->func)            \
	pubkey_table[i].pubkey->func = dummy_##func;

      pubkey_use_dummy (generate);
      pubkey_use_dummy (check_secret_key);
      pubkey_use_dummy (encrypt);
      pubkey_use_dummy (decrypt);
      pubkey_use_dummy (sign);
      pubkey_use_dummy (verify);
      pubkey_use_dummy (get_nbits);
#undef pubkey_use_dummy

      err = _gcry_module_add (&pubkeys_registered,
			      pubkey_table[i].algorithm,
			      (void *) pubkey_table[i].pubkey,
			      (void *) pubkey_table[i].extraspec,
                              NULL);
    }

  if (err)
    BUG ();
}

/* Internal callback function.  Used via _gcry_module_lookup.  */
static int
gcry_pk_lookup_func_name (void *spec, void *data)
{
  gcry_pk_spec_t *pubkey = (gcry_pk_spec_t *) spec;
  char *name = (char *) data;
  const char **aliases = pubkey->aliases;
  int ret = stricmp (name, pubkey->name);

  while (ret && *aliases)
    ret = stricmp (name, *aliases++);

  return ! ret;
}

/* Internal function.  Lookup a pubkey entry by it's name.  */
static gcry_module_t
gcry_pk_lookup_name (const char *name)
{
  gcry_module_t pubkey;

  pubkey = _gcry_module_lookup (pubkeys_registered, (void *) name,
				gcry_pk_lookup_func_name);

  return pubkey;
}

/* Register a new pubkey module whose specification can be found in
   PUBKEY.  On success, a new algorithm ID is stored in ALGORITHM_ID
   and a pointer representhing this module is stored in MODULE.  */
gcry_error_t
_gcry_pk_register (gcry_pk_spec_t *pubkey,
                   pk_extra_spec_t *extraspec,
                   unsigned int *algorithm_id,
                   gcry_module_t *module)
{
  gcry_err_code_t err = GPG_ERR_NO_ERROR;
  gcry_module_t mod;

  /* We do not support module loading in fips mode.  */
  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  ath_mutex_lock (&pubkeys_registered_lock);
  err = _gcry_module_add (&pubkeys_registered, 0,
			  (void *) pubkey,
			  (void *)(extraspec? extraspec : &dummy_extra_spec),
                          &mod);
  ath_mutex_unlock (&pubkeys_registered_lock);

  if (! err)
    {
      *module = mod;
      *algorithm_id = mod->mod_id;
    }

  return err;
}

/* Unregister the pubkey identified by ID, which must have been
   registered with gcry_pk_register.  */
void
gcry_pk_unregister (gcry_module_t module)
{
  ath_mutex_lock (&pubkeys_registered_lock);
  _gcry_module_release (module);
  ath_mutex_unlock (&pubkeys_registered_lock);
}

static void
release_mpi_array (gcry_mpi_t *array)
{
  for (; *array; array++)
    {
      mpi_free(*array);
      *array = NULL;
    }
}

/****************
 * Map a string to the pubkey algo
 */
int
gcry_pk_map_name (const char *string)
{
  gcry_module_t pubkey;
  int algorithm = 0;

  if (!string)
    return 0;

  REGISTER_DEFAULT_PUBKEYS;

  ath_mutex_lock (&pubkeys_registered_lock);
  pubkey = gcry_pk_lookup_name (string);
  if (pubkey)
    {
      algorithm = pubkey->mod_id;
      _gcry_module_release (pubkey);
    }
  ath_mutex_unlock (&pubkeys_registered_lock);

  return algorithm;
}


/* Map the public key algorithm whose ID is contained in ALGORITHM to
   a string representation of the algorithm name.  For unknown
   algorithm IDs this functions returns "?". */
const char *
gcry_pk_algo_name (int algorithm)
{
  gcry_module_t pubkey;
  const char *name;

  REGISTER_DEFAULT_PUBKEYS;

  ath_mutex_lock (&pubkeys_registered_lock);
  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (pubkey)
    {
      name = ((gcry_pk_spec_t *) pubkey->spec)->name;
      _gcry_module_release (pubkey);
    }
  else
    name = "?";
  ath_mutex_unlock (&pubkeys_registered_lock);

  return name;
}


/* A special version of gcry_pk_algo name to return the first aliased
   name of the algorithm.  This is required to adhere to the spki
   specs where the algorithm names are lowercase. */
const char *
_gcry_pk_aliased_algo_name (int algorithm)
{
  const char *name = NULL;
  gcry_module_t module;

  REGISTER_DEFAULT_PUBKEYS;

  ath_mutex_lock (&pubkeys_registered_lock);
  module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (module)
    {
      gcry_pk_spec_t *pubkey = (gcry_pk_spec_t *) module->spec;

      name = pubkey->aliases? *pubkey->aliases : NULL;
      if (!name || !*name)
        name = pubkey->name;
      _gcry_module_release (module);
    }
  ath_mutex_unlock (&pubkeys_registered_lock);

  return name;
}


static void
disable_pubkey_algo (int algorithm)
{
  gcry_module_t pubkey;

  ath_mutex_lock (&pubkeys_registered_lock);
  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (pubkey)
    {
      if (! (pubkey-> flags & FLAG_MODULE_DISABLED))
	pubkey->flags |= FLAG_MODULE_DISABLED;
      _gcry_module_release (pubkey);
    }
  ath_mutex_unlock (&pubkeys_registered_lock);
}


/****************
 * A USE of 0 means: don't care.
 */
static gcry_err_code_t
check_pubkey_algo (int algorithm, unsigned use)
{
  gcry_err_code_t err = GPG_ERR_NO_ERROR;
  gcry_pk_spec_t *pubkey;
  gcry_module_t module;

  REGISTER_DEFAULT_PUBKEYS;

  ath_mutex_lock (&pubkeys_registered_lock);
  module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (module)
    {
      pubkey = (gcry_pk_spec_t *) module->spec;

      if (((use & GCRY_PK_USAGE_SIGN)
	   && (! (pubkey->use & GCRY_PK_USAGE_SIGN)))
	  || ((use & GCRY_PK_USAGE_ENCR)
	      && (! (pubkey->use & GCRY_PK_USAGE_ENCR))))
	err = GPG_ERR_WRONG_PUBKEY_ALGO;
      else if (module->flags & FLAG_MODULE_DISABLED)
	err = GPG_ERR_PUBKEY_ALGO;
      _gcry_module_release (module);
    }
  else
    err = GPG_ERR_PUBKEY_ALGO;
  ath_mutex_unlock (&pubkeys_registered_lock);

  return err;
}


/****************
 * Return the number of public key material numbers
 */
static int
pubkey_get_npkey (int algorithm)
{
  gcry_module_t pubkey;
  int npkey = 0;

  REGISTER_DEFAULT_PUBKEYS;

  ath_mutex_lock (&pubkeys_registered_lock);
  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (pubkey)
    {
      npkey = strlen (((gcry_pk_spec_t *) pubkey->spec)->elements_pkey);
      _gcry_module_release (pubkey);
    }
  ath_mutex_unlock (&pubkeys_registered_lock);

  return npkey;
}

/****************
 * Return the number of secret key material numbers
 */
static int
pubkey_get_nskey (int algorithm)
{
  gcry_module_t pubkey;
  int nskey = 0;

  REGISTER_DEFAULT_PUBKEYS;

  ath_mutex_lock (&pubkeys_registered_lock);
  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (pubkey)
    {
      nskey = strlen (((gcry_pk_spec_t *) pubkey->spec)->elements_skey);
      _gcry_module_release (pubkey);
    }
  ath_mutex_unlock (&pubkeys_registered_lock);

  return nskey;
}

/****************
 * Return the number of signature material numbers
 */
static int
pubkey_get_nsig (int algorithm)
{
  gcry_module_t pubkey;
  int nsig = 0;

  REGISTER_DEFAULT_PUBKEYS;

  ath_mutex_lock (&pubkeys_registered_lock);
  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (pubkey)
    {
      nsig = strlen (((gcry_pk_spec_t *) pubkey->spec)->elements_sig);
      _gcry_module_release (pubkey);
    }
  ath_mutex_unlock (&pubkeys_registered_lock);

  return nsig;
}

/****************
 * Return the number of encryption material numbers
 */
static int
pubkey_get_nenc (int algorithm)
{
  gcry_module_t pubkey;
  int nenc = 0;

  REGISTER_DEFAULT_PUBKEYS;

  ath_mutex_lock (&pubkeys_registered_lock);
  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (pubkey)
    {
      nenc = strlen (((gcry_pk_spec_t *) pubkey->spec)->elements_enc);
      _gcry_module_release (pubkey);
    }
  ath_mutex_unlock (&pubkeys_registered_lock);

  return nenc;
}


/* Generate a new public key with algorithm ALGORITHM of size NBITS
   and return it at SKEY.  USE_E depends on the ALGORITHM.  GENPARMS
   is passed to the algorithm module if it features an extended
   generation function.  RETFACTOR is used by some algorithms to
   return certain additional information which are in general not
   required.

   The function returns the error code number or 0 on success. */
static gcry_err_code_t
pubkey_generate (int algorithm,
                 unsigned int nbits,
                 unsigned long use_e,
                 gcry_sexp_t genparms,
                 gcry_mpi_t *skey, gcry_mpi_t **retfactors,
                 gcry_sexp_t *r_extrainfo)
{
  gcry_err_code_t ec = GPG_ERR_PUBKEY_ALGO;
  gcry_module_t pubkey;

  REGISTER_DEFAULT_PUBKEYS;

  ath_mutex_lock (&pubkeys_registered_lock);
  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (pubkey)
    {
      pk_extra_spec_t *extraspec = pubkey->extraspec;

      if (extraspec && extraspec->ext_generate)
        {
          /* Use the extended generate function.  */
          ec = extraspec->ext_generate
            (algorithm, nbits, use_e, genparms, skey, retfactors, r_extrainfo);
        }
      else
        {
          /* Use the standard generate function.  */
          ec = ((gcry_pk_spec_t *) pubkey->spec)->generate
            (algorithm, nbits, use_e, skey, retfactors);
        }
      _gcry_module_release (pubkey);
    }
  ath_mutex_unlock (&pubkeys_registered_lock);

  return ec;
}


static gcry_err_code_t
pubkey_check_secret_key (int algorithm, gcry_mpi_t *skey)
{
  gcry_err_code_t err = GPG_ERR_PUBKEY_ALGO;
  gcry_module_t pubkey;

  REGISTER_DEFAULT_PUBKEYS;

  ath_mutex_lock (&pubkeys_registered_lock);
  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (pubkey)
    {
      err = ((gcry_pk_spec_t *) pubkey->spec)->check_secret_key
        (algorithm, skey);
      _gcry_module_release (pubkey);
    }
  ath_mutex_unlock (&pubkeys_registered_lock);

  return err;
}


/****************
 * This is the interface to the public key encryption.  Encrypt DATA
 * with PKEY and put it into RESARR which should be an array of MPIs
 * of size PUBKEY_MAX_NENC (or less if the algorithm allows this -
 * check with pubkey_get_nenc() )
 */
static gcry_err_code_t
pubkey_encrypt (int algorithm, gcry_mpi_t *resarr, gcry_mpi_t data,
                gcry_mpi_t *pkey, int flags)
{
  gcry_pk_spec_t *pubkey;
  gcry_module_t module;
  gcry_err_code_t rc;
  int i;

  /* Note: In fips mode DBG_CIPHER will enver evaluate to true but as
     an extra failsafe protection we explicitly test for fips mode
     here. */
  if (DBG_CIPHER && !fips_mode ())
    {
      log_debug ("pubkey_encrypt: algo=%d\n", algorithm);
      for(i = 0; i < pubkey_get_npkey (algorithm); i++)
	log_mpidump ("  pkey:", pkey[i]);
      log_mpidump ("  data:", data);
    }

  ath_mutex_lock (&pubkeys_registered_lock);
  module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (module)
    {
      pubkey = (gcry_pk_spec_t *) module->spec;
      rc = pubkey->encrypt (algorithm, resarr, data, pkey, flags);
      _gcry_module_release (module);
      goto ready;
    }
  rc = GPG_ERR_PUBKEY_ALGO;

 ready:
  ath_mutex_unlock (&pubkeys_registered_lock);

  if (!rc && DBG_CIPHER && !fips_mode ())
    {
      for(i = 0; i < pubkey_get_nenc (algorithm); i++)
	log_mpidump("  encr:", resarr[i] );
    }
  return rc;
}


/****************
 * This is the interface to the public key decryption.
 * ALGO gives the algorithm to use and this implicitly determines
 * the size of the arrays.
 * result is a pointer to a mpi variable which will receive a
 * newly allocated mpi or NULL in case of an error.
 */
static gcry_err_code_t
pubkey_decrypt (int algorithm, gcry_mpi_t *result, gcry_mpi_t *data,
                gcry_mpi_t *skey, int flags)
{
  gcry_pk_spec_t *pubkey;
  gcry_module_t module;
  gcry_err_code_t rc;
  int i;

  *result = NULL; /* so the caller can always do a mpi_free */
  if (DBG_CIPHER && !fips_mode ())
    {
      log_debug ("pubkey_decrypt: algo=%d\n", algorithm);
      for(i = 0; i < pubkey_get_nskey (algorithm); i++)
	log_mpidump ("  skey:", skey[i]);
      for(i = 0; i < pubkey_get_nenc (algorithm); i++)
	log_mpidump ("  data:", data[i]);
    }

  ath_mutex_lock (&pubkeys_registered_lock);
  module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (module)
    {
      pubkey = (gcry_pk_spec_t *) module->spec;
      rc = pubkey->decrypt (algorithm, result, data, skey, flags);
      _gcry_module_release (module);
      goto ready;
    }

  rc = GPG_ERR_PUBKEY_ALGO;

 ready:
  ath_mutex_unlock (&pubkeys_registered_lock);

  if (!rc && DBG_CIPHER && !fips_mode ())
    log_mpidump (" plain:", *result);

  return rc;
}


/****************
 * This is the interface to the public key signing.
 * Sign data with skey and put the result into resarr which
 * should be an array of MPIs of size PUBKEY_MAX_NSIG (or less if the
 * algorithm allows this - check with pubkey_get_nsig() )
 */
static gcry_err_code_t
pubkey_sign (int algorithm, gcry_mpi_t *resarr, gcry_mpi_t data,
             gcry_mpi_t *skey)
{
  gcry_pk_spec_t *pubkey;
  gcry_module_t module;
  gcry_err_code_t rc;
  int i;

  if (DBG_CIPHER && !fips_mode ())
    {
      log_debug ("pubkey_sign: algo=%d\n", algorithm);
      for(i = 0; i < pubkey_get_nskey (algorithm); i++)
	log_mpidump ("  skey:", skey[i]);
      log_mpidump("  data:", data );
    }

  ath_mutex_lock (&pubkeys_registered_lock);
  module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (module)
    {
      pubkey = (gcry_pk_spec_t *) module->spec;
      rc = pubkey->sign (algorithm, resarr, data, skey);
      _gcry_module_release (module);
      goto ready;
    }

  rc = GPG_ERR_PUBKEY_ALGO;

 ready:
  ath_mutex_unlock (&pubkeys_registered_lock);

  if (!rc && DBG_CIPHER && !fips_mode ())
    for (i = 0; i < pubkey_get_nsig (algorithm); i++)
      log_mpidump ("   sig:", resarr[i]);

  return rc;
}

/****************
 * Verify a public key signature.
 * Return 0 if the signature is good
 */
static gcry_err_code_t
pubkey_verify (int algorithm, gcry_mpi_t hash, gcry_mpi_t *data,
               gcry_mpi_t *pkey,
	       int (*cmp)(void *, gcry_mpi_t), void *opaquev)
{
  gcry_pk_spec_t *pubkey;
  gcry_module_t module;
  gcry_err_code_t rc;
  int i;

  if (DBG_CIPHER && !fips_mode ())
    {
      log_debug ("pubkey_verify: algo=%d\n", algorithm);
      for (i = 0; i < pubkey_get_npkey (algorithm); i++)
	log_mpidump ("  pkey", pkey[i]);
      for (i = 0; i < pubkey_get_nsig (algorithm); i++)
	log_mpidump ("   sig", data[i]);
      log_mpidump ("  hash", hash);
    }

  ath_mutex_lock (&pubkeys_registered_lock);
  module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (module)
    {
      pubkey = (gcry_pk_spec_t *) module->spec;
      rc = pubkey->verify (algorithm, hash, data, pkey, cmp, opaquev);
      _gcry_module_release (module);
      goto ready;
    }

  rc = GPG_ERR_PUBKEY_ALGO;

 ready:
  ath_mutex_unlock (&pubkeys_registered_lock);
  return rc;
}


/* Turn VALUE into an octet string and store it in an allocated buffer
   at R_FRAME or - if R_RAME is NULL - copy it into the caller
   provided buffer SPACE; either SPACE or R_FRAME may be used.  If
   SPACE if not NULL, the caller must provide a buffer of at least
   NBYTES.  If the resulting octet string is shorter than NBYTES pad
   it to the left with zeroes.  If VALUE does not fit into NBYTES
   return an error code.  */
static gpg_err_code_t
octet_string_from_mpi (unsigned char **r_frame, void *space,
                       gcry_mpi_t value, size_t nbytes)
{
  gpg_err_code_t rc;
  size_t nframe, noff, n;
  unsigned char *frame;

  if (!r_frame == !space)
    return GPG_ERR_INV_ARG;  /* Only one may be used.  */

  if (r_frame)
    *r_frame = NULL;

  rc = gcry_err_code (gcry_mpi_print (GCRYMPI_FMT_USG,
                                      NULL, 0, &nframe, value));
  if (rc)
    return rc;
  if (nframe > nbytes)
    return GPG_ERR_TOO_LARGE; /* Value too long to fit into NBYTES.  */

  noff = (nframe < nbytes)? nbytes - nframe : 0;
  n = nframe + noff;
  if (space)
    frame = space;
  else
    {
      frame = mpi_is_secure (value)? gcry_malloc_secure (n) : gcry_malloc (n);
      if (!frame)
        {
          rc = gpg_err_code_from_syserror ();
          return rc;
        }
    }
  if (noff)
    memset (frame, 0, noff);
  nframe += noff;
  rc = gcry_err_code (gcry_mpi_print (GCRYMPI_FMT_USG,
                                      frame+noff, nframe-noff, NULL, value));
  if (rc)
    {
      gcry_free (frame);
      return rc;
    }

  if (r_frame)
    *r_frame = frame;
  return 0;
}


/* Encode {VALUE,VALUELEN} for an NBITS keys using the pkcs#1 block
   type 2 padding.  On sucess the result is stored as a new MPI at
   R_RESULT.  On error the value at R_RESULT is undefined.

   If {RANDOM_OVERRIDE, RANDOM_OVERRIDE_LEN} is given it is used as
   the seed instead of using a random string for it.  This feature is
   only useful for regression tests.  Note that this value may not
   contain zero bytes.

   We encode the value in this way:

     0  2  RND(n bytes)  0  VALUE

   0   is a marker we unfortunately can't encode because we return an
       MPI which strips all leading zeroes.
   2   is the block type.
   RND are non-zero random bytes.

   (Note that OpenPGP includes the cipher algorithm and a checksum in
   VALUE; the caller needs to prepare the value accordingly.)
  */
static gcry_err_code_t
pkcs1_encode_for_encryption (gcry_mpi_t *r_result, unsigned int nbits,
			     const unsigned char *value, size_t valuelen,
                             const unsigned char *random_override,
                             size_t random_override_len)
{
  gcry_err_code_t rc = 0;
  gcry_error_t err;
  unsigned char *frame = NULL;
  size_t nframe = (nbits+7) / 8;
  int i;
  size_t n;
  unsigned char *p;

  if (valuelen + 7 > nframe || !nframe)
    {
      /* Can't encode a VALUELEN value in a NFRAME bytes frame.  */
      return GPG_ERR_TOO_SHORT; /* The key is too short.  */
    }

  if ( !(frame = gcry_malloc_secure (nframe)))
    return gpg_err_code_from_syserror ();

  n = 0;
  frame[n++] = 0;
  frame[n++] = 2; /* block type */
  i = nframe - 3 - valuelen;
  gcry_assert (i > 0);

  if (random_override)
    {
      int j;

      if (random_override_len != i)
        {
          gcry_free (frame);
          return GPG_ERR_INV_ARG;
        }
      /* Check that random does not include a zero byte.  */
      for (j=0; j < random_override_len; j++)
        if (!random_override[j])
          {
            gcry_free (frame);
            return GPG_ERR_INV_ARG;
          }
      memcpy (frame + n, random_override, random_override_len);
      n += random_override_len;
    }
  else
    {
      p = gcry_random_bytes_secure (i, GCRY_STRONG_RANDOM);
      /* Replace zero bytes by new values. */
      for (;;)
        {
          int j, k;
          unsigned char *pp;

          /* Count the zero bytes. */
          for (j=k=0; j < i; j++)
            {
              if (!p[j])
                k++;
            }
          if (!k)
            break; /* Okay: no (more) zero bytes. */

          k += k/128 + 3; /* Better get some more. */
          pp = gcry_random_bytes_secure (k, GCRY_STRONG_RANDOM);
          for (j=0; j < i && k; )
            {
              if (!p[j])
                p[j] = pp[--k];
              if (p[j])
                j++;
            }
          gcry_free (pp);
        }
      memcpy (frame+n, p, i);
      n += i;
      gcry_free (p);
    }

  frame[n++] = 0;
  memcpy (frame+n, value, valuelen);
  n += valuelen;
  gcry_assert (n == nframe);

  err = gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, n, &nframe);
  if (err)
    rc = gcry_err_code (err);
  else if (DBG_CIPHER)
    log_mpidump ("PKCS#1 block type 2 encoded data", *r_result);
  gcry_free (frame);

  return rc;
}


/* Decode a plaintext in VALUE assuming pkcs#1 block type 2 padding.
   NBITS is the size of the secret key.  On success the result is
   stored as a newly allocated buffer at R_RESULT and its valid length at
   R_RESULTLEN.  On error NULL is stored at R_RESULT.  */
static gcry_err_code_t
pkcs1_decode_for_encryption (unsigned char **r_result, size_t *r_resultlen,
                             unsigned int nbits, gcry_mpi_t value)
{
  gcry_error_t err;
  unsigned char *frame = NULL;
  size_t nframe = (nbits+7) / 8;
  size_t n;

  *r_result = NULL;

  if ( !(frame = gcry_malloc_secure (nframe)))
    return gpg_err_code_from_syserror ();

  err = gcry_mpi_print (GCRYMPI_FMT_USG, frame, nframe, &n, value);
  if (err)
    {
      gcry_free (frame);
      return gcry_err_code (err);
    }

  nframe = n; /* Set NFRAME to the actual length.  */

  /* FRAME = 0x00 || 0x02 || PS || 0x00 || M

     pkcs#1 requires that the first byte is zero.  Our MPIs usually
     strip leading zero bytes; thus we are not able to detect them.
     However due to the way gcry_mpi_print is implemented we may see
     leading zero bytes nevertheless.  We handle this by making the
     first zero byte optional.  */
  if (nframe < 4)
    {
      gcry_free (frame);
      return GPG_ERR_ENCODING_PROBLEM;  /* Too short.  */
    }
  n = 0;
  if (!frame[0])
    n++;
  if (frame[n++] != 0x02)
    {
      gcry_free (frame);
      return GPG_ERR_ENCODING_PROBLEM;  /* Wrong block type.  */
    }

  /* Skip the non-zero random bytes and the terminating zero byte.  */
  for (; n < nframe && frame[n] != 0x00; n++)
    ;
  if (n+1 >= nframe)
    {
      gcry_free (frame);
      return GPG_ERR_ENCODING_PROBLEM; /* No zero byte.  */
    }
  n++; /* Skip the zero byte.  */

  /* To avoid an extra allocation we reuse the frame buffer.  The only
     caller of this function will anyway free the result soon.  */
  memmove (frame, frame + n, nframe - n);
  *r_result = frame;
  *r_resultlen = nframe - n;

  if (DBG_CIPHER)
    log_printhex ("value extracted from PKCS#1 block type 2 encoded data:",
                  *r_result, *r_resultlen);

  return 0;
}


/* Encode {VALUE,VALUELEN} for an NBITS keys and hash algorith ALGO
   using the pkcs#1 block type 1 padding.  On success the result is
   stored as a new MPI at R_RESULT.  On error the value at R_RESULT is
   undefined.

   We encode the value in this way:

     0  1  PAD(n bytes)  0  ASN(asnlen bytes) VALUE(valuelen bytes)

   0   is a marker we unfortunately can't encode because we return an
       MPI which strips all leading zeroes.
   1   is the block type.
   PAD consists of 0xff bytes.
   0   marks the end of the padding.
   ASN is the DER encoding of the hash algorithm; along with the VALUE
       it yields a valid DER encoding.

   (Note that PGP prior to version 2.3 encoded the message digest as:
      0   1   MD(16 bytes)   0   PAD(n bytes)   1
    The MD is always 16 bytes here because it's always MD5.  GnuPG
    does not not support pre-v2.3 signatures, but I'm including this
    comment so the information is easily found if needed.)
*/
static gcry_err_code_t
pkcs1_encode_for_signature (gcry_mpi_t *r_result, unsigned int nbits,
			    const unsigned char *value, size_t valuelen,
			    int algo)
{
  gcry_err_code_t rc = 0;
  gcry_error_t err;
  byte asn[100];
  byte *frame = NULL;
  size_t nframe = (nbits+7) / 8;
  int i;
  size_t n;
  size_t asnlen, dlen;

  asnlen = DIM(asn);
  dlen = gcry_md_get_algo_dlen (algo);

  if (gcry_md_algo_info (algo, GCRYCTL_GET_ASNOID, asn, &asnlen))
    {
      /* We don't have yet all of the above algorithms.  */
      return GPG_ERR_NOT_IMPLEMENTED;
    }

  if ( valuelen != dlen )
    {
      /* Hash value does not match the length of digest for
         the given algorithm.  */
      return GPG_ERR_CONFLICT;
    }

  if ( !dlen || dlen + asnlen + 4 > nframe)
    {
      /* Can't encode an DLEN byte digest MD into an NFRAME byte
         frame.  */
      return GPG_ERR_TOO_SHORT;
    }

  if ( !(frame = gcry_malloc (nframe)) )
    return gpg_err_code_from_syserror ();

  /* Assemble the pkcs#1 block type 1. */
  n = 0;
  frame[n++] = 0;
  frame[n++] = 1; /* block type */
  i = nframe - valuelen - asnlen - 3 ;
  gcry_assert (i > 1);
  memset (frame+n, 0xff, i );
  n += i;
  frame[n++] = 0;
  memcpy (frame+n, asn, asnlen);
  n += asnlen;
  memcpy (frame+n, value, valuelen );
  n += valuelen;
  gcry_assert (n == nframe);

  /* Convert it into an MPI. */
  err = gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, n, &nframe);
  if (err)
    rc = gcry_err_code (err);
  else if (DBG_CIPHER)
    log_mpidump ("PKCS#1 block type 1 encoded data", *r_result);
  gcry_free (frame);

  return rc;
}


/* Mask generation function for OAEP.  See RFC-3447 B.2.1.  */
static gcry_err_code_t
mgf1 (unsigned char *output, size_t outlen, unsigned char *seed, size_t seedlen,
      int algo)
{
  size_t dlen, nbytes, n;
  int idx;
  gcry_md_hd_t hd;
  gcry_error_t err;

  err = gcry_md_open (&hd, algo, 0);
  if (err)
    return gpg_err_code (err);

  dlen = gcry_md_get_algo_dlen (algo);

  /* We skip step 1 which would be assert(OUTLEN <= 2^32).  The loop
     in step 3 is merged with step 4 by concatenating no more octets
     than what would fit into OUTPUT.  The ceiling for the counter IDX
     is implemented indirectly.  */
  nbytes = 0;  /* Step 2.  */
  idx = 0;
  while ( nbytes < outlen )
    {
      unsigned char c[4], *digest;

      if (idx)
        gcry_md_reset (hd);

      c[0] = (idx >> 24) & 0xFF;
      c[1] = (idx >> 16) & 0xFF;
      c[2] = (idx >> 8) & 0xFF;
      c[3] = idx & 0xFF;
      idx++;

      gcry_md_write (hd, seed, seedlen);
      gcry_md_write (hd, c, 4);
      digest = gcry_md_read (hd, 0);

      n = (outlen - nbytes < dlen)? (outlen - nbytes) : dlen;
      memcpy (output+nbytes, digest, n);
      nbytes += n;
    }

  gcry_md_close (hd);
  return GPG_ERR_NO_ERROR;
}


/* RFC-3447 (pkcs#1 v2.1) OAEP encoding.  NBITS is the length of the
   key measured in bits.  ALGO is the hash function; it must be a
   valid and usable algorithm.  {VALUE,VALUELEN} is the message to
   encrypt.  {LABEL,LABELLEN} is the optional label to be associated
   with the message, if LABEL is NULL the default is to use the empty
   string as label.  On success the encoded ciphertext is returned at
   R_RESULT.

   If {RANDOM_OVERRIDE, RANDOM_OVERRIDE_LEN} is given it is used as
   the seed instead of using a random string for it.  This feature is
   only useful for regression tests.

   Here is figure 1 from the RFC depicting the process:

                             +----------+---------+-------+
                        DB = |  lHash   |    PS   |   M   |
                             +----------+---------+-------+
                                            |
                  +----------+              V
                  |   seed   |--> MGF ---> xor
                  +----------+              |
                        |                   |
               +--+     V                   |
               |00|    xor <----- MGF <-----|
               +--+     |                   |
                 |      |                   |
                 V      V                   V
               +--+----------+----------------------------+
         EM =  |00|maskedSeed|          maskedDB          |
               +--+----------+----------------------------+
  */
static gcry_err_code_t
oaep_encode (gcry_mpi_t *r_result, unsigned int nbits, int algo,
             const unsigned char *value, size_t valuelen,
             const unsigned char *label, size_t labellen,
             const void *random_override, size_t random_override_len)
{
  gcry_err_code_t rc = 0;
  gcry_error_t err;
  unsigned char *frame = NULL;
  size_t nframe = (nbits+7) / 8;
  unsigned char *p;
  size_t hlen;
  size_t n;

  *r_result = NULL;

  /* Set defaults for LABEL.  */
  if (!label || !labellen)
    {
      label = (const unsigned char*)"";
      labellen = 0;
    }

  hlen = gcry_md_get_algo_dlen (algo);

  /* We skip step 1a which would be to check that LABELLEN is not
     greater than 2^61-1.  See rfc-3447 7.1.1. */

  /* Step 1b.  Note that the obsolete rfc-2437 uses the check:
     valuelen > nframe - 2 * hlen - 1 .  */
  if (valuelen > nframe - 2 * hlen - 2 || !nframe)
    {
      /* Can't encode a VALUELEN value in a NFRAME bytes frame. */
      return GPG_ERR_TOO_SHORT; /* The key is too short.  */
    }

  /* Allocate the frame.  */
  frame = gcry_calloc_secure (1, nframe);
  if (!frame)
    return gpg_err_code_from_syserror ();

  /* Step 2a: Compute the hash of the label.  We store it in the frame
     where later the maskedDB will commence.  */
  gcry_md_hash_buffer (algo, frame + 1 + hlen, label, labellen);

  /* Step 2b: Set octet string to zero.  */
  /* This has already been done while allocating FRAME.  */

  /* Step 2c: Create DB by concatenating lHash, PS, 0x01 and M.  */
  n = nframe - valuelen - 1;
  frame[n] = 0x01;
  memcpy (frame + n + 1, value, valuelen);

  /* Step 3d: Generate seed.  We store it where the maskedSeed will go
     later. */
  if (random_override)
    {
      if (random_override_len != hlen)
        {
          gcry_free (frame);
          return GPG_ERR_INV_ARG;
        }
      memcpy (frame + 1, random_override, hlen);
    }
  else
    gcry_randomize (frame + 1, hlen, GCRY_STRONG_RANDOM);

  /* Step 2e and 2f: Create maskedDB.  */
  {
    unsigned char *dmask;

    dmask = gcry_malloc_secure (nframe - hlen - 1);
    if (!dmask)
      {
        rc = gpg_err_code_from_syserror ();
        gcry_free (frame);
        return rc;
      }
    rc = mgf1 (dmask, nframe - hlen - 1, frame+1, hlen, algo);
    if (rc)
      {
        gcry_free (dmask);
        gcry_free (frame);
        return rc;
      }
    for (n = 1 + hlen, p = dmask; n < nframe; n++)
      frame[n] ^= *p++;
    gcry_free (dmask);
  }

  /* Step 2g and 2h: Create maskedSeed.  */
  {
    unsigned char *smask;

    smask = gcry_malloc_secure (hlen);
    if (!smask)
      {
        rc = gpg_err_code_from_syserror ();
        gcry_free (frame);
        return rc;
      }
    rc = mgf1 (smask, hlen, frame + 1 + hlen, nframe - hlen - 1, algo);
    if (rc)
      {
        gcry_free (smask);
        gcry_free (frame);
        return rc;
      }
    for (n = 1, p = smask; n < 1 + hlen; n++)
      frame[n] ^= *p++;
    gcry_free (smask);
  }

  /* Step 2i: Concatenate 0x00, maskedSeed and maskedDB.  */
  /* This has already been done by using in-place operations.  */

  /* Convert the stuff into an MPI as expected by the caller.  */
  err = gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, nframe, NULL);
  if (err)
    rc = gcry_err_code (err);
  else if (DBG_CIPHER)
    log_mpidump ("OAEP encoded data", *r_result);
  gcry_free (frame);

  return rc;
}


/* RFC-3447 (pkcs#1 v2.1) OAEP decoding.  NBITS is the length of the
   key measured in bits.  ALGO is the hash function; it must be a
   valid and usable algorithm.  VALUE is the raw decrypted message
   {LABEL,LABELLEN} is the optional label to be associated with the
   message, if LABEL is NULL the default is to use the empty string as
   label.  On success the plaintext is returned as a newly allocated
   buffer at R_RESULT; its valid length is stored at R_RESULTLEN.  On
   error NULL is stored at R_RESULT.  */
static gcry_err_code_t
oaep_decode (unsigned char **r_result, size_t *r_resultlen,
             unsigned int nbits, int algo,
             gcry_mpi_t value, const unsigned char *label, size_t labellen)
{
  gcry_err_code_t rc;
  unsigned char *frame = NULL; /* Encoded messages (EM).  */
  unsigned char *masked_seed;  /* Points into FRAME.  */
  unsigned char *masked_db;    /* Points into FRAME.  */
  unsigned char *seed = NULL;  /* Allocated space for the seed and DB.  */
  unsigned char *db;           /* Points into SEED.  */
  unsigned char *lhash = NULL; /* Hash of the label.  */
  size_t nframe;               /* Length of the ciphertext (EM).  */
  size_t hlen;                 /* Length of the hash digest.  */
  size_t db_len;               /* Length of DB and masked_db.  */
  size_t nkey = (nbits+7)/8;   /* Length of the key in bytes.  */
  int failed = 0;              /* Error indicator.  */
  size_t n;

  *r_result = NULL;

  /* This code is implemented as described by rfc-3447 7.1.2.  */

  /* Set defaults for LABEL.  */
  if (!label || !labellen)
    {
      label = (const unsigned char*)"";
      labellen = 0;
    }

  /* Get the length of the digest.  */
  hlen = gcry_md_get_algo_dlen (algo);

  /* Hash the label right away.  */
  lhash = gcry_malloc (hlen);
  if (!lhash)
    return gpg_err_code_from_syserror ();
  gcry_md_hash_buffer (algo, lhash, label, labellen);

  /* Turn the MPI into an octet string.  If the octet string is
     shorter than the key we pad it to the left with zeroes.  This may
     happen due to the leading zero in OAEP frames and due to the
     following random octets (seed^mask) which may have leading zero
     bytes.  This all is needed to cope with our leading zeroes
     suppressing MPI implementation.  The code implictly implements
     Step 1b (bail out if NFRAME != N).  */
  rc = octet_string_from_mpi (&frame, NULL, value, nkey);
  if (rc)
    {
      gcry_free (lhash);
      return GPG_ERR_ENCODING_PROBLEM;
    }
  nframe = nkey;

  /* Step 1c: Check that the key is long enough.  */
  if ( nframe < 2 * hlen + 2 )
    {
      gcry_free (frame);
      gcry_free (lhash);
      return GPG_ERR_ENCODING_PROBLEM;
    }

  /* Step 2 has already been done by the caller and the
     gcry_mpi_aprint above.  */

  /* Allocate space for SEED and DB.  */
  seed = gcry_malloc_secure (nframe - 1);
  if (!seed)
    {
      rc = gpg_err_code_from_syserror ();
      gcry_free (frame);
      gcry_free (lhash);
      return rc;
    }
  db = seed + hlen;

  /* To avoid choosen ciphertext attacks from now on we make sure to
     run all code even in the error case; this avoids possible timing
     attacks as described by Manger.  */

  /* Step 3a: Hash the label.  */
  /* This has already been done.  */

  /* Step 3b: Separate the encoded message.  */
  masked_seed = frame + 1;
  masked_db   = frame + 1 + hlen;
  db_len      = nframe - 1 - hlen;

  /* Step 3c and 3d: seed = maskedSeed ^ mgf(maskedDB, hlen).  */
  if (mgf1 (seed, hlen, masked_db, db_len, algo))
    failed = 1;
  for (n = 0; n < hlen; n++)
    seed[n] ^= masked_seed[n];

  /* Step 3e and 3f: db = maskedDB ^ mgf(seed, db_len).  */
  if (mgf1 (db, db_len, seed, hlen, algo))
    failed = 1;
  for (n = 0; n < db_len; n++)
    db[n] ^= masked_db[n];

  /* Step 3g: Check lhash, an possible empty padding string terminated
     by 0x01 and the first byte of EM being 0.  */
  if (memcmp (lhash, db, hlen))
    failed = 1;
  for (n = hlen; n < db_len; n++)
    if (db[n] == 0x01)
      break;
  if (n == db_len)
    failed = 1;
  if (frame[0])
    failed = 1;

  gcry_free (lhash);
  gcry_free (frame);
  if (failed)
    {
      gcry_free (seed);
      return GPG_ERR_ENCODING_PROBLEM;
    }

  /* Step 4: Output M.  */
  /* To avoid an extra allocation we reuse the seed buffer.  The only
     caller of this function will anyway free the result soon.  */
  n++;
  memmove (seed, db + n, db_len - n);
  *r_result = seed;
  *r_resultlen = db_len - n;
  seed = NULL;

  if (DBG_CIPHER)
    log_printhex ("value extracted from OAEP encoded data:",
                  *r_result, *r_resultlen);

  return 0;
}


/* RFC-3447 (pkcs#1 v2.1) PSS encoding.  Encode {VALUE,VALUELEN} for
   an NBITS key.  Note that VALUE is already the mHash from the
   picture below.  ALGO is a valid hash algorithm and SALTLEN is the
   length of salt to be used.  On success the result is stored as a
   new MPI at R_RESULT.  On error the value at R_RESULT is undefined.

   If {RANDOM_OVERRIDE, RANDOM_OVERRIDE_LEN} is given it is used as
   the salt instead of using a random string for the salt.  This
   feature is only useful for regression tests.

   Here is figure 2 from the RFC (errata 595 applied) depicting the
   process:

                                  +-----------+
                                  |     M     |
                                  +-----------+
                                        |
                                        V
                                      Hash
                                        |
                                        V
                          +--------+----------+----------+
                     M' = |Padding1|  mHash   |   salt   |
                          +--------+----------+----------+
                                         |
               +--------+----------+     V
         DB =  |Padding2| salt     |   Hash
               +--------+----------+     |
                         |               |
                         V               |    +----+
                        xor <--- MGF <---|    |0xbc|
                         |               |    +----+
                         |               |      |
                         V               V      V
               +-------------------+----------+----+
         EM =  |    maskedDB       |     H    |0xbc|
               +-------------------+----------+----+

  */
static gcry_err_code_t
pss_encode (gcry_mpi_t *r_result, unsigned int nbits, int algo,
	    const unsigned char *value, size_t valuelen, int saltlen,
            const void *random_override, size_t random_override_len)
{
  gcry_err_code_t rc = 0;
  gcry_error_t err;
  size_t hlen;                 /* Length of the hash digest.  */
  unsigned char *em = NULL;    /* Encoded message.  */
  size_t emlen = (nbits+7)/8;  /* Length in bytes of EM.  */
  unsigned char *h;            /* Points into EM.  */
  unsigned char *buf = NULL;   /* Help buffer.  */
  size_t buflen;               /* Length of BUF.  */
  unsigned char *mhash;        /* Points into BUF.  */
  unsigned char *salt;         /* Points into BUF.  */
  unsigned char *dbmask;       /* Points into BUF.  */
  unsigned char *p;
  size_t n;

  /* This code is implemented as described by rfc-3447 9.1.1.  */

  /* Get the length of the digest.  */
  hlen = gcry_md_get_algo_dlen (algo);
  gcry_assert (hlen);  /* We expect a valid ALGO here.  */

  /* Allocate a help buffer and setup some pointers.  */
  buflen = 8 + hlen + saltlen + (emlen - hlen - 1);
  buf = gcry_malloc (buflen);
  if (!buf)
    {
      rc = gpg_err_code_from_syserror ();
      goto leave;
    }
  mhash = buf + 8;
  salt  = mhash + hlen;
  dbmask= salt + saltlen;

  /* Step 2: That would be: mHash = Hash(M) but our input is already
     mHash thus we do only a consistency check and copy to MHASH.  */
  if (valuelen != hlen)
    {
      rc = GPG_ERR_INV_LENGTH;
      goto leave;
    }
  memcpy (mhash, value, hlen);

  /* Step 3: Check length constraints.  */
  if (emlen < hlen + saltlen + 2)
    {
      rc = GPG_ERR_TOO_SHORT;
      goto leave;
    }

  /* Allocate space for EM.  */
  em = gcry_malloc (emlen);
  if (!em)
    {
      rc = gpg_err_code_from_syserror ();
      goto leave;
    }
  h = em + emlen - 1 - hlen;

  /* Step 4: Create a salt.  */
  if (saltlen)
    {
      if (random_override)
        {
          if (random_override_len != saltlen)
            {
              rc = GPG_ERR_INV_ARG;
              goto leave;
            }
          memcpy (salt, random_override, saltlen);
        }
      else
        gcry_randomize (salt, saltlen, GCRY_STRONG_RANDOM);
    }

  /* Step 5 and 6: M' = Hash(Padding1 || mHash || salt).  */
  memset (buf, 0, 8);  /* Padding.  */
  gcry_md_hash_buffer (algo, h, buf, 8 + hlen + saltlen);

  /* Step 7 and 8: DB = PS || 0x01 || salt.  */
  /* Note that we use EM to store DB and later Xor in-place.  */
  p = em + emlen - 1 - hlen - saltlen - 1;
  memset (em, 0, p - em);
  *p++ = 0x01;
  memcpy (p, salt, saltlen);

  /* Step 9: dbmask = MGF(H, emlen - hlen - 1).  */
  mgf1 (dbmask, emlen - hlen - 1, h, hlen, algo);

  /* Step 10: maskedDB = DB ^ dbMask */
  for (n = 0, p = dbmask; n < emlen - hlen - 1; n++, p++)
    em[n] ^= *p;

  /* Step 11: Set the leftmost bits to zero.  */
  em[0] &= 0xFF >> (8 * emlen - nbits);

  /* Step 12: EM = maskedDB || H || 0xbc.  */
  em[emlen-1] = 0xbc;

  /* Convert EM into an MPI.  */
  err = gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, em, emlen, NULL);
  if (err)
    rc = gcry_err_code (err);
  else if (DBG_CIPHER)
    log_mpidump ("PSS encoded data", *r_result);

 leave:
  if (em)
    {
      wipememory (em, emlen);
      gcry_free (em);
    }
  if (buf)
    {
      wipememory (buf, buflen);
      gcry_free (buf);
    }
  return rc;
}


/* Verify a signature assuming PSS padding.  VALUE is the hash of the
   message (mHash) encoded as an MPI; its length must match the digest
   length of ALGO.  ENCODED is the output of the RSA public key
   function (EM).  NBITS is the size of the public key.  ALGO is the
   hash algorithm and SALTLEN is the length of the used salt.  The
   function returns 0 on success or on error code.  */
static gcry_err_code_t
pss_verify (gcry_mpi_t value, gcry_mpi_t encoded, unsigned int nbits, int algo,
            size_t saltlen)
{
  gcry_err_code_t rc = 0;
  size_t hlen;                 /* Length of the hash digest.  */
  unsigned char *em = NULL;    /* Encoded message.  */
  size_t emlen = (nbits+7)/8;  /* Length in bytes of EM.  */
  unsigned char *salt;         /* Points into EM.  */
  unsigned char *h;            /* Points into EM.  */
  unsigned char *buf = NULL;   /* Help buffer.  */
  size_t buflen;               /* Length of BUF.  */
  unsigned char *dbmask;       /* Points into BUF.  */
  unsigned char *mhash;        /* Points into BUF.  */
  unsigned char *p;
  size_t n;

  /* This code is implemented as described by rfc-3447 9.1.2.  */

  /* Get the length of the digest.  */
  hlen = gcry_md_get_algo_dlen (algo);
  gcry_assert (hlen);  /* We expect a valid ALGO here.  */

  /* Allocate a help buffer and setup some pointers.
     This buffer is used for two purposes:
        +------------------------------+-------+
     1. | dbmask                       | mHash |
        +------------------------------+-------+
           emlen - hlen - 1              hlen

        +----------+-------+---------+-+-------+
     2. | padding1 | mHash | salt    | | mHash |
        +----------+-------+---------+-+-------+
             8       hlen    saltlen     hlen
  */
  buflen = 8 + hlen + saltlen;
  if (buflen < emlen - hlen - 1)
    buflen = emlen - hlen - 1;
  buflen += hlen;
  buf = gcry_malloc (buflen);
  if (!buf)
    {
      rc = gpg_err_code_from_syserror ();
      goto leave;
    }
  dbmask = buf;
  mhash = buf + buflen - hlen;

  /* Step 2: That would be: mHash = Hash(M) but our input is already
     mHash thus we only need to convert VALUE into MHASH.  */
  rc = octet_string_from_mpi (NULL, mhash, value, hlen);
  if (rc)
    goto leave;

  /* Convert the signature into an octet string.  */
  rc = octet_string_from_mpi (&em, NULL, encoded, emlen);
  if (rc)
    goto leave;

  /* Step 3: Check length of EM.  Because we internally use MPI
     functions we can't do this properly; EMLEN is always the length
     of the key because octet_string_from_mpi needs to left pad the
     result with zero to cope with the fact that our MPIs suppress all
     leading zeroes.  Thus what we test here are merely the digest and
     salt lengths to the key.  */
  if (emlen < hlen + saltlen + 2)
    {
      rc = GPG_ERR_TOO_SHORT; /* For the hash and saltlen.  */
      goto leave;
    }

  /* Step 4: Check last octet.  */
  if (em[emlen - 1] != 0xbc)
    {
      rc = GPG_ERR_BAD_SIGNATURE;
      goto leave;
    }

  /* Step 5: Split EM.  */
  h = em + emlen - 1 - hlen;

  /* Step 6: Check the leftmost bits.  */
  if ((em[0] & ~(0xFF >> (8 * emlen - nbits))))
    {
      rc = GPG_ERR_BAD_SIGNATURE;
      goto leave;
    }

  /* Step 7: dbmask = MGF(H, emlen - hlen - 1).  */
  mgf1 (dbmask, emlen - hlen - 1, h, hlen, algo);

  /* Step 8: maskedDB = DB ^ dbMask.  */
  for (n = 0, p = dbmask; n < emlen - hlen - 1; n++, p++)
    em[n] ^= *p;

  /* Step 9: Set leftmost bits in DB to zero.  */
  em[0] &= 0xFF >> (8 * emlen - nbits);

  /* Step 10: Check the padding of DB.  */
  for (n = 0; n < emlen - hlen - saltlen - 2 && !em[n]; n++)
    ;
  if (n != emlen - hlen - saltlen - 2 || em[n++] != 1)
    {
      rc = GPG_ERR_BAD_SIGNATURE;
      goto leave;
    }

  /* Step 11: Extract salt from DB.  */
  salt = em + n;

  /* Step 12:  M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */
  memset (buf, 0, 8);
  memcpy (buf+8, mhash, hlen);
  memcpy (buf+8+hlen, salt, saltlen);

  /* Step 13:  H' = Hash(M').  */
  gcry_md_hash_buffer (algo, buf, buf, 8 + hlen + saltlen);

  /* Step 14:  Check H == H'.   */
  rc = memcmp (h, buf, hlen) ? GPG_ERR_BAD_SIGNATURE : GPG_ERR_NO_ERROR;

 leave:
  if (em)
    {
      wipememory (em, emlen);
      gcry_free (em);
    }
  if (buf)
    {
      wipememory (buf, buflen);
      gcry_free (buf);
    }
  return rc;
}


/* Callback for the pubkey algorithm code to verify PSS signatures.
   OPAQUE is the data provided by the actual caller.  The meaning of
   TMP depends on the actual algorithm (but there is only RSA); now
   for RSA it is the output of running the public key function on the
   input.  */
static int
pss_verify_cmp (void *opaque, gcry_mpi_t tmp)
{
  struct pk_encoding_ctx *ctx = opaque;
  gcry_mpi_t hash = ctx->verify_arg;

  return pss_verify (hash, tmp, ctx->nbits - 1, ctx->hash_algo, ctx->saltlen);
}


/* Internal function.   */
static gcry_err_code_t
sexp_elements_extract (gcry_sexp_t key_sexp, const char *element_names,
		       gcry_mpi_t *elements, const char *algo_name)
{
  gcry_err_code_t err = 0;
  int i, idx;
  const char *name;
  gcry_sexp_t list;

  for (name = element_names, idx = 0; *name && !err; name++, idx++)
    {
      list = gcry_sexp_find_token (key_sexp, name, 1);
      if (!list)
	elements[idx] = NULL;
      else
	{
	  elements[idx] = gcry_sexp_nth_mpi (list, 1, GCRYMPI_FMT_USG);
	  gcry_sexp_release (list);
	  if (!elements[idx])
	    err = GPG_ERR_INV_OBJ;
	}
    }

  if (!err)
    {
      /* Check that all elements are available.  */
      for (name = element_names, idx = 0; *name; name++, idx++)
        if (!elements[idx])
          break;
      if (*name)
        {
          err = GPG_ERR_NO_OBJ;
          /* Some are missing.  Before bailing out we test for
             optional parameters.  */
          if (algo_name && !strcmp (algo_name, "RSA")
              && !strcmp (element_names, "nedpqu") )
            {
              /* This is RSA.  Test whether we got N, E and D and that
                 the optional P, Q and U are all missing.  */
              if (elements[0] && elements[1] && elements[2]
                  && !elements[3] && !elements[4] && !elements[5])
                err = 0;
            }
        }
    }


  if (err)
    {
      for (i = 0; i < idx; i++)
        if (elements[i])
          gcry_free (elements[i]);
    }
  return err;
}


/* Internal function used for ecc.  Note, that this function makes use
   of its intimate knowledge about the ECC parameters from ecc.c. */
static gcry_err_code_t
sexp_elements_extract_ecc (gcry_sexp_t key_sexp, const char *element_names,
                           gcry_mpi_t *elements, pk_extra_spec_t *extraspec)

{
  gcry_err_code_t err = 0;
  int idx;
  const char *name;
  gcry_sexp_t list;

  /* Clear the array for easier error cleanup. */
  for (name = element_names, idx = 0; *name; name++, idx++)
    elements[idx] = NULL;
  gcry_assert (idx >= 5); /* We know that ECC has at least 5 elements
                             (params only) or 6 (full public key).  */
  if (idx == 5)
    elements[5] = NULL;   /* Extra clear for the params only case.  */


  /* Init the array with the available curve parameters. */
  for (name = element_names, idx = 0; *name && !err; name++, idx++)
    {
      list = gcry_sexp_find_token (key_sexp, name, 1);
      if (!list)
	elements[idx] = NULL;
      else
	{
	  elements[idx] = gcry_sexp_nth_mpi (list, 1, GCRYMPI_FMT_USG);
	  gcry_sexp_release (list);
	  if (!elements[idx])
            {
              err = GPG_ERR_INV_OBJ;
              goto leave;
            }
	}
    }

  /* Check whether a curve parameter has been given and then fill any
     missing elements.  */
  list = gcry_sexp_find_token (key_sexp, "curve", 5);
  if (list)
    {
      if (extraspec->get_param)
        {
          char *curve;
          gcry_mpi_t params[6];

          for (idx = 0; idx < DIM(params); idx++)
            params[idx] = NULL;

          curve = _gcry_sexp_nth_string (list, 1);
          gcry_sexp_release (list);
          if (!curve)
            {
              /* No curve name given (or out of core). */
              err = GPG_ERR_INV_OBJ;
              goto leave;
            }
          err = extraspec->get_param (curve, params);
          gcry_free (curve);
          if (err)
            goto leave;

          for (idx = 0; idx < DIM(params); idx++)
            {
              if (!elements[idx])
                elements[idx] = params[idx];
              else
                mpi_free (params[idx]);
            }
        }
      else
        {
          gcry_sexp_release (list);
          err = GPG_ERR_INV_OBJ; /* "curve" given but ECC not supported. */
          goto leave;
        }
    }

  /* Check that all parameters are known.  */
  for (name = element_names, idx = 0; *name; name++, idx++)
    if (!elements[idx])
      {
        err = GPG_ERR_NO_OBJ;
        goto leave;
      }

 leave:
  if (err)
    {
      for (name = element_names, idx = 0; *name; name++, idx++)
        if (elements[idx])
          gcry_free (elements[idx]);
    }
  return err;
}



/****************
 * Convert a S-Exp with either a private or a public key to our
 * internal format. Currently we do only support the following
 * algorithms:
 *    dsa
 *    rsa
 *    openpgp-dsa
 *    openpgp-rsa
 *    openpgp-elg
 *    openpgp-elg-sig
 *    ecdsa
 *    ecdh
 * Provide a SE with the first element be either "private-key" or
 * or "public-key". It is followed by a list with its first element
 * be one of the above algorithm identifiers and the remaning
 * elements are pairs with parameter-id and value.
 * NOTE: we look through the list to find a list beginning with
 * "private-key" or "public-key" - the first one found is used.
 *
 * If OVERRIDE_ELEMS is not NULL those elems override the parameter
 * specification taken from the module.  This ise used by
 * gcry_pk_get_curve.
 *
 * Returns: A pointer to an allocated array of MPIs if the return value is
 *	    zero; the caller has to release this array.
 *
 * Example of a DSA public key:
 *  (private-key
 *    (dsa
 *	(p <mpi>)
 *	(g <mpi>)
 *	(y <mpi>)
 *	(x <mpi>)
 *    )
 *  )
 * The <mpi> are expected to be in GCRYMPI_FMT_USG
 */
static gcry_err_code_t
sexp_to_key (gcry_sexp_t sexp, int want_private, const char *override_elems,
             gcry_mpi_t **retarray, gcry_module_t *retalgo)
{
  gcry_err_code_t err = 0;
  gcry_sexp_t list, l2;
  char *name;
  const char *elems;
  gcry_mpi_t *array;
  gcry_module_t module;
  gcry_pk_spec_t *pubkey;
  pk_extra_spec_t *extraspec;
  int is_ecc;

  /* Check that the first element is valid.  */
  list = gcry_sexp_find_token (sexp,
                               want_private? "private-key":"public-key", 0);
  if (!list)
    return GPG_ERR_INV_OBJ; /* Does not contain a key object.  */

  l2 = gcry_sexp_cadr( list );
  gcry_sexp_release ( list );
  list = l2;
  name = _gcry_sexp_nth_string (list, 0);
  if (!name)
    {
      gcry_sexp_release ( list );
      return GPG_ERR_INV_OBJ;      /* Invalid structure of object. */
    }

  ath_mutex_lock (&pubkeys_registered_lock);
  module = gcry_pk_lookup_name (name);
  ath_mutex_unlock (&pubkeys_registered_lock);

  /* Fixme: We should make sure that an ECC key is always named "ecc"
     and not "ecdsa".  "ecdsa" should be used for the signature
     itself.  We need a function to test whether an algorithm given
     with a key is compatible with an application of the key (signing,
     encryption).  For RSA this is easy, but ECC is the first
     algorithm which has many flavours.  */
  is_ecc = ( !strcmp (name, "ecdsa")
             || !strcmp (name, "ecdh")
             || !strcmp (name, "ecc") );
  gcry_free (name);

  if (!module)
    {
      gcry_sexp_release (list);
      return GPG_ERR_PUBKEY_ALGO; /* Unknown algorithm. */
    }
  else
    {
      pubkey = (gcry_pk_spec_t *) module->spec;
      extraspec = module->extraspec;
    }

  if (override_elems)
    elems = override_elems;
  else if (want_private)
    elems = pubkey->elements_skey;
  else
    elems = pubkey->elements_pkey;
  array = gcry_calloc (strlen (elems) + 1, sizeof (*array));
  if (!array)
    err = gpg_err_code_from_syserror ();
  if (!err)
    {
      if (is_ecc)
        err = sexp_elements_extract_ecc (list, elems, array, extraspec);
      else
        err = sexp_elements_extract (list, elems, array, pubkey->name);
    }

  gcry_sexp_release (list);

  if (err)
    {
      gcry_free (array);

      ath_mutex_lock (&pubkeys_registered_lock);
      _gcry_module_release (module);
      ath_mutex_unlock (&pubkeys_registered_lock);
    }
  else
    {
      *retarray = array;
      *retalgo = module;
    }

  return err;
}


static gcry_err_code_t
sexp_to_sig (gcry_sexp_t sexp, gcry_mpi_t **retarray,
	     gcry_module_t *retalgo)
{
  gcry_err_code_t err = 0;
  gcry_sexp_t list, l2;
  char *name;
  const char *elems;
  gcry_mpi_t *array;
  gcry_module_t module;
  gcry_pk_spec_t *pubkey;

  /* Check that the first element is valid.  */
  list = gcry_sexp_find_token( sexp, "sig-val" , 0 );
  if (!list)
    return GPG_ERR_INV_OBJ; /* Does not contain a signature value object.  */

  l2 = gcry_sexp_nth (list, 1);
  if (!l2)
    {
      gcry_sexp_release (list);
      return GPG_ERR_NO_OBJ;   /* No cadr for the sig object.  */
    }
  name = _gcry_sexp_nth_string (l2, 0);
  if (!name)
    {
      gcry_sexp_release (list);
      gcry_sexp_release (l2);
      return GPG_ERR_INV_OBJ;  /* Invalid structure of object.  */
    }
  else if (!strcmp (name, "flags"))
    {
      /* Skip flags, since they are not used but here just for the
	 sake of consistent S-expressions.  */
      gcry_free (name);
      gcry_sexp_release (l2);
      l2 = gcry_sexp_nth (list, 2);
      if (!l2)
	{
	  gcry_sexp_release (list);
	  return GPG_ERR_INV_OBJ;
	}
      name = _gcry_sexp_nth_string (l2, 0);
    }

  ath_mutex_lock (&pubkeys_registered_lock);
  module = gcry_pk_lookup_name (name);
  ath_mutex_unlock (&pubkeys_registered_lock);
  gcry_free (name);
  name = NULL;

  if (!module)
    {
      gcry_sexp_release (l2);
      gcry_sexp_release (list);
      return GPG_ERR_PUBKEY_ALGO;  /* Unknown algorithm. */
    }
  else
    pubkey = (gcry_pk_spec_t *) module->spec;

  elems = pubkey->elements_sig;
  array = gcry_calloc (strlen (elems) + 1 , sizeof *array );
  if (!array)
    err = gpg_err_code_from_syserror ();

  if (!err)
    err = sexp_elements_extract (list, elems, array, NULL);

  gcry_sexp_release (l2);
  gcry_sexp_release (list);

  if (err)
    {
      ath_mutex_lock (&pubkeys_registered_lock);
      _gcry_module_release (module);
      ath_mutex_unlock (&pubkeys_registered_lock);

      gcry_free (array);
    }
  else
    {
      *retarray = array;
      *retalgo = module;
    }

  return err;
}

static inline int
get_hash_algo (const char *s, size_t n)
{
  static const struct { const char *name; int algo; } hashnames[] = {
    { "sha1",   GCRY_MD_SHA1 },
    { "md5",    GCRY_MD_MD5 },
    { "sha256", GCRY_MD_SHA256 },
    { "ripemd160", GCRY_MD_RMD160 },
    { "rmd160", GCRY_MD_RMD160 },
    { "sha384", GCRY_MD_SHA384 },
    { "sha512", GCRY_MD_SHA512 },
    { "sha224", GCRY_MD_SHA224 },
    { "md2",    GCRY_MD_MD2 },
    { "md4",    GCRY_MD_MD4 },
    { "tiger",  GCRY_MD_TIGER },
    { "haval",  GCRY_MD_HAVAL },
    { NULL, 0 }
  };
  int algo;
  int i;

  for (i=0; hashnames[i].name; i++)
    {
      if ( strlen (hashnames[i].name) == n
	   && !memcmp (hashnames[i].name, s, n))
	break;
    }
  if (hashnames[i].name)
    algo = hashnames[i].algo;
  else
    {
      /* In case of not listed or dynamically allocated hash
	 algorithm we fall back to this somewhat slower
	 method.  Further, it also allows to use OIDs as
	 algorithm names. */
      char *tmpname;

      tmpname = gcry_malloc (n+1);
      if (!tmpname)
	algo = 0;  /* Out of core - silently give up.  */
      else
	{
	  memcpy (tmpname, s, n);
	  tmpname[n] = 0;
	  algo = gcry_md_map_name (tmpname);
	  gcry_free (tmpname);
	}
    }
  return algo;
}


/****************
 * Take sexp and return an array of MPI as used for our internal decrypt
 * function.
 * s_data = (enc-val
 *           [(flags [raw, pkcs1, oaep, no-blinding])]
 *           [(hash-algo <algo>)]
 *           [(label <label>)]
 *	      (<algo>
 *		(<param_name1> <mpi>)
 *		...
 *		(<param_namen> <mpi>)
 *	      ))
 * HASH-ALGO and LABEL are specific to OAEP.
 * RET_MODERN is set to true when at least an empty flags list has been found.
 * CTX is used to return encoding information; it may be NULL in which
 * case raw encoding is used.
 */
static gcry_err_code_t
sexp_to_enc (gcry_sexp_t sexp, gcry_mpi_t **retarray, gcry_module_t *retalgo,
             int *ret_modern, int *flags, struct pk_encoding_ctx *ctx)
{
  gcry_err_code_t err = 0;
  gcry_sexp_t list = NULL, l2 = NULL;
  gcry_pk_spec_t *pubkey = NULL;
  gcry_module_t module = NULL;
  char *name = NULL;
  size_t n;
  int parsed_flags = 0;
  const char *elems;
  gcry_mpi_t *array = NULL;

  *ret_modern = 0;

  /* Check that the first element is valid.  */
  list = gcry_sexp_find_token (sexp, "enc-val" , 0);
  if (!list)
    {
      err = GPG_ERR_INV_OBJ; /* Does not contain an encrypted value object.  */
      goto leave;
    }

  l2 = gcry_sexp_nth (list, 1);
  if (!l2)
    {
      err = GPG_ERR_NO_OBJ; /* No cdr for the data object.  */
      goto leave;
    }

  /* Extract identifier of sublist.  */
  name = _gcry_sexp_nth_string (l2, 0);
  if (!name)
    {
      err = GPG_ERR_INV_OBJ; /* Invalid structure of object.  */
      goto leave;
    }

  if (!strcmp (name, "flags"))
    {
      /* There is a flags element - process it.  */
      const char *s;
      int i;

      *ret_modern = 1;
      for (i = gcry_sexp_length (l2) - 1; i > 0; i--)
        {
          s = gcry_sexp_nth_data (l2, i, &n);
          if (! s)
            ; /* Not a data element - ignore.  */
          else if (n == 3 && !memcmp (s, "raw", 3)
                   && ctx->encoding == PUBKEY_ENC_UNKNOWN)
            ctx->encoding = PUBKEY_ENC_RAW;
          else if (n == 5 && !memcmp (s, "pkcs1", 5)
                   && ctx->encoding == PUBKEY_ENC_UNKNOWN)
	    ctx->encoding = PUBKEY_ENC_PKCS1;
          else if (n == 4 && !memcmp (s, "oaep", 4)
                   && ctx->encoding == PUBKEY_ENC_UNKNOWN)
	    ctx->encoding = PUBKEY_ENC_OAEP;
          else if (n == 3 && !memcmp (s, "pss", 3)
                   && ctx->encoding == PUBKEY_ENC_UNKNOWN)
	    {
	      err = GPG_ERR_CONFLICT;
	      goto leave;
	    }
          else if (n == 11 && ! memcmp (s, "no-blinding", 11))
            parsed_flags |= PUBKEY_FLAG_NO_BLINDING;
          else
            {
              err = GPG_ERR_INV_FLAG;
              goto leave;
            }
        }
      gcry_sexp_release (l2);

      /* Get the OAEP parameters HASH-ALGO and LABEL, if any. */
      if (ctx->encoding == PUBKEY_ENC_OAEP)
	{
	  /* Get HASH-ALGO. */
	  l2 = gcry_sexp_find_token (list, "hash-algo", 0);
	  if (l2)
	    {
	      s = gcry_sexp_nth_data (l2, 1, &n);
	      if (!s)
		err = GPG_ERR_NO_OBJ;
	      else
		{
		  ctx->hash_algo = get_hash_algo (s, n);
		  if (!ctx->hash_algo)
		    err = GPG_ERR_DIGEST_ALGO;
		}
	      gcry_sexp_release (l2);
	      if (err)
		goto leave;
	    }

	  /* Get LABEL. */
	  l2 = gcry_sexp_find_token (list, "label", 0);
	  if (l2)
	    {
	      s = gcry_sexp_nth_data (l2, 1, &n);
	      if (!s)
		err = GPG_ERR_NO_OBJ;
	      else if (n > 0)
		{
		  ctx->label = gcry_malloc (n);
		  if (!ctx->label)
		    err = gpg_err_code_from_syserror ();
		  else
		    {
		      memcpy (ctx->label, s, n);
		      ctx->labellen = n;
		    }
		}
	      gcry_sexp_release (l2);
	      if (err)
		goto leave;
	    }
	}

      /* Get the next which has the actual data - skip HASH-ALGO and LABEL. */
      for (i = 2; (l2 = gcry_sexp_nth (list, i)) != NULL; i++)
	{
	  s = gcry_sexp_nth_data (l2, 0, &n);
	  if (!(n == 9 && !memcmp (s, "hash-algo", 9))
	      && !(n == 5 && !memcmp (s, "label", 5))
	      && !(n == 15 && !memcmp (s, "random-override", 15)))
	    break;
	  gcry_sexp_release (l2);
	}

      if (!l2)
        {
          err = GPG_ERR_NO_OBJ; /* No cdr for the data object. */
          goto leave;
        }

      /* Extract sublist identifier.  */
      gcry_free (name);
      name = _gcry_sexp_nth_string (l2, 0);
      if (!name)
        {
          err = GPG_ERR_INV_OBJ; /* Invalid structure of object. */
          goto leave;
        }

      gcry_sexp_release (list);
      list = l2;
      l2 = NULL;
    }

  ath_mutex_lock (&pubkeys_registered_lock);
  module = gcry_pk_lookup_name (name);
  ath_mutex_unlock (&pubkeys_registered_lock);

  if (!module)
    {
      err = GPG_ERR_PUBKEY_ALGO; /* Unknown algorithm.  */
      goto leave;
    }
  pubkey = (gcry_pk_spec_t *) module->spec;

  elems = pubkey->elements_enc;
  array = gcry_calloc (strlen (elems) + 1, sizeof (*array));
  if (!array)
    {
      err = gpg_err_code_from_syserror ();
      goto leave;
    }

  err = sexp_elements_extract (list, elems, array, NULL);

 leave:
  gcry_sexp_release (list);
  gcry_sexp_release (l2);
  gcry_free (name);

  if (err)
    {
      ath_mutex_lock (&pubkeys_registered_lock);
      _gcry_module_release (module);
      ath_mutex_unlock (&pubkeys_registered_lock);
      gcry_free (array);
      gcry_free (ctx->label);
      ctx->label = NULL;
    }
  else
    {
      *retarray = array;
      *retalgo = module;
      *flags = parsed_flags;
    }

  return err;
}

/* Take the hash value and convert into an MPI, suitable for
   passing to the low level functions.  We currently support the
   old style way of passing just a MPI and the modern interface which
   allows to pass flags so that we can choose between raw and pkcs1
   padding - may be more padding options later.

   (<mpi>)
   or
   (data
    [(flags [raw, pkcs1, oaep, pss, no-blinding])]
    [(hash <algo> <value>)]
    [(value <text>)]
    [(hash-algo <algo>)]
    [(label <label>)]
    [(salt-length <length>)]
    [(random-override <data>)]
   )

   Either the VALUE or the HASH element must be present for use
   with signatures.  VALUE is used for encryption.

   HASH-ALGO and LABEL are specific to OAEP.

   SALT-LENGTH is for PSS.

   RANDOM-OVERRIDE is used to replace random nonces for regression
   testing.  */
static gcry_err_code_t
sexp_data_to_mpi (gcry_sexp_t input, gcry_mpi_t *ret_mpi,
		  struct pk_encoding_ctx *ctx)
{
  gcry_err_code_t rc = 0;
  gcry_sexp_t ldata, lhash, lvalue;
  int i;
  size_t n;
  const char *s;
  int unknown_flag=0;
  int parsed_flags = 0;

  *ret_mpi = NULL;
  ldata = gcry_sexp_find_token (input, "data", 0);
  if (!ldata)
    { /* assume old style */
      *ret_mpi = gcry_sexp_nth_mpi (input, 0, 0);
      return *ret_mpi ? GPG_ERR_NO_ERROR : GPG_ERR_INV_OBJ;
    }

  /* see whether there is a flags object */
  {
    gcry_sexp_t lflags = gcry_sexp_find_token (ldata, "flags", 0);
    if (lflags)
      { /* parse the flags list. */
        for (i=gcry_sexp_length (lflags)-1; i > 0; i--)
          {
            s = gcry_sexp_nth_data (lflags, i, &n);
            if (!s)
              ; /* not a data element*/
            else if ( n == 3 && !memcmp (s, "raw", 3)
                      && ctx->encoding == PUBKEY_ENC_UNKNOWN)
              ctx->encoding = PUBKEY_ENC_RAW;
            else if ( n == 5 && !memcmp (s, "pkcs1", 5)
                      && ctx->encoding == PUBKEY_ENC_UNKNOWN)
              ctx->encoding = PUBKEY_ENC_PKCS1;
            else if ( n == 4 && !memcmp (s, "oaep", 4)
                      && ctx->encoding == PUBKEY_ENC_UNKNOWN)
              ctx->encoding = PUBKEY_ENC_OAEP;
            else if ( n == 3 && !memcmp (s, "pss", 3)
                      && ctx->encoding == PUBKEY_ENC_UNKNOWN)
              ctx->encoding = PUBKEY_ENC_PSS;
	    else if (n == 11 && ! memcmp (s, "no-blinding", 11))
	      parsed_flags |= PUBKEY_FLAG_NO_BLINDING;
            else
              unknown_flag = 1;
          }
        gcry_sexp_release (lflags);
      }
  }

  if (ctx->encoding == PUBKEY_ENC_UNKNOWN)
    ctx->encoding = PUBKEY_ENC_RAW; /* default to raw */

  /* Get HASH or MPI */
  lhash = gcry_sexp_find_token (ldata, "hash", 0);
  lvalue = lhash? NULL : gcry_sexp_find_token (ldata, "value", 0);

  if (!(!lhash ^ !lvalue))
    rc = GPG_ERR_INV_OBJ; /* none or both given */
  else if (unknown_flag)
    rc = GPG_ERR_INV_FLAG;
  else if (ctx->encoding == PUBKEY_ENC_RAW && lvalue)
    {
      *ret_mpi = gcry_sexp_nth_mpi (lvalue, 1, GCRYMPI_FMT_USG);
      if (!*ret_mpi)
        rc = GPG_ERR_INV_OBJ;
    }
  else if (ctx->encoding == PUBKEY_ENC_PKCS1 && lvalue
	   && ctx->op == PUBKEY_OP_ENCRYPT)
    {
      const void * value;
      size_t valuelen;
      gcry_sexp_t list;
      void *random_override = NULL;
      size_t random_override_len = 0;

      if ( !(value=gcry_sexp_nth_data (lvalue, 1, &valuelen)) || !valuelen )
        rc = GPG_ERR_INV_OBJ;
      else
        {
          /* Get optional RANDOM-OVERRIDE.  */
          list = gcry_sexp_find_token (ldata, "random-override", 0);
          if (list)
            {
              s = gcry_sexp_nth_data (list, 1, &n);
              if (!s)
                rc = GPG_ERR_NO_OBJ;
              else if (n > 0)
                {
                  random_override = gcry_malloc (n);
                  if (!random_override)
                    rc = gpg_err_code_from_syserror ();
                  else
                    {
                      memcpy (random_override, s, n);
                      random_override_len = n;
                    }
                }
              gcry_sexp_release (list);
              if (rc)
                goto leave;
            }

          rc = pkcs1_encode_for_encryption (ret_mpi, ctx->nbits,
                                            value, valuelen,
                                            random_override,
                                            random_override_len);
          gcry_free (random_override);
        }
    }
  else if (ctx->encoding == PUBKEY_ENC_PKCS1 && lhash
	   && (ctx->op == PUBKEY_OP_SIGN || ctx->op == PUBKEY_OP_VERIFY))
    {
      if (gcry_sexp_length (lhash) != 3)
        rc = GPG_ERR_INV_OBJ;
      else if ( !(s=gcry_sexp_nth_data (lhash, 1, &n)) || !n )
        rc = GPG_ERR_INV_OBJ;
      else
        {
          const void * value;
          size_t valuelen;

	  ctx->hash_algo = get_hash_algo (s, n);

          if (!ctx->hash_algo)
            rc = GPG_ERR_DIGEST_ALGO;
          else if ( !(value=gcry_sexp_nth_data (lhash, 2, &valuelen))
                    || !valuelen )
            rc = GPG_ERR_INV_OBJ;
          else
	    rc = pkcs1_encode_for_signature (ret_mpi, ctx->nbits,
					     value, valuelen,
					     ctx->hash_algo);
        }
    }
  else if (ctx->encoding == PUBKEY_ENC_OAEP && lvalue
	   && ctx->op == PUBKEY_OP_ENCRYPT)
    {
      const void * value;
      size_t valuelen;

      if ( !(value=gcry_sexp_nth_data (lvalue, 1, &valuelen)) || !valuelen )
	rc = GPG_ERR_INV_OBJ;
      else
	{
	  gcry_sexp_t list;
          void *random_override = NULL;
          size_t random_override_len = 0;

	  /* Get HASH-ALGO. */
	  list = gcry_sexp_find_token (ldata, "hash-algo", 0);
	  if (list)
	    {
	      s = gcry_sexp_nth_data (list, 1, &n);
	      if (!s)
		rc = GPG_ERR_NO_OBJ;
	      else
		{
		  ctx->hash_algo = get_hash_algo (s, n);
		  if (!ctx->hash_algo)
		    rc = GPG_ERR_DIGEST_ALGO;
		}
	      gcry_sexp_release (list);
	      if (rc)
		goto leave;
	    }

	  /* Get LABEL. */
	  list = gcry_sexp_find_token (ldata, "label", 0);
	  if (list)
	    {
	      s = gcry_sexp_nth_data (list, 1, &n);
	      if (!s)
		rc = GPG_ERR_NO_OBJ;
	      else if (n > 0)
		{
		  ctx->label = gcry_malloc (n);
		  if (!ctx->label)
		    rc = gpg_err_code_from_syserror ();
		  else
		    {
		      memcpy (ctx->label, s, n);
		      ctx->labellen = n;
		    }
		}
	      gcry_sexp_release (list);
	      if (rc)
		goto leave;
	    }
          /* Get optional RANDOM-OVERRIDE.  */
          list = gcry_sexp_find_token (ldata, "random-override", 0);
          if (list)
            {
              s = gcry_sexp_nth_data (list, 1, &n);
              if (!s)
                rc = GPG_ERR_NO_OBJ;
              else if (n > 0)
                {
                  random_override = gcry_malloc (n);
                  if (!random_override)
                    rc = gpg_err_code_from_syserror ();
                  else
                    {
                      memcpy (random_override, s, n);
                      random_override_len = n;
                    }
                }
              gcry_sexp_release (list);
              if (rc)
                goto leave;
            }

	  rc = oaep_encode (ret_mpi, ctx->nbits, ctx->hash_algo,
			    value, valuelen,
			    ctx->label, ctx->labellen,
                            random_override, random_override_len);

          gcry_free (random_override);
	}
    }
  else if (ctx->encoding == PUBKEY_ENC_PSS && lhash
	   && ctx->op == PUBKEY_OP_SIGN)
    {
      if (gcry_sexp_length (lhash) != 3)
        rc = GPG_ERR_INV_OBJ;
      else if ( !(s=gcry_sexp_nth_data (lhash, 1, &n)) || !n )
        rc = GPG_ERR_INV_OBJ;
      else
        {
          const void * value;
          size_t valuelen;
          void *random_override = NULL;
          size_t random_override_len = 0;

	  ctx->hash_algo = get_hash_algo (s, n);

          if (!ctx->hash_algo)
            rc = GPG_ERR_DIGEST_ALGO;
          else if ( !(value=gcry_sexp_nth_data (lhash, 2, &valuelen))
                    || !valuelen )
            rc = GPG_ERR_INV_OBJ;
          else
	    {
	      gcry_sexp_t list;

	      /* Get SALT-LENGTH. */
	      list = gcry_sexp_find_token (ldata, "salt-length", 0);
	      if (list)
		{
		  s = gcry_sexp_nth_data (list, 1, &n);
		  if (!s)
		    {
		      rc = GPG_ERR_NO_OBJ;
		      goto leave;
		    }
		  ctx->saltlen = (unsigned int)strtoul (s, NULL, 10);
		  gcry_sexp_release (list);
		}

              /* Get optional RANDOM-OVERRIDE.  */
              list = gcry_sexp_find_token (ldata, "random-override", 0);
              if (list)
                {
                  s = gcry_sexp_nth_data (list, 1, &n);
                  if (!s)
                    rc = GPG_ERR_NO_OBJ;
                  else if (n > 0)
                    {
                      random_override = gcry_malloc (n);
                      if (!random_override)
                        rc = gpg_err_code_from_syserror ();
                      else
                        {
                          memcpy (random_override, s, n);
                          random_override_len = n;
                        }
                    }
                  gcry_sexp_release (list);
                  if (rc)
                    goto leave;
                }

              /* Encode the data.  (NBITS-1 is due to 8.1.1, step 1.) */
	      rc = pss_encode (ret_mpi, ctx->nbits - 1, ctx->hash_algo,
			       value, valuelen, ctx->saltlen,
                               random_override, random_override_len);

              gcry_free (random_override);
	    }
        }
    }
  else if (ctx->encoding == PUBKEY_ENC_PSS && lhash
	   && ctx->op == PUBKEY_OP_VERIFY)
    {
      if (gcry_sexp_length (lhash) != 3)
        rc = GPG_ERR_INV_OBJ;
      else if ( !(s=gcry_sexp_nth_data (lhash, 1, &n)) || !n )
        rc = GPG_ERR_INV_OBJ;
      else
        {
	  ctx->hash_algo = get_hash_algo (s, n);

          if (!ctx->hash_algo)
            rc = GPG_ERR_DIGEST_ALGO;
	  else
	    {
	      *ret_mpi = gcry_sexp_nth_mpi (lhash, 2, GCRYMPI_FMT_USG);
	      if (!*ret_mpi)
		rc = GPG_ERR_INV_OBJ;
	      ctx->verify_cmp = pss_verify_cmp;
	      ctx->verify_arg = *ret_mpi;
	    }
	}
    }
  else
    rc = GPG_ERR_CONFLICT;

 leave:
  gcry_sexp_release (ldata);
  gcry_sexp_release (lhash);
  gcry_sexp_release (lvalue);

  if (!rc)
    ctx->flags = parsed_flags;
  else
    {
      gcry_free (ctx->label);
      ctx->label = NULL;
    }

  return rc;
}

static void
init_encoding_ctx (struct pk_encoding_ctx *ctx, enum pk_operation op,
		   unsigned int nbits)
{
  ctx->op = op;
  ctx->nbits = nbits;
  ctx->encoding = PUBKEY_ENC_UNKNOWN;
  ctx->flags = 0;
  ctx->hash_algo = GCRY_MD_SHA1;
  ctx->label = NULL;
  ctx->labellen = 0;
  ctx->saltlen = 20;
  ctx->verify_cmp = NULL;
  ctx->verify_arg = NULL;
}


/*
   Do a PK encrypt operation

   Caller has to provide a public key as the SEXP pkey and data as a
   SEXP with just one MPI in it. Alternatively S_DATA might be a
   complex S-Expression, similar to the one used for signature
   verification.  This provides a flag which allows to handle PKCS#1
   block type 2 padding.  The function returns a sexp which may be
   passed to to pk_decrypt.

   Returns: 0 or an errorcode.

   s_data = See comment for sexp_data_to_mpi
   s_pkey = <key-as-defined-in-sexp_to_key>
   r_ciph = (enc-val
               (<algo>
                 (<param_name1> <mpi>)
                 ...
                 (<param_namen> <mpi>)
               ))

*/
gcry_error_t
gcry_pk_encrypt (gcry_sexp_t *r_ciph, gcry_sexp_t s_data, gcry_sexp_t s_pkey)
{
  gcry_mpi_t *pkey = NULL, data = NULL, *ciph = NULL;
  const char *algo_name, *algo_elems;
  struct pk_encoding_ctx ctx;
  gcry_err_code_t rc;
  gcry_pk_spec_t *pubkey = NULL;
  gcry_module_t module = NULL;

  *r_ciph = NULL;

  REGISTER_DEFAULT_PUBKEYS;

  /* Get the key. */
  rc = sexp_to_key (s_pkey, 0, NULL, &pkey, &module);
  if (rc)
    goto leave;

  gcry_assert (module);
  pubkey = (gcry_pk_spec_t *) module->spec;

  /* If aliases for the algorithm name exists, take the first one
     instead of the regular name to adhere to SPKI conventions.  We
     assume that the first alias name is the lowercase version of the
     regular one.  This change is required for compatibility with
     1.1.12 generated S-expressions. */
  algo_name = pubkey->aliases? *pubkey->aliases : NULL;
  if (!algo_name || !*algo_name)
    algo_name = pubkey->name;

  algo_elems = pubkey->elements_enc;

  /* Get the stuff we want to encrypt. */
  init_encoding_ctx (&ctx, PUBKEY_OP_ENCRYPT, gcry_pk_get_nbits (s_pkey));
  rc = sexp_data_to_mpi (s_data, &data, &ctx);
  if (rc)
    goto leave;

  /* Now we can encrypt DATA to CIPH. */
  ciph = gcry_calloc (strlen (algo_elems) + 1, sizeof (*ciph));
  if (!ciph)
    {
      rc = gpg_err_code_from_syserror ();
      goto leave;
    }
  rc = pubkey_encrypt (module->mod_id, ciph, data, pkey, ctx.flags);
  mpi_free (data);
  data = NULL;
  if (rc)
    goto leave;

  /* We did it.  Now build the return list */
  if (ctx.encoding == PUBKEY_ENC_OAEP
      || ctx.encoding == PUBKEY_ENC_PKCS1)
    {
      /* We need to make sure to return the correct length to avoid
         problems with missing leading zeroes.  We know that this
         encoding does only make sense with RSA thus we don't need to
         build the S-expression on the fly.  */
      unsigned char *em;
      size_t emlen = (ctx.nbits+7)/8;

      rc = octet_string_from_mpi (&em, NULL, ciph[0], emlen);
      if (rc)
        goto leave;
      rc = gcry_err_code (gcry_sexp_build (r_ciph, NULL,
                                           "(enc-val(%s(a%b)))",
                                           algo_name, (int)emlen, em));
      gcry_free (em);
      if (rc)
        goto leave;
    }
  else
    {
      char *string, *p;
      int i;
      size_t nelem = strlen (algo_elems);
      size_t needed = 19 + strlen (algo_name) + (nelem * 5);
      void **arg_list;

      /* Build the string.  */
      string = p = gcry_malloc (needed);
      if (!string)
        {
          rc = gpg_err_code_from_syserror ();
          goto leave;
        }
      p = stpcpy ( p, "(enc-val(" );
      p = stpcpy ( p, algo_name );
      for (i=0; algo_elems[i]; i++ )
        {
          *p++ = '(';
          *p++ = algo_elems[i];
          p = stpcpy ( p, "%m)" );
        }
      strcpy ( p, "))" );

      /* And now the ugly part: We don't have a function to pass an
       * array to a format string, so we have to do it this way :-(.  */
      /* FIXME: There is now such a format specifier, so we can
         change the code to be more clear. */
      arg_list = calloc (nelem, sizeof *arg_list);
      if (!arg_list)
        {
          rc = gpg_err_code_from_syserror ();
          goto leave;
        }

      for (i = 0; i < nelem; i++)
        arg_list[i] = ciph + i;

      rc = gcry_sexp_build_array (r_ciph, NULL, string, arg_list);
      free (arg_list);
      if (rc)
        BUG ();
      gcry_free (string);
    }

 leave:
  if (pkey)
    {
      release_mpi_array (pkey);
      gcry_free (pkey);
    }

  if (ciph)
    {
      release_mpi_array (ciph);
      gcry_free (ciph);
    }

  if (module)
    {
      ath_mutex_lock (&pubkeys_registered_lock);
      _gcry_module_release (module);
      ath_mutex_unlock (&pubkeys_registered_lock);
    }

  gcry_free (ctx.label);

  return gcry_error (rc);
}

/*
   Do a PK decrypt operation

   Caller has to provide a secret key as the SEXP skey and data in a
   format as created by gcry_pk_encrypt.  For historic reasons the
   function returns simply an MPI as an S-expression part; this is
   deprecated and the new method should be used which returns a real
   S-expressionl this is selected by adding at least an empty flags
   list to S_DATA.

   Returns: 0 or an errorcode.

   s_data = (enc-val
              [(flags [raw, pkcs1, oaep])]
              (<algo>
                (<param_name1> <mpi>)
                ...
                (<param_namen> <mpi>)
              ))
   s_skey = <key-as-defined-in-sexp_to_key>
   r_plain= Either an incomplete S-expression without the parentheses
            or if the flags list is used (even if empty) a real S-expression:
            (value PLAIN).  In raw mode (or no flags given) the returned value
            is to be interpreted as a signed MPI, thus it may have an extra
            leading zero octet even if not included in the original data.
            With pkcs1 or oaep decoding enabled the returned value is a
            verbatim octet string.
 */
gcry_error_t
gcry_pk_decrypt (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t s_skey)
{
  gcry_mpi_t *skey = NULL, *data = NULL, plain = NULL;
  unsigned char *unpad = NULL;
  size_t unpadlen = 0;
  int modern, flags;
  struct pk_encoding_ctx ctx;
  gcry_err_code_t rc;
  gcry_module_t module_enc = NULL, module_key = NULL;

  *r_plain = NULL;
  ctx.label = NULL;

  REGISTER_DEFAULT_PUBKEYS;

  rc = sexp_to_key (s_skey, 1, NULL, &skey, &module_key);
  if (rc)
    goto leave;

  init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT, gcry_pk_get_nbits (s_skey));
  rc = sexp_to_enc (s_data, &data, &module_enc, &modern, &flags, &ctx);
  if (rc)
    goto leave;

  if (module_key->mod_id != module_enc->mod_id)
    {
      rc = GPG_ERR_CONFLICT; /* Key algo does not match data algo. */
      goto leave;
    }

  rc = pubkey_decrypt (module_key->mod_id, &plain, data, skey, flags);
  if (rc)
    goto leave;

  /* Do un-padding if necessary. */
  switch (ctx.encoding)
    {
    case PUBKEY_ENC_PKCS1:
      rc = pkcs1_decode_for_encryption (&unpad, &unpadlen,
                                        gcry_pk_get_nbits (s_skey), plain);
      mpi_free (plain);
      plain = NULL;
      if (!rc)
        rc = gcry_err_code (gcry_sexp_build (r_plain, NULL, "(value %b)",
                                             (int)unpadlen, unpad));
      break;

    case PUBKEY_ENC_OAEP:
      rc = oaep_decode (&unpad, &unpadlen,
                        gcry_pk_get_nbits (s_skey), ctx.hash_algo,
			plain, ctx.label, ctx.labellen);
      mpi_free (plain);
      plain = NULL;
      if (!rc)
        rc = gcry_err_code (gcry_sexp_build (r_plain, NULL, "(value %b)",
                                             (int)unpadlen, unpad));
      break;

    default:
      /* Raw format.  For backward compatibility we need to assume a
         signed mpi by using the sexp format string "%m".  */
      rc = gcry_err_code (gcry_sexp_build
                          (r_plain, NULL, modern? "(value %m)" : "%m", plain));
      break;
    }

 leave:
  gcry_free (unpad);

  if (skey)
    {
      release_mpi_array (skey);
      gcry_free (skey);
    }

  mpi_free (plain);

  if (data)
    {
      release_mpi_array (data);
      gcry_free (data);
    }

  if (module_key || module_enc)
    {
      ath_mutex_lock (&pubkeys_registered_lock);
      if (module_key)
	_gcry_module_release (module_key);
      if (module_enc)
	_gcry_module_release (module_enc);
      ath_mutex_unlock (&pubkeys_registered_lock);
    }

  gcry_free (ctx.label);

  return gcry_error (rc);
}



/*
   Create a signature.

   Caller has to provide a secret key as the SEXP skey and data
   expressed as a SEXP list hash with only one element which should
   instantly be available as a MPI. Alternatively the structure given
   below may be used for S_HASH, it provides the abiliy to pass flags
   to the operation; the flags defined by now are "pkcs1" which does
   PKCS#1 block type 1 style padding and "pss" for PSS encoding.

   Returns: 0 or an errorcode.
            In case of 0 the function returns a new SEXP with the
            signature value; the structure of this signature depends on the
            other arguments but is always suitable to be passed to
            gcry_pk_verify

   s_hash = See comment for sexp_data_to_mpi

   s_skey = <key-as-defined-in-sexp_to_key>
   r_sig  = (sig-val
              (<algo>
                (<param_name1> <mpi>)
                ...
                (<param_namen> <mpi>))
             [(hash algo)])

  Note that (hash algo) in R_SIG is not used.
*/
gcry_error_t
gcry_pk_sign (gcry_sexp_t *r_sig, gcry_sexp_t s_hash, gcry_sexp_t s_skey)
{
  gcry_mpi_t *skey = NULL, hash = NULL, *result = NULL;
  gcry_pk_spec_t *pubkey = NULL;
  gcry_module_t module = NULL;
  const char *algo_name, *algo_elems;
  struct pk_encoding_ctx ctx;
  int i;
  gcry_err_code_t rc;

  *r_sig = NULL;

  REGISTER_DEFAULT_PUBKEYS;

  rc = sexp_to_key (s_skey, 1, NULL, &skey, &module);
  if (rc)
    goto leave;

  gcry_assert (module);
  pubkey = (gcry_pk_spec_t *) module->spec;
  algo_name = pubkey->aliases? *pubkey->aliases : NULL;
  if (!algo_name || !*algo_name)
    algo_name = pubkey->name;

  algo_elems = pubkey->elements_sig;

  /* Get the stuff we want to sign.  Note that pk_get_nbits does also
      work on a private key. */
  init_encoding_ctx (&ctx, PUBKEY_OP_SIGN, gcry_pk_get_nbits (s_skey));
  rc = sexp_data_to_mpi (s_hash, &hash, &ctx);
  if (rc)
    goto leave;

  result = gcry_calloc (strlen (algo_elems) + 1, sizeof (*result));
  if (!result)
    {
      rc = gpg_err_code_from_syserror ();
      goto leave;
    }
  rc = pubkey_sign (module->mod_id, result, hash, skey);
  if (rc)
    goto leave;

  if (ctx.encoding == PUBKEY_ENC_PSS
      || ctx.encoding == PUBKEY_ENC_PKCS1)
    {
      /* We need to make sure to return the correct length to avoid
         problems with missing leading zeroes.  We know that this
         encoding does only make sense with RSA thus we don't need to
         build the S-expression on the fly.  */
      unsigned char *em;
      size_t emlen = (ctx.nbits+7)/8;

      rc = octet_string_from_mpi (&em, NULL, result[0], emlen);
      if (rc)
        goto leave;
      rc = gcry_err_code (gcry_sexp_build (r_sig, NULL,
                                           "(sig-val(%s(s%b)))",
                                           algo_name, (int)emlen, em));
      gcry_free (em);
      if (rc)
        goto leave;
    }
  else
    {
      /* General purpose output encoding.  Do it on the fly.  */
      char *string, *p;
      size_t nelem, needed = strlen (algo_name) + 20;
      void **arg_list;

      nelem = strlen (algo_elems);

      /* Count elements, so that we can allocate enough space. */
      needed += 10 * nelem;

      /* Build the string. */
      string = p = gcry_malloc (needed);
      if (!string)
        {
          rc = gpg_err_code_from_syserror ();
          goto leave;
        }
      p = stpcpy (p, "(sig-val(");
      p = stpcpy (p, algo_name);
      for (i = 0; algo_elems[i]; i++)
        {
          *p++ = '(';
          *p++ = algo_elems[i];
          p = stpcpy (p, "%M)");
        }
      strcpy (p, "))");

      arg_list = calloc (nelem, sizeof *arg_list);
      if (!arg_list)
        {
          rc = gpg_err_code_from_syserror ();
          goto leave;
        }

      for (i = 0; i < nelem; i++)
        arg_list[i] = result + i;

      rc = gcry_sexp_build_array (r_sig, NULL, string, arg_list);
      free (arg_list);
      if (rc)
        BUG ();
      gcry_free (string);
    }

 leave:
  if (skey)
    {
      release_mpi_array (skey);
      gcry_free (skey);
    }

  if (hash)
    mpi_free (hash);

  if (result)
    {
      release_mpi_array (result);
      gcry_free (result);
    }

  return gcry_error (rc);
}


/*
   Verify a signature.

   Caller has to supply the public key pkey, the signature sig and his
   hashvalue data.  Public key has to be a standard public key given
   as an S-Exp, sig is a S-Exp as returned from gcry_pk_sign and data
   must be an S-Exp like the one in sign too.  */
gcry_error_t
gcry_pk_verify (gcry_sexp_t s_sig, gcry_sexp_t s_hash, gcry_sexp_t s_pkey)
{
  gcry_module_t module_key = NULL, module_sig = NULL;
  gcry_mpi_t *pkey = NULL, hash = NULL, *sig = NULL;
  struct pk_encoding_ctx ctx;
  gcry_err_code_t rc;

  REGISTER_DEFAULT_PUBKEYS;

  rc = sexp_to_key (s_pkey, 0, NULL, &pkey, &module_key);
  if (rc)
    goto leave;

  rc = sexp_to_sig (s_sig, &sig, &module_sig);
  if (rc)
    goto leave;

  /* Fixme: Check that the algorithm of S_SIG is compatible to the one
     of S_PKEY.  */

  if (module_key->mod_id != module_sig->mod_id)
    {
      rc = GPG_ERR_CONFLICT;
      goto leave;
    }

  /* Get the stuff we want to verify. */
  init_encoding_ctx (&ctx, PUBKEY_OP_VERIFY, gcry_pk_get_nbits (s_pkey));
  rc = sexp_data_to_mpi (s_hash, &hash, &ctx);
  if (rc)
    goto leave;

  rc = pubkey_verify (module_key->mod_id, hash, sig, pkey,
		      ctx.verify_cmp, &ctx);

 leave:
  if (pkey)
    {
      release_mpi_array (pkey);
      gcry_free (pkey);
    }
  if (sig)
    {
      release_mpi_array (sig);
      gcry_free (sig);
    }
  if (hash)
    mpi_free (hash);

  if (module_key || module_sig)
    {
      ath_mutex_lock (&pubkeys_registered_lock);
      if (module_key)
	_gcry_module_release (module_key);
      if (module_sig)
	_gcry_module_release (module_sig);
      ath_mutex_unlock (&pubkeys_registered_lock);
    }

  return gcry_error (rc);
}


/*
   Test a key.

   This may be used either for a public or a secret key to see whether
   the internal structure is okay.

   Returns: 0 or an errorcode.

   s_key = <key-as-defined-in-sexp_to_key> */
gcry_error_t
gcry_pk_testkey (gcry_sexp_t s_key)
{
  gcry_module_t module = NULL;
  gcry_mpi_t *key = NULL;
  gcry_err_code_t rc;

  REGISTER_DEFAULT_PUBKEYS;

  /* Note we currently support only secret key checking. */
  rc = sexp_to_key (s_key, 1, NULL, &key, &module);
  if (! rc)
    {
      rc = pubkey_check_secret_key (module->mod_id, key);
      release_mpi_array (key);
      gcry_free (key);
    }
  return gcry_error (rc);
}


/*
  Create a public key pair and return it in r_key.
  How the key is created depends on s_parms:
  (genkey
   (algo
     (parameter_name_1 ....)
      ....
     (parameter_name_n ....)
  ))
  The key is returned in a format depending on the
  algorithm. Both, private and secret keys are returned
  and optionally some additional informatin.
  For elgamal we return this structure:
  (key-data
   (public-key
     (elg
 	(p <mpi>)
 	(g <mpi>)
 	(y <mpi>)
     )
   )
   (private-key
     (elg
 	(p <mpi>)
 	(g <mpi>)
 	(y <mpi>)
 	(x <mpi>)
     )
   )
   (misc-key-info
      (pm1-factors n1 n2 ... nn)
   ))
 */
gcry_error_t
gcry_pk_genkey (gcry_sexp_t *r_key, gcry_sexp_t s_parms)
{
  gcry_pk_spec_t *pubkey = NULL;
  gcry_module_t module = NULL;
  gcry_sexp_t list = NULL;
  gcry_sexp_t l2 = NULL;
  gcry_sexp_t l3 = NULL;
  char *name = NULL;
  size_t n;
  gcry_err_code_t rc = GPG_ERR_NO_ERROR;
  int i, j;
  const char *algo_name = NULL;
  int algo;
  const char *sec_elems = NULL, *pub_elems = NULL;
  gcry_mpi_t skey[12];
  gcry_mpi_t *factors = NULL;
  gcry_sexp_t extrainfo = NULL;
  unsigned int nbits = 0;
  unsigned long use_e = 0;

  skey[0] = NULL;
  *r_key = NULL;

  REGISTER_DEFAULT_PUBKEYS;

  list = gcry_sexp_find_token (s_parms, "genkey", 0);
  if (!list)
    {
      rc = GPG_ERR_INV_OBJ; /* Does not contain genkey data. */
      goto leave;
    }

  l2 = gcry_sexp_cadr (list);
  gcry_sexp_release (list);
  list = l2;
  l2 = NULL;
  if (! list)
    {
      rc = GPG_ERR_NO_OBJ; /* No cdr for the genkey. */
      goto leave;
    }

  name = _gcry_sexp_nth_string (list, 0);
  if (!name)
    {
      rc = GPG_ERR_INV_OBJ; /* Algo string missing.  */
      goto leave;
    }

  ath_mutex_lock (&pubkeys_registered_lock);
  module = gcry_pk_lookup_name (name);
  ath_mutex_unlock (&pubkeys_registered_lock);
  gcry_free (name);
  name = NULL;
  if (!module)
    {
      rc = GPG_ERR_PUBKEY_ALGO; /* Unknown algorithm.  */
      goto leave;
    }

  pubkey = (gcry_pk_spec_t *) module->spec;
  algo = module->mod_id;
  algo_name = pubkey->aliases? *pubkey->aliases : NULL;
  if (!algo_name || !*algo_name)
    algo_name = pubkey->name;
  pub_elems = pubkey->elements_pkey;
  sec_elems = pubkey->elements_skey;
  if (strlen (sec_elems) >= DIM(skey))
    BUG ();

  /* Handle the optional rsa-use-e element.  Actually this belong into
     the algorithm module but we have this parameter in the public
     module API, so we need to parse it right here.  */
  l2 = gcry_sexp_find_token (list, "rsa-use-e", 0);
  if (l2)
    {
      char buf[50];
      const char *s;

      s = gcry_sexp_nth_data (l2, 1, &n);
      if ( !s || n >= DIM (buf) - 1 )
        {
          rc = GPG_ERR_INV_OBJ; /* No value or value too large.  */
          goto leave;
        }
      memcpy (buf, s, n);
      buf[n] = 0;
      use_e = strtoul (buf, NULL, 0);
      gcry_sexp_release (l2);
      l2 = NULL;
    }
  else
    use_e = 65537; /* Not given, use the value generated by old versions. */


  /* Get the "nbits" parameter.  */
  l2 = gcry_sexp_find_token (list, "nbits", 0);
  if (l2)
    {
      char buf[50];
      const char *s;

      s = gcry_sexp_nth_data (l2, 1, &n);
      if (!s || n >= DIM (buf) - 1 )
        {
          rc = GPG_ERR_INV_OBJ; /* NBITS given without a cdr.  */
          goto leave;
        }
      memcpy (buf, s, n);
      buf[n] = 0;
      nbits = (unsigned int)strtoul (buf, NULL, 0);
      gcry_sexp_release (l2); l2 = NULL;
    }
  else
    nbits = 0;

  /* Pass control to the algorithm module. */
  rc = pubkey_generate (module->mod_id, nbits, use_e, list, skey,
                        &factors, &extrainfo);
  gcry_sexp_release (list); list = NULL;
  if (rc)
    goto leave;

  /* Key generation succeeded: Build an S-expression.  */
  {
    char *string, *p;
    size_t nelem=0, nelem_cp = 0, needed=0;
    gcry_mpi_t mpis[30];
    int percent_s_idx = -1;

    /* Estimate size of format string.  */
    nelem = strlen (pub_elems) + strlen (sec_elems);
    if (factors)
      {
        for (i = 0; factors[i]; i++)
          nelem++;
      }
    nelem_cp = nelem;

    needed += nelem * 10;
    /* (+5 is for EXTRAINFO ("%S")).  */
    needed += 2 * strlen (algo_name) + 300 + 5;
    if (nelem > DIM (mpis))
      BUG ();

    /* Build the string. */
    nelem = 0;
    string = p = gcry_malloc (needed);
    if (!string)
      {
        rc = gpg_err_code_from_syserror ();
        goto leave;
      }
    p = stpcpy (p, "(key-data");
    p = stpcpy (p, "(public-key(");
    p = stpcpy (p, algo_name);
    for(i = 0; pub_elems[i]; i++)
      {
        *p++ = '(';
        *p++ = pub_elems[i];
        p = stpcpy (p, "%m)");
        mpis[nelem++] = skey[i];
      }
    if (extrainfo && (algo == GCRY_PK_ECDSA || algo == GCRY_PK_ECDH))
      {
        /* Very ugly hack to insert the used curve parameter into the
           list of public key parameters.  */
        percent_s_idx = nelem;
        p = stpcpy (p, "%S");
      }
    p = stpcpy (p, "))");
    p = stpcpy (p, "(private-key(");
    p = stpcpy (p, algo_name);
    for (i = 0; sec_elems[i]; i++)
      {
        *p++ = '(';
        *p++ = sec_elems[i];
        p = stpcpy (p, "%m)");
        mpis[nelem++] = skey[i];
      }
    p = stpcpy (p, "))");

    /* Hack to make release_mpi_array() work.  */
    skey[i] = NULL;

    if (extrainfo && percent_s_idx == -1)
      {
        /* If we have extrainfo we should not have any factors.  */
        p = stpcpy (p, "%S");
      }
    else if (factors && factors[0])
      {
        p = stpcpy (p, "(misc-key-info(pm1-factors");
        for(i = 0; factors[i]; i++)
          {
            p = stpcpy (p, "%m");
            mpis[nelem++] = factors[i];
          }
        p = stpcpy (p, "))");
      }
    strcpy (p, ")");
    gcry_assert (p - string < needed);

    while (nelem < DIM (mpis))
      mpis[nelem++] = NULL;

    {
      int elem_n = strlen (pub_elems) + strlen (sec_elems);
      void **arg_list;

      /* Allocate one extra for EXTRAINFO ("%S").  */
      arg_list = gcry_calloc (nelem_cp+1, sizeof *arg_list);
      if (!arg_list)
        {
          rc = gpg_err_code_from_syserror ();
          goto leave;
        }
      for (i = j = 0; i < elem_n; i++)
        {
          if (i == percent_s_idx)
            arg_list[j++] = &extrainfo;
          arg_list[j++] = mpis + i;
        }
      if (extrainfo && percent_s_idx == -1)
        arg_list[j] = &extrainfo;
      else if (factors && factors[0])
        {
          for (; i < nelem_cp; i++)
            arg_list[j++] = factors + i - elem_n;
        }
      rc = gcry_sexp_build_array (r_key, NULL, string, arg_list);
      gcry_free (arg_list);
      if (rc)
	BUG ();
      gcry_assert (DIM (mpis) == 30); /* Reminder to make sure that
                                         the array gets increased if
                                         new parameters are added. */
    }
    gcry_free (string);
  }

 leave:
  gcry_free (name);
  gcry_sexp_release (extrainfo);
  release_mpi_array (skey);
  /* Don't free SKEY itself, it is an stack allocated array. */

  if (factors)
    {
      release_mpi_array ( factors );
      gcry_free (factors);
    }

  gcry_sexp_release (l3);
  gcry_sexp_release (l2);
  gcry_sexp_release (list);

  if (module)
    {
      ath_mutex_lock (&pubkeys_registered_lock);
      _gcry_module_release (module);
      ath_mutex_unlock (&pubkeys_registered_lock);
    }

  return gcry_error (rc);
}


/*
   Get the number of nbits from the public key.

   Hmmm: Should we have really this function or is it better to have a
   more general function to retrieve different properties of the key?  */
unsigned int
gcry_pk_get_nbits (gcry_sexp_t key)
{
  gcry_module_t module = NULL;
  gcry_pk_spec_t *pubkey;
  gcry_mpi_t *keyarr = NULL;
  unsigned int nbits = 0;
  gcry_err_code_t rc;

  REGISTER_DEFAULT_PUBKEYS;

  rc = sexp_to_key (key, 0, NULL, &keyarr, &module);
  if (rc == GPG_ERR_INV_OBJ)
    rc = sexp_to_key (key, 1, NULL, &keyarr, &module);
  if (rc)
    return 0; /* Error - 0 is a suitable indication for that. */

  pubkey = (gcry_pk_spec_t *) module->spec;
  nbits = (*pubkey->get_nbits) (module->mod_id, keyarr);

  ath_mutex_lock (&pubkeys_registered_lock);
  _gcry_module_release (module);
  ath_mutex_unlock (&pubkeys_registered_lock);

  release_mpi_array (keyarr);
  gcry_free (keyarr);

  return nbits;
}


/* Return the so called KEYGRIP which is the SHA-1 hash of the public
   key parameters expressed in a way depending on the algorithm.

   ARRAY must either be 20 bytes long or NULL; in the latter case a
   newly allocated array of that size is returned, otherwise ARRAY or
   NULL is returned to indicate an error which is most likely an
   unknown algorithm.  The function accepts public or secret keys. */
unsigned char *
gcry_pk_get_keygrip (gcry_sexp_t key, unsigned char *array)
{
  gcry_sexp_t list = NULL, l2 = NULL;
  gcry_pk_spec_t *pubkey = NULL;
  gcry_module_t module = NULL;
  pk_extra_spec_t *extraspec;
  const char *s;
  char *name = NULL;
  int idx;
  const char *elems;
  gcry_md_hd_t md = NULL;
  int okay = 0;

  REGISTER_DEFAULT_PUBKEYS;

  /* Check that the first element is valid. */
  list = gcry_sexp_find_token (key, "public-key", 0);
  if (! list)
    list = gcry_sexp_find_token (key, "private-key", 0);
  if (! list)
    list = gcry_sexp_find_token (key, "protected-private-key", 0);
  if (! list)
    list = gcry_sexp_find_token (key, "shadowed-private-key", 0);
  if (! list)
    return NULL; /* No public- or private-key object. */

  l2 = gcry_sexp_cadr (list);
  gcry_sexp_release (list);
  list = l2;
  l2 = NULL;

  name = _gcry_sexp_nth_string (list, 0);
  if (!name)
    goto fail; /* Invalid structure of object. */

  ath_mutex_lock (&pubkeys_registered_lock);
  module = gcry_pk_lookup_name (name);
  ath_mutex_unlock (&pubkeys_registered_lock);

  if (!module)
    goto fail; /* Unknown algorithm.  */

  pubkey = (gcry_pk_spec_t *) module->spec;
  extraspec = module->extraspec;

  elems = pubkey->elements_grip;
  if (!elems)
    goto fail; /* No grip parameter.  */

  if (gcry_md_open (&md, GCRY_MD_SHA1, 0))
    goto fail;

  if (extraspec && extraspec->comp_keygrip)
    {
      /* Module specific method to compute a keygrip.  */
      if (extraspec->comp_keygrip (md, list))
        goto fail;
    }
  else
    {
      /* Generic method to compute a keygrip.  */
      for (idx = 0, s = elems; *s; s++, idx++)
        {
          const char *data;
          size_t datalen;
          char buf[30];

          l2 = gcry_sexp_find_token (list, s, 1);
          if (! l2)
            goto fail;
          data = gcry_sexp_nth_data (l2, 1, &datalen);
          if (! data)
            goto fail;

          snprintf (buf, sizeof buf, "(1:%c%u:", *s, (unsigned int)datalen);
          gcry_md_write (md, buf, strlen (buf));
          gcry_md_write (md, data, datalen);
          gcry_sexp_release (l2);
          l2 = NULL;
          gcry_md_write (md, ")", 1);
        }
    }

  if (!array)
    {
      array = gcry_malloc (20);
      if (! array)
        goto fail;
    }

  memcpy (array, gcry_md_read (md, GCRY_MD_SHA1), 20);
  okay = 1;

 fail:
  gcry_free (name);
  gcry_sexp_release (l2);
  gcry_md_close (md);
  gcry_sexp_release (list);
  return okay? array : NULL;
}



const char *
gcry_pk_get_curve (gcry_sexp_t key, int iterator, unsigned int *r_nbits)
{
  gcry_mpi_t *pkey = NULL;
  gcry_sexp_t list = NULL;
  gcry_sexp_t l2;
  gcry_module_t module = NULL;
  pk_extra_spec_t *extraspec;
  char *name = NULL;
  const char *result = NULL;
  int want_private = 1;

  if (r_nbits)
    *r_nbits = 0;

  REGISTER_DEFAULT_PUBKEYS;

  if (key)
    {
      iterator = 0;

      /* Check that the first element is valid. */
      list = gcry_sexp_find_token (key, "public-key", 0);
      if (list)
        want_private = 0;
      if (!list)
        list = gcry_sexp_find_token (key, "private-key", 0);
      if (!list)
        return NULL; /* No public- or private-key object. */

      l2 = gcry_sexp_cadr (list);
      gcry_sexp_release (list);
      list = l2;
      l2 = NULL;

      name = _gcry_sexp_nth_string (list, 0);
      if (!name)
        goto leave; /* Invalid structure of object. */

      /* Get the key.  We pass the names of the parameters for
         override_elems; this allows to call this function without the
         actual public key parameter.  */
      if (sexp_to_key (key, want_private, "pabgn", &pkey, &module))
        goto leave;
    }
  else
    {
      ath_mutex_lock (&pubkeys_registered_lock);
      module = gcry_pk_lookup_name ("ecc");
      ath_mutex_unlock (&pubkeys_registered_lock);
      if (!module)
        goto leave;
    }

  extraspec = module->extraspec;
  if (!extraspec || !extraspec->get_curve)
    goto leave;

  result = extraspec->get_curve (pkey, iterator, r_nbits);

 leave:
  if (pkey)
    {
      release_mpi_array (pkey);
      gcry_free (pkey);
    }
  if (module)
    {
      ath_mutex_lock (&pubkeys_registered_lock);
      _gcry_module_release (module);
      ath_mutex_unlock (&pubkeys_registered_lock);
    }
  gcry_free (name);
  gcry_sexp_release (list);
  return result;
}



gcry_sexp_t
gcry_pk_get_param (int algo, const char *name)
{
  gcry_module_t module = NULL;
  pk_extra_spec_t *extraspec;
  gcry_sexp_t result = NULL;

  if (algo != GCRY_PK_ECDSA && algo != GCRY_PK_ECDH)
    return NULL;

  REGISTER_DEFAULT_PUBKEYS;

  ath_mutex_lock (&pubkeys_registered_lock);
  module = gcry_pk_lookup_name ("ecc");
  ath_mutex_unlock (&pubkeys_registered_lock);
  if (module)
    {
      extraspec = module->extraspec;
      if (extraspec && extraspec->get_curve_param)
        result = extraspec->get_curve_param (name);

      ath_mutex_lock (&pubkeys_registered_lock);
      _gcry_module_release (module);
      ath_mutex_unlock (&pubkeys_registered_lock);
    }
  return result;
}



gcry_error_t
gcry_pk_ctl (int cmd, void *buffer, size_t buflen)
{
  gcry_err_code_t err = GPG_ERR_NO_ERROR;

  REGISTER_DEFAULT_PUBKEYS;

  switch (cmd)
    {
    case GCRYCTL_DISABLE_ALGO:
      /* This one expects a buffer pointing to an integer with the
         algo number.  */
      if ((! buffer) || (buflen != sizeof (int)))
	err = GPG_ERR_INV_ARG;
      else
	disable_pubkey_algo (*((int *) buffer));
      break;

    default:
      err = GPG_ERR_INV_OP;
    }

  return gcry_error (err);
}


/* Return information about the given algorithm

   WHAT selects the kind of information returned:

    GCRYCTL_TEST_ALGO:
        Returns 0 when the specified algorithm is available for use.
        Buffer must be NULL, nbytes  may have the address of a variable
        with the required usage of the algorithm. It may be 0 for don't
        care or a combination of the GCRY_PK_USAGE_xxx flags;

    GCRYCTL_GET_ALGO_USAGE:
        Return the usage flags for the given algo.  An invalid algo
        returns 0.  Disabled algos are ignored here because we
        only want to know whether the algo is at all capable of
        the usage.

   Note: Because this function is in most cases used to return an
   integer value, we can make it easier for the caller to just look at
   the return value.  The caller will in all cases consult the value
   and thereby detecting whether a error occurred or not (i.e. while
   checking the block size) */
gcry_error_t
gcry_pk_algo_info (int algorithm, int what, void *buffer, size_t *nbytes)
{
  gcry_err_code_t err = GPG_ERR_NO_ERROR;

  switch (what)
    {
    case GCRYCTL_TEST_ALGO:
      {
	int use = nbytes ? *nbytes : 0;
	if (buffer)
	  err = GPG_ERR_INV_ARG;
	else if (check_pubkey_algo (algorithm, use))
	  err = GPG_ERR_PUBKEY_ALGO;
	break;
      }

    case GCRYCTL_GET_ALGO_USAGE:
      {
	gcry_module_t pubkey;
	int use = 0;

	REGISTER_DEFAULT_PUBKEYS;

	ath_mutex_lock (&pubkeys_registered_lock);
	pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
	if (pubkey)
	  {
	    use = ((gcry_pk_spec_t *) pubkey->spec)->use;
	    _gcry_module_release (pubkey);
	  }
	ath_mutex_unlock (&pubkeys_registered_lock);

	/* FIXME? */
	*nbytes = use;

	break;
      }

    case GCRYCTL_GET_ALGO_NPKEY:
      {
	/* FIXME?  */
	int npkey = pubkey_get_npkey (algorithm);
	*nbytes = npkey;
	break;
      }
    case GCRYCTL_GET_ALGO_NSKEY:
      {
	/* FIXME?  */
	int nskey = pubkey_get_nskey (algorithm);
	*nbytes = nskey;
	break;
      }
    case GCRYCTL_GET_ALGO_NSIGN:
      {
	/* FIXME?  */
	int nsign = pubkey_get_nsig (algorithm);
	*nbytes = nsign;
	break;
      }
    case GCRYCTL_GET_ALGO_NENCR:
      {
	/* FIXME?  */
	int nencr = pubkey_get_nenc (algorithm);
	*nbytes = nencr;
	break;
      }

    default:
      err = GPG_ERR_INV_OP;
    }

  return gcry_error (err);
}


/* Explicitly initialize this module.  */
gcry_err_code_t
_gcry_pk_init (void)
{
  gcry_err_code_t err = GPG_ERR_NO_ERROR;

  REGISTER_DEFAULT_PUBKEYS;

  return err;
}


gcry_err_code_t
_gcry_pk_module_lookup (int algorithm, gcry_module_t *module)
{
  gcry_err_code_t err = GPG_ERR_NO_ERROR;
  gcry_module_t pubkey;

  REGISTER_DEFAULT_PUBKEYS;

  ath_mutex_lock (&pubkeys_registered_lock);
  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  if (pubkey)
    *module = pubkey;
  else
    err = GPG_ERR_PUBKEY_ALGO;
  ath_mutex_unlock (&pubkeys_registered_lock);

  return err;
}


void
_gcry_pk_module_release (gcry_module_t module)
{
  ath_mutex_lock (&pubkeys_registered_lock);
  _gcry_module_release (module);
  ath_mutex_unlock (&pubkeys_registered_lock);
}

/* Get a list consisting of the IDs of the loaded pubkey modules.  If
   LIST is zero, write the number of loaded pubkey modules to
   LIST_LENGTH and return.  If LIST is non-zero, the first
   *LIST_LENGTH algorithm IDs are stored in LIST, which must be of
   according size.  In case there are less pubkey modules than
   *LIST_LENGTH, *LIST_LENGTH is updated to the correct number.  */
gcry_error_t
gcry_pk_list (int *list, int *list_length)
{
  gcry_err_code_t err = GPG_ERR_NO_ERROR;

  ath_mutex_lock (&pubkeys_registered_lock);
  err = _gcry_module_list (pubkeys_registered, list, list_length);
  ath_mutex_unlock (&pubkeys_registered_lock);

  return err;
}


/* Run the selftests for pubkey algorithm ALGO with optional reporting
   function REPORT.  */
gpg_error_t
_gcry_pk_selftest (int algo, int extended, selftest_report_func_t report)
{
  gcry_module_t module = NULL;
  pk_extra_spec_t *extraspec = NULL;
  gcry_err_code_t ec = 0;

  REGISTER_DEFAULT_PUBKEYS;

  ath_mutex_lock (&pubkeys_registered_lock);
  module = _gcry_module_lookup_id (pubkeys_registered, algo);
  if (module && !(module->flags & FLAG_MODULE_DISABLED))
    extraspec = module->extraspec;
  ath_mutex_unlock (&pubkeys_registered_lock);
  if (extraspec && extraspec->selftest)
    ec = extraspec->selftest (algo, extended, report);
  else
    {
      ec = GPG_ERR_PUBKEY_ALGO;
      if (report)
        report ("pubkey", algo, "module",
                module && !(module->flags & FLAG_MODULE_DISABLED)?
                "no selftest available" :
                module? "algorithm disabled" : "algorithm not found");
    }

  if (module)
    {
      ath_mutex_lock (&pubkeys_registered_lock);
      _gcry_module_release (module);
      ath_mutex_unlock (&pubkeys_registered_lock);
    }
  return gpg_error (ec);
}


/* This function is only used by ac.c!  */
gcry_err_code_t
_gcry_pk_get_elements (int algo, char **enc, char **sig)
{
  gcry_module_t pubkey;
  gcry_pk_spec_t *spec;
  gcry_err_code_t err;
  char *enc_cp;
  char *sig_cp;

  REGISTER_DEFAULT_PUBKEYS;

  enc_cp = NULL;
  sig_cp = NULL;
  spec = NULL;

  pubkey = _gcry_module_lookup_id (pubkeys_registered, algo);
  if (! pubkey)
    {
      err = GPG_ERR_INTERNAL;
      goto out;
    }
  spec = pubkey->spec;

  if (enc)
    {
      enc_cp = strdup (spec->elements_enc);
      if (! enc_cp)
	{
	  err = gpg_err_code_from_syserror ();
	  goto out;
	}
    }

  if (sig)
    {
      sig_cp = strdup (spec->elements_sig);
      if (! sig_cp)
	{
	  err = gpg_err_code_from_syserror ();
	  goto out;
	}
    }

  if (enc)
    *enc = enc_cp;
  if (sig)
    *sig = sig_cp;
  err = 0;

 out:

  _gcry_module_release (pubkey);
  if (err)
    {
      free (enc_cp);
      free (sig_cp);
    }

  return err;
}