summaryrefslogtreecommitdiff
path: root/plugins/MirOTR/Libgcrypt/cipher/ac.c
blob: ee9498b23d16701b1db2b1a1c97049833f2e9df0 (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
/* ac.c - Alternative interface for asymmetric cryptography.
   Copyright (C) 2003, 2004, 2005, 2006
                 2007, 2008  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 <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stddef.h>

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



/* At the moment the ac interface is a wrapper around the pk
   interface, but this might change somewhen in the future, depending
   on how many people prefer the ac interface.  */

/* Mapping of flag numbers to the according strings as it is expected
   for S-expressions.  */
static struct number_string
{
  int number;
  const char *string;
} ac_flags[] =
  {
    { GCRY_AC_FLAG_NO_BLINDING, "no-blinding" },
  };

/* The positions in this list correspond to the values contained in
   the gcry_ac_key_type_t enumeration list.  */
static const char *ac_key_identifiers[] =
  {
    "private-key",
    "public-key"
  };

/* These specifications are needed for key-pair generation; the caller
   is allowed to pass additional, algorithm-specific `specs' to
   gcry_ac_key_pair_generate.  This list is used for decoding the
   provided values according to the selected algorithm.  */
struct gcry_ac_key_generate_spec
{
  int algorithm;		/* Algorithm for which this flag is
				   relevant.  */
  const char *name;		/* Name of this flag.  */
  size_t offset;		/* Offset in the cipher-specific spec
				   structure at which the MPI value
				   associated with this flag is to be
				   found.  */
} ac_key_generate_specs[] =
  {
    { GCRY_AC_RSA, "rsa-use-e", offsetof (gcry_ac_key_spec_rsa_t, e) },
    { 0 }
  };

/* Handle structure.  */
struct gcry_ac_handle
{
  int algorithm;		/* Algorithm ID associated with this
				   handle.  */
  const char *algorithm_name;	/* Name of the algorithm.  */
  unsigned int flags;		/* Flags, not used yet.  */
  gcry_module_t module;	        /* Reference to the algorithm
				   module.  */
};

/* A named MPI value.  */
typedef struct gcry_ac_mpi
{
  char *name;			/* Self-maintained copy of name.  */
  gcry_mpi_t mpi;		/* MPI value.         */
  unsigned int flags;		/* Flags.             */
} gcry_ac_mpi_t;

/* A data set, that is simply a list of named MPI values.  */
struct gcry_ac_data
{
  gcry_ac_mpi_t *data;		/* List of named values.      */
  unsigned int data_n;		/* Number of values in DATA.  */
};

/* A single key.  */
struct gcry_ac_key
{
  gcry_ac_data_t data;		/* Data in native ac structure.  */
  gcry_ac_key_type_t type;	/* Type of the key.              */
};

/* A key pair.  */
struct gcry_ac_key_pair
{
  gcry_ac_key_t public;
  gcry_ac_key_t secret;
};



/* 
 * Functions for working with data sets.
 */

/* Creates a new, empty data set and store it in DATA.  */
gcry_error_t
_gcry_ac_data_new (gcry_ac_data_t *data)
{
  gcry_ac_data_t data_new;
  gcry_error_t err;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  data_new = gcry_malloc (sizeof (*data_new));
  if (! data_new)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  data_new->data = NULL;
  data_new->data_n = 0;
  *data = data_new;
  err = 0;

 out:

  return err;
}

/* Destroys all the entries in DATA, but not DATA itself.  */
static void
ac_data_values_destroy (gcry_ac_data_t data)
{
  unsigned int i;
  
  for (i = 0; i < data->data_n; i++)
    if (data->data[i].flags & GCRY_AC_FLAG_DEALLOC)
      {
	gcry_mpi_release (data->data[i].mpi);
	gcry_free (data->data[i].name);
      }
}

/* Destroys the data set DATA.  */
void
_gcry_ac_data_destroy (gcry_ac_data_t data)
{
  if (data)
    {
      ac_data_values_destroy (data);
      gcry_free (data->data);
      gcry_free (data);
    }
}

/* This function creates a copy of the array of named MPIs DATA_MPIS,
   which is of length DATA_MPIS_N; the copy is stored in
   DATA_MPIS_CP.  */
static gcry_error_t
ac_data_mpi_copy (gcry_ac_mpi_t *data_mpis, unsigned int data_mpis_n,
		  gcry_ac_mpi_t **data_mpis_cp)
{
  gcry_ac_mpi_t *data_mpis_new;
  gcry_error_t err;
  unsigned int i;
  gcry_mpi_t mpi;
  char *label;

  data_mpis_new = gcry_malloc (sizeof (*data_mpis_new) * data_mpis_n);
  if (! data_mpis_new)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }
  memset (data_mpis_new, 0, sizeof (*data_mpis_new) * data_mpis_n);

  err = 0;
  for (i = 0; i < data_mpis_n; i++)
    {
      /* Copy values.  */

      label = gcry_strdup (data_mpis[i].name);
      mpi = gcry_mpi_copy (data_mpis[i].mpi);
      if (! (label && mpi))
	{
	  err = gcry_error_from_errno (errno);
	  gcry_mpi_release (mpi);
	  gcry_free (label);
	  break;
	}

      data_mpis_new[i].flags = GCRY_AC_FLAG_DEALLOC;
      data_mpis_new[i].name = label;
      data_mpis_new[i].mpi = mpi;
    }
  if (err)
    goto out;

  *data_mpis_cp = data_mpis_new;
  err = 0;

 out:

  if (err)
    if (data_mpis_new)
      {
	for (i = 0; i < data_mpis_n; i++)
	  {
	    gcry_mpi_release (data_mpis_new[i].mpi);
	    gcry_free (data_mpis_new[i].name);
	  }
	gcry_free (data_mpis_new);
      }

  return err;
}

/* Create a copy of the data set DATA and store it in DATA_CP.  */
gcry_error_t
_gcry_ac_data_copy (gcry_ac_data_t *data_cp, gcry_ac_data_t data)
{
  gcry_ac_mpi_t *data_mpis = NULL;
  gcry_ac_data_t data_new;
  gcry_error_t err;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  /* Allocate data set.  */
  data_new = gcry_malloc (sizeof (*data_new));
  if (! data_new)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  err = ac_data_mpi_copy (data->data, data->data_n, &data_mpis);
  if (err)
    goto out;
  
  data_new->data_n = data->data_n;
  data_new->data = data_mpis;
  *data_cp = data_new;

 out:

  if (err)
    gcry_free (data_new);

  return err;
}

/* Returns the number of named MPI values inside of the data set
   DATA.  */
unsigned int
_gcry_ac_data_length (gcry_ac_data_t data)
{
  return data->data_n;
}


/* Add the value MPI to DATA with the label NAME.  If FLAGS contains
   GCRY_AC_FLAG_COPY, the data set will contain copies of NAME
   and MPI.  If FLAGS contains GCRY_AC_FLAG_DEALLOC or
   GCRY_AC_FLAG_COPY, the values contained in the data set will
   be deallocated when they are to be removed from the data set.  */
gcry_error_t
_gcry_ac_data_set (gcry_ac_data_t data, unsigned int flags,
		   const char *name, gcry_mpi_t mpi)
{
  gcry_error_t err;
  gcry_mpi_t mpi_cp;
  char *name_cp;
  unsigned int i;

  name_cp = NULL;
  mpi_cp = NULL;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  if (flags & ~(GCRY_AC_FLAG_DEALLOC | GCRY_AC_FLAG_COPY))
    {
      err = gcry_error (GPG_ERR_INV_ARG);
      goto out;
    }

  if (flags & GCRY_AC_FLAG_COPY)
    {
      /* Create copies.  */

      flags |= GCRY_AC_FLAG_DEALLOC;
      name_cp = gcry_strdup (name);
      mpi_cp = gcry_mpi_copy (mpi);
      if (! (name_cp && mpi_cp))
	{
	  err = gcry_error_from_errno (errno);
	  goto out;
	}
    }

  /* Search for existing entry.  */
  for (i = 0; i < data->data_n; i++)
    if (! strcmp (name, data->data[i].name))
      break;
  if (i < data->data_n)
    {
      /* An entry for NAME does already exist.  */
      if (data->data[i].flags & GCRY_AC_FLAG_DEALLOC)
	{
	  gcry_mpi_release (data->data[i].mpi);
	  gcry_free (data->data[i].name);
	}
    }
  else
    {
      /* Create a new entry.  */

      gcry_ac_mpi_t *ac_mpis;

      ac_mpis = gcry_realloc (data->data,
			      sizeof (*data->data) * (data->data_n + 1));
      if (! ac_mpis)
	{
	  err = gcry_error_from_errno (errno);
	  goto out;
	}

      if (data->data != ac_mpis)
	data->data = ac_mpis;
      data->data_n++;
    }

  data->data[i].name = name_cp ? name_cp : ((char *) name);
  data->data[i].mpi = mpi_cp ? mpi_cp : mpi;
  data->data[i].flags = flags;
  err = 0;

 out:

  if (err)
    {
      gcry_mpi_release (mpi_cp);
      gcry_free (name_cp);
    }

  return err;
}

/* Stores the value labelled with NAME found in the data set DATA in
   MPI.  The returned MPI value will be released in case
   gcry_ac_data_set is used to associate the label NAME with a
   different MPI value.  */
gcry_error_t
_gcry_ac_data_get_name (gcry_ac_data_t data, unsigned int flags,
			const char *name, gcry_mpi_t *mpi)
{
  gcry_mpi_t mpi_return;
  gcry_error_t err;
  unsigned int i;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  if (flags & ~(GCRY_AC_FLAG_COPY))
    {
      err = gcry_error (GPG_ERR_INV_ARG);
      goto out;
    }

  for (i = 0; i < data->data_n; i++)
    if (! strcmp (name, data->data[i].name))
      break;
  if (i == data->data_n)
    {
      err = gcry_error (GPG_ERR_NOT_FOUND);
      goto out;
    }

  if (flags & GCRY_AC_FLAG_COPY)
    {
      mpi_return = gcry_mpi_copy (data->data[i].mpi);
      if (! mpi_return)
	{
	  err = gcry_error_from_errno (errno); /* FIXME? */
	  goto out;
	}
    }
  else
    mpi_return = data->data[i].mpi;

  *mpi = mpi_return;
  err = 0;

 out:

  return err;
}

/* Stores in NAME and MPI the named MPI value contained in the data
   set DATA with the index IDX.  NAME or MPI may be NULL.  The
   returned MPI value will be released in case gcry_ac_data_set is
   used to associate the label NAME with a different MPI value.  */
gcry_error_t
_gcry_ac_data_get_index (gcry_ac_data_t data, unsigned int flags,
			 unsigned int idx,
			 const char **name, gcry_mpi_t *mpi)
{
  gcry_error_t err;
  gcry_mpi_t mpi_cp;
  char *name_cp;

  name_cp = NULL;
  mpi_cp = NULL;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  if (flags & ~(GCRY_AC_FLAG_COPY))
    {
      err = gcry_error (GPG_ERR_INV_ARG);
      goto out;
    }

  if (idx >= data->data_n)
    {
      err = gcry_error (GPG_ERR_INV_ARG);
      goto out;
    }

  if (flags & GCRY_AC_FLAG_COPY)
    {
      /* Return copies to the user.  */
      if (name)
	{
	  name_cp = gcry_strdup (data->data[idx].name);
	  if (! name_cp)
	    {
	      err = gcry_error_from_errno (errno);
	      goto out;
	    }
	}
      if (mpi)
	{
	  mpi_cp = gcry_mpi_copy (data->data[idx].mpi);
	  if (! mpi_cp)
	    {
	      err = gcry_error_from_errno (errno);
	      goto out;
	    }
	}
    }

  if (name)
    *name = name_cp ? name_cp : data->data[idx].name;
  if (mpi)
    *mpi = mpi_cp ? mpi_cp : data->data[idx].mpi;
  err = 0;

 out:

  if (err)
    {
      gcry_mpi_release (mpi_cp);
      gcry_free (name_cp);
    }

  return err;
}

/* Convert the data set DATA into a new S-Expression, which is to be
   stored in SEXP, according to the identifiers contained in
   IDENTIFIERS.  */
gcry_error_t
_gcry_ac_data_to_sexp (gcry_ac_data_t data, gcry_sexp_t *sexp,
		       const char **identifiers)
{
  gcry_sexp_t sexp_new;
  gcry_error_t err;
  char *sexp_buffer;
  size_t sexp_buffer_n;
  size_t identifiers_n;
  const char *label;
  gcry_mpi_t mpi;
  void **arg_list;
  size_t data_n;
  unsigned int i;

  sexp_buffer_n = 1;
  sexp_buffer = NULL;
  arg_list = NULL;
  err = 0;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  /* Calculate size of S-expression representation.  */

  i = 0;
  if (identifiers)
    while (identifiers[i])
      {
	/* For each identifier, we add "(<IDENTIFIER>)".  */
	sexp_buffer_n += 1 + strlen (identifiers[i]) + 1;
	i++;
      }
  identifiers_n = i;
  
  if (! identifiers_n)
    /* If there are NO identifiers, we still add surrounding braces so
       that we have a list of named MPI value lists.  Otherwise it
       wouldn't be too much fun to process these lists.  */
    sexp_buffer_n += 2;
  
  data_n = _gcry_ac_data_length (data);
  for (i = 0; i < data_n; i++)
    {
      err = gcry_ac_data_get_index (data, 0, i, &label, NULL);
      if (err)
	break;
      /* For each MPI we add "(<LABEL> %m)".  */
      sexp_buffer_n += 1 + strlen (label) + 4;
    }
  if (err)
    goto out;

  /* Allocate buffer.  */

  sexp_buffer = gcry_malloc (sexp_buffer_n);
  if (! sexp_buffer)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  /* Fill buffer.  */

  *sexp_buffer = 0;
  sexp_buffer_n = 0;

  /* Add identifiers: (<IDENTIFIER0>(<IDENTIFIER1>...)).  */
  if (identifiers_n)
    {
      /* Add nested identifier lists as usual.  */
      for (i = 0; i < identifiers_n; i++)
	sexp_buffer_n += sprintf (sexp_buffer + sexp_buffer_n, "(%s",
				  identifiers[i]);
    }
  else
    {
      /* Add special list.  */
      sexp_buffer_n += sprintf (sexp_buffer + sexp_buffer_n, "(");
    }

  /* Add MPI list.  */
  arg_list = gcry_malloc (sizeof (*arg_list) * (data_n + 1));
  if (! arg_list)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }
  for (i = 0; i < data_n; i++)
    {
      err = gcry_ac_data_get_index (data, 0, i, &label, &mpi);
      if (err)
	break;
      sexp_buffer_n += sprintf (sexp_buffer + sexp_buffer_n,
				"(%s %%m)", label);
      arg_list[i] = &data->data[i].mpi;
    }
  if (err)
    goto out;

  if (identifiers_n)
    {
      /* Add closing braces for identifier lists as usual.  */
      for (i = 0; i < identifiers_n; i++)
	sexp_buffer_n += sprintf (sexp_buffer + sexp_buffer_n, ")");
    }
  else
    {
      /* Add closing braces for special list.  */
      sexp_buffer_n += sprintf (sexp_buffer + sexp_buffer_n, ")");
    }

  /* Construct.  */
  err = gcry_sexp_build_array (&sexp_new, NULL, sexp_buffer, arg_list);
  if (err)
    goto out;

  *sexp = sexp_new;

 out:

  gcry_free (sexp_buffer);
  gcry_free (arg_list);

  return err;
}

/* Create a new data set, which is to be stored in DATA_SET, from the
   S-Expression SEXP, according to the identifiers contained in
   IDENTIFIERS.  */
gcry_error_t
_gcry_ac_data_from_sexp (gcry_ac_data_t *data_set, gcry_sexp_t sexp,
			 const char **identifiers)
{
  gcry_ac_data_t data_set_new;
  gcry_error_t err;
  gcry_sexp_t sexp_cur;
  gcry_sexp_t sexp_tmp;
  gcry_mpi_t mpi;
  char *string;
  const char *data;
  size_t data_n;
  size_t sexp_n;
  unsigned int i;
  int skip_name;

  data_set_new = NULL;
  sexp_cur = sexp;
  sexp_tmp = NULL;
  string = NULL;
  mpi = NULL;
  err = 0;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  /* Process S-expression/identifiers.  */

  if (identifiers)
    {
      for (i = 0; identifiers[i]; i++)
	{
	  /* Next identifier.  Extract first data item from
	     SEXP_CUR.  */
	  data = gcry_sexp_nth_data (sexp_cur, 0, &data_n);

	  if (! ((data_n == strlen (identifiers[i]))
		 && (! strncmp (data, identifiers[i], data_n))))
	    {
	      /* Identifier mismatch -> error.  */
	      err = gcry_error (GPG_ERR_INV_SEXP);
	      break;
	    }

	  /* Identifier matches.  Now we have to distinguish two
	     cases:
	     
	     (i)  we are at the last identifier:
	     leave loop

	     (ii) we are not at the last identifier:
	     extract next element, which is supposed to be a
	     sublist.  */

	  if (! identifiers[i + 1])
	    /* Last identifier.  */
	    break;
	  else
	    {
	      /* Not the last identifier, extract next sublist.  */

	      sexp_tmp = gcry_sexp_nth (sexp_cur, 1);
	      if (! sexp_tmp)
		{
		  /* Missing sublist.  */
		  err = gcry_error (GPG_ERR_INV_SEXP);
		  break;
		}

	      /* Release old SEXP_CUR, in case it is not equal to the
		 original SEXP.  */
	      if (sexp_cur != sexp)
		gcry_sexp_release (sexp_cur);

	      /* Make SEXP_CUR point to the new current sublist.  */
	      sexp_cur = sexp_tmp;
              sexp_tmp = NULL;
	    }
	}
      if (err)
	goto out;

      if (i)
        {
          /* We have at least one identifier in the list, this means
             the the list of named MPI values is prefixed, this means
             that we need to skip the first item (the list name), when
             processing the MPI values.  */
          skip_name = 1;
        }
      else
        {
          /* Since there is no identifiers list, the list of named MPI
             values is not prefixed with a list name, therefore the
             offset to use is zero.  */
          skip_name = 0;
        }
    }
  else
    /* Since there is no identifiers list, the list of named MPI
       values is not prefixed with a list name, therefore the offset
       to use is zero.  */
    skip_name = 0;

  /* Create data set from S-expression data.  */
  
  err = gcry_ac_data_new (&data_set_new);
  if (err)
    goto out;

  /* Figure out amount of named MPIs in SEXP_CUR.  */
  if (sexp_cur)
    sexp_n = gcry_sexp_length (sexp_cur) - skip_name;
  else
    sexp_n = 0;

  /* Extracte the named MPIs sequentially.  */
  for (i = 0; i < sexp_n; i++)
    {
      /* Store next S-Expression pair, which is supposed to consist of
	 a name and an MPI value, in SEXP_TMP.  */

      sexp_tmp = gcry_sexp_nth (sexp_cur, i + skip_name);
      if (! sexp_tmp)
	{
	  err = gcry_error (GPG_ERR_INV_SEXP);
	  break;
	}

      /* Extract name from current S-Expression pair.  */
      data = gcry_sexp_nth_data (sexp_tmp, 0, &data_n);
      string = gcry_malloc (data_n + 1);
      if (! string)
	{
	  err = gcry_error_from_errno (errno);
	  break;
	}
      memcpy (string, data, data_n);
      string[data_n] = 0;

      /* Extract MPI value.  */
      mpi = gcry_sexp_nth_mpi (sexp_tmp, 1, 0);
      if (! mpi)
	{
	  err = gcry_error (GPG_ERR_INV_SEXP); /* FIXME? */
	  break;
	}

      /* Store named MPI in data_set_new.  */
      err = gcry_ac_data_set (data_set_new, GCRY_AC_FLAG_DEALLOC, string, mpi);
      if (err)
	break;

/*       gcry_free (string); */
      string = NULL;
/*       gcry_mpi_release (mpi); */
      mpi = NULL;

      gcry_sexp_release (sexp_tmp);
      sexp_tmp = NULL;
    }
  if (err)
    goto out;

  *data_set = data_set_new;

 out:

  if (sexp_cur != sexp)
    gcry_sexp_release (sexp_cur);
  gcry_sexp_release (sexp_tmp);
  gcry_mpi_release (mpi);
  gcry_free (string);
  
  if (err)
    gcry_ac_data_destroy (data_set_new);

  return err;
}


static void
_gcry_ac_data_dump (const char *prefix, gcry_ac_data_t data)
{
  unsigned char *mpi_buffer;
  size_t mpi_buffer_n;
  unsigned int data_n;
  gcry_error_t err;
  const char *name;
  gcry_mpi_t mpi;
  unsigned int i;

  if (! data)
    return;

  if (fips_mode ())
    return;

  mpi_buffer = NULL;

  data_n = _gcry_ac_data_length (data);
  for (i = 0; i < data_n; i++)
    {
      err = gcry_ac_data_get_index (data, 0, i, &name, &mpi);
      if (err)
	{
	  log_error ("failed to dump data set");
	  break;
	}

      err = gcry_mpi_aprint (GCRYMPI_FMT_HEX, &mpi_buffer, &mpi_buffer_n, mpi);
      if (err)
	{
	  log_error ("failed to dump data set");
	  break;
	}

      log_printf ("%s%s%s: %s\n",
		  prefix ? prefix : "",
		  prefix ? ": " : ""
		  , name, mpi_buffer);

      gcry_free (mpi_buffer);
      mpi_buffer = NULL;
    }

  gcry_free (mpi_buffer);
}

/* Dump the named MPI values contained in the data set DATA to
   Libgcrypt's logging stream.  */
void
gcry_ac_data_dump (const char *prefix, gcry_ac_data_t data)
{
  _gcry_ac_data_dump (prefix, data);
}

/* Destroys any values contained in the data set DATA.  */
void
_gcry_ac_data_clear (gcry_ac_data_t data)
{
  ac_data_values_destroy (data);
  gcry_free (data->data);
  data->data = NULL;
  data->data_n = 0;
}



/*
 * Implementation of `ac io' objects.
 */

/* Initialize AC_IO according to MODE, TYPE and the variable list of
   arguments AP.  The list of variable arguments to specify depends on
   the given TYPE.  */
void
_gcry_ac_io_init_va (gcry_ac_io_t *ac_io,
		     gcry_ac_io_mode_t mode, gcry_ac_io_type_t type, va_list ap)
{
  memset (ac_io, 0, sizeof (*ac_io));

  if (fips_mode ())
    return;

  gcry_assert ((mode == GCRY_AC_IO_READABLE) || (mode == GCRY_AC_IO_WRITABLE));
  gcry_assert ((type == GCRY_AC_IO_STRING) || (type == GCRY_AC_IO_STRING));

  ac_io->mode = mode;
  ac_io->type = type;

  switch (mode)
    {
    case GCRY_AC_IO_READABLE:
      switch (type)
	{
	case GCRY_AC_IO_STRING:
	  ac_io->io.readable.string.data = va_arg (ap, unsigned char *);
	  ac_io->io.readable.string.data_n = va_arg (ap, size_t);
	  break;

	case GCRY_AC_IO_CALLBACK:
	  ac_io->io.readable.callback.cb = va_arg (ap, gcry_ac_data_read_cb_t);
	  ac_io->io.readable.callback.opaque = va_arg (ap, void *);
	  break;
	}
      break;
    case GCRY_AC_IO_WRITABLE:
      switch (type)
	{
	case GCRY_AC_IO_STRING:
	  ac_io->io.writable.string.data = va_arg (ap, unsigned char **);
	  ac_io->io.writable.string.data_n = va_arg (ap, size_t *);
	  break;

	case GCRY_AC_IO_CALLBACK:
	  ac_io->io.writable.callback.cb = va_arg (ap, gcry_ac_data_write_cb_t);
	  ac_io->io.writable.callback.opaque = va_arg (ap, void *);
	  break;
	}
      break;
    }
}

/* Initialize AC_IO according to MODE, TYPE and the variable list of
   arguments.  The list of variable arguments to specify depends on
   the given TYPE. */
void
_gcry_ac_io_init (gcry_ac_io_t *ac_io,
		  gcry_ac_io_mode_t mode, gcry_ac_io_type_t type, ...)
{
  va_list ap;

  va_start (ap, type);
  _gcry_ac_io_init_va (ac_io, mode, type, ap);
  va_end (ap);
}


/* Write to the IO object AC_IO BUFFER_N bytes from BUFFER.  Return
   zero on success or error code.  */
static gcry_error_t
_gcry_ac_io_write (gcry_ac_io_t *ac_io, unsigned char *buffer, size_t buffer_n)
{
  gcry_error_t err;

  gcry_assert (ac_io->mode == GCRY_AC_IO_WRITABLE);
  err = 0;

  switch (ac_io->type)
    {
    case GCRY_AC_IO_STRING:
      {
	unsigned char *p;

	if (*ac_io->io.writable.string.data)
	  {
	    p = gcry_realloc (*ac_io->io.writable.string.data,
			      *ac_io->io.writable.string.data_n + buffer_n);
	    if (! p)
	      err = gcry_error_from_errno (errno);
	    else
	      {
		if (*ac_io->io.writable.string.data != p)
		  *ac_io->io.writable.string.data = p;
		memcpy (p + *ac_io->io.writable.string.data_n, buffer, buffer_n);
		*ac_io->io.writable.string.data_n += buffer_n;
	      }
	  }
	else
	  {
	    if (gcry_is_secure (buffer))
	      p = gcry_malloc_secure (buffer_n);
	    else
	      p = gcry_malloc (buffer_n);
	    if (! p)
	      err = gcry_error_from_errno (errno);
	    else
	      {
		memcpy (p, buffer, buffer_n);
		*ac_io->io.writable.string.data = p;
		*ac_io->io.writable.string.data_n = buffer_n;
	      }
	  }
      }
      break;

    case GCRY_AC_IO_CALLBACK:
      err = (*ac_io->io.writable.callback.cb) (ac_io->io.writable.callback.opaque,
					       buffer, buffer_n);
      break;
    }

  return err;
}

/* Read *BUFFER_N bytes from the IO object AC_IO into BUFFER; NREAD
   bytes have already been read from the object; on success, store the
   amount of bytes read in *BUFFER_N; zero bytes read means EOF.
   Return zero on success or error code.  */
static gcry_error_t
_gcry_ac_io_read (gcry_ac_io_t *ac_io,
		  unsigned int nread, unsigned char *buffer, size_t *buffer_n)
{
  gcry_error_t err;
  
  gcry_assert (ac_io->mode == GCRY_AC_IO_READABLE);
  err = 0;

  switch (ac_io->type)
    {
    case GCRY_AC_IO_STRING:
      {
	size_t bytes_available;
	size_t bytes_to_read;
	size_t bytes_wanted;

	bytes_available = ac_io->io.readable.string.data_n - nread;
	bytes_wanted = *buffer_n;

	if (bytes_wanted > bytes_available)
	  bytes_to_read = bytes_available;
	else
	  bytes_to_read = bytes_wanted;

	memcpy (buffer, ac_io->io.readable.string.data + nread, bytes_to_read);
	*buffer_n = bytes_to_read;
	err = 0;
	break;
      }

    case GCRY_AC_IO_CALLBACK:
      err = (*ac_io->io.readable.callback.cb)
	(ac_io->io.readable.callback.opaque, buffer, buffer_n);
      break;
    }

  return err;
}

/* Read all data available from the IO object AC_IO into newly
   allocated memory, storing an appropriate pointer in *BUFFER and the
   amount of bytes read in *BUFFER_N.  Return zero on success or error
   code.  */
static gcry_error_t
_gcry_ac_io_read_all (gcry_ac_io_t *ac_io, unsigned char **buffer, size_t *buffer_n)
{
  unsigned char *buffer_new;
  size_t buffer_new_n;
  unsigned char buf[BUFSIZ];
  size_t buf_n;
  unsigned char *p;
  gcry_error_t err;

  buffer_new = NULL;
  buffer_new_n = 0;

  while (1)
    {
      buf_n = sizeof (buf);
      err = _gcry_ac_io_read (ac_io, buffer_new_n, buf, &buf_n);
      if (err)
	break;

      if (buf_n)
	{
	  p = gcry_realloc (buffer_new, buffer_new_n + buf_n);
	  if (! p)
	    {
	      err = gcry_error_from_errno (errno);
	      break;
	    }
	  
	  if (buffer_new != p)
	    buffer_new = p;

	  memcpy (buffer_new + buffer_new_n, buf, buf_n);
	  buffer_new_n += buf_n;
	}
      else
	break;
    }
  if (err)
    goto out;

  *buffer_n = buffer_new_n;
  *buffer = buffer_new;

 out:

  if (err)
    gcry_free (buffer_new);

  return err;
}

/* Read data chunks from the IO object AC_IO until EOF, feeding them
   to the callback function CB.  Return zero on success or error
   code.  */
static gcry_error_t
_gcry_ac_io_process (gcry_ac_io_t *ac_io,
		     gcry_ac_data_write_cb_t cb, void *opaque)
{
  unsigned char buffer[BUFSIZ];
  unsigned int nread;
  size_t buffer_n;
  gcry_error_t err;

  nread = 0;

  while (1)
    {
      buffer_n = sizeof (buffer);
      err = _gcry_ac_io_read (ac_io, nread, buffer, &buffer_n);
      if (err)
	break;
      if (buffer_n)
	{
	  err = (*cb) (opaque, buffer, buffer_n);
	  if (err)
	    break;
	  nread += buffer_n;
	}
      else
	break;
    }

  return err;
}



/* 
 * Functions for converting data between the native ac and the
 * S-expression structure used by the pk interface.
 */

/* Extract the S-Expression DATA_SEXP into DATA under the control of
   TYPE and NAME.  This function assumes that S-Expressions are of the
   following structure:

   (IDENTIFIER [...]
   (ALGORITHM <list of named MPI values>)) */
static gcry_error_t
ac_data_extract (const char *identifier, const char *algorithm,
		 gcry_sexp_t sexp, gcry_ac_data_t *data)
{
  gcry_error_t err;
  gcry_sexp_t value_sexp;
  gcry_sexp_t data_sexp;
  size_t data_sexp_n;
  gcry_mpi_t value_mpi;
  char *value_name;
  const char *data_raw;
  size_t data_raw_n;
  gcry_ac_data_t data_new;
  unsigned int i;

  value_sexp = NULL;
  data_sexp = NULL;
  value_name = NULL;
  value_mpi = NULL;
  data_new = NULL;

  /* Verify that the S-expression contains the correct identifier.  */
  data_raw = gcry_sexp_nth_data (sexp, 0, &data_raw_n);
  if ((! data_raw) || strncmp (identifier, data_raw, data_raw_n))
    {
      err = gcry_error (GPG_ERR_INV_SEXP);
      goto out;
    }

  /* Extract inner S-expression.  */
  data_sexp = gcry_sexp_find_token (sexp, algorithm, 0);
  if (! data_sexp)
    {
      err = gcry_error (GPG_ERR_INV_SEXP);
      goto out;
    }

  /* Count data elements.  */
  data_sexp_n = gcry_sexp_length (data_sexp);
  data_sexp_n--;

  /* Allocate new data set.  */
  err = _gcry_ac_data_new (&data_new);
  if (err)
    goto out;

  /* Iterate through list of data elements and add them to the data
     set.  */
  for (i = 0; i < data_sexp_n; i++)
    {
      /* Get the S-expression of the named MPI, that contains the name
	 and the MPI value.  */
      value_sexp = gcry_sexp_nth (data_sexp, i + 1);
      if (! value_sexp)
	{
	  err = gcry_error (GPG_ERR_INV_SEXP);
	  break;
	}

      /* Extract the name.  */
      data_raw = gcry_sexp_nth_data (value_sexp, 0, &data_raw_n);
      if (! data_raw)
	{
	  err = gcry_error (GPG_ERR_INV_SEXP);
	  break;
	}

      /* Extract the MPI value.  */
      value_mpi = gcry_sexp_nth_mpi (value_sexp, 1, GCRYMPI_FMT_USG);
      if (! value_mpi)
	{
	  err = gcry_error (GPG_ERR_INTERNAL); /* FIXME? */
	  break;
	}

      /* Duplicate the name.  */
      value_name = gcry_malloc (data_raw_n + 1);
      if (! value_name)
	{
	  err = gcry_error_from_errno (errno);
	  break;
	}
      strncpy (value_name, data_raw, data_raw_n);
      value_name[data_raw_n] = 0;

      err = _gcry_ac_data_set (data_new, GCRY_AC_FLAG_DEALLOC, value_name, value_mpi);
      if (err)
	break;

      gcry_sexp_release (value_sexp);
      value_sexp = NULL;
      value_name = NULL;
      value_mpi = NULL;
    }
  if (err)
    goto out;

  /* Copy out.  */
  *data = data_new;

 out:

  /* Deallocate resources.  */
  if (err)
    {
      _gcry_ac_data_destroy (data_new);
      gcry_mpi_release (value_mpi);
      gcry_free (value_name);
      gcry_sexp_release (value_sexp);
    }
  gcry_sexp_release (data_sexp);

  return err;
}

/* Construct an S-expression from the DATA and store it in
   DATA_SEXP. The S-expression will be of the following structure:

   (IDENTIFIER [(flags [...])]
   (ALGORITHM <list of named MPI values>))  */
static gcry_error_t
ac_data_construct (const char *identifier, int include_flags,
		   unsigned int flags, const char *algorithm,
		   gcry_ac_data_t data, gcry_sexp_t *sexp)
{
  unsigned int data_length;
  gcry_sexp_t sexp_new;
  gcry_error_t err;
  size_t sexp_format_n;
  char *sexp_format;
  void **arg_list;
  unsigned int i;

  arg_list = NULL;
  sexp_new = NULL;
  sexp_format = NULL;

  /* We build a list of arguments to pass to
     gcry_sexp_build_array().  */
  data_length = _gcry_ac_data_length (data);
  arg_list = gcry_malloc (sizeof (*arg_list) * (data_length * 2));
  if (! arg_list)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  /* Fill list with MPIs.  */
  for (i = 0; i < data_length; i++)
    {
      char **nameaddr  = &data->data[i].name;

      arg_list[(i * 2) + 0] = nameaddr;
      arg_list[(i * 2) + 1] = &data->data[i].mpi;
    }

  /* Calculate size of format string.  */
  sexp_format_n = (3
		   + (include_flags ? 7 : 0)
		   + (algorithm ? (2 + strlen (algorithm)) : 0)
		   + strlen (identifier));

  for (i = 0; i < data_length; i++)
    /* Per-element sizes.  */
    sexp_format_n += 6;

  if (include_flags)
    /* Add flags.  */
    for (i = 0; i < DIM (ac_flags); i++)
      if (flags & ac_flags[i].number)
	sexp_format_n += strlen (ac_flags[i].string) + 1;

  /* Done.  */
  sexp_format = gcry_malloc (sexp_format_n);
  if (! sexp_format)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  /* Construct the format string.  */

  *sexp_format = 0;
  strcat (sexp_format, "(");
  strcat (sexp_format, identifier);
  if (include_flags)
    {
      strcat (sexp_format, "(flags");
      for (i = 0; i < DIM (ac_flags); i++)
	if (flags & ac_flags[i].number)
	  {
	    strcat (sexp_format, " ");
	    strcat (sexp_format, ac_flags[i].string);
	  }
      strcat (sexp_format, ")");
    }
  if (algorithm)
    {
      strcat (sexp_format, "(");
      strcat (sexp_format, algorithm);
    }
  for (i = 0; i < data_length; i++)
    strcat (sexp_format, "(%s%m)");
  if (algorithm)
    strcat (sexp_format, ")");
  strcat (sexp_format, ")");

  /* Create final S-expression.  */
  err = gcry_sexp_build_array (&sexp_new, NULL, sexp_format, arg_list);
  if (err)
    goto out;

  *sexp = sexp_new;

 out:

  /* Deallocate resources.  */
  gcry_free (sexp_format);
  gcry_free (arg_list);
  if (err)
    gcry_sexp_release (sexp_new);

  return err;
}



/*
 * Handle management.
 */

/* Creates a new handle for the algorithm ALGORITHM and stores it in
   HANDLE.  FLAGS is not used yet.  */
gcry_error_t
_gcry_ac_open (gcry_ac_handle_t *handle,
	       gcry_ac_id_t algorithm, unsigned int flags)
{
  gcry_ac_handle_t handle_new;
  const char *algorithm_name;
  gcry_module_t module;
  gcry_error_t err;

  *handle = NULL;
  module = NULL;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  /* Get name.  */
  algorithm_name = _gcry_pk_aliased_algo_name (algorithm);
  if (! algorithm_name)
    {
      err = gcry_error (GPG_ERR_PUBKEY_ALGO);
      goto out;
    }

  /* Acquire reference to the pubkey module.  */
  err = _gcry_pk_module_lookup (algorithm, &module);
  if (err)
    goto out;
  
  /* Allocate.  */
  handle_new = gcry_malloc (sizeof (*handle_new));
  if (! handle_new)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  /* Done.  */
  handle_new->algorithm = algorithm;
  handle_new->algorithm_name = algorithm_name;
  handle_new->flags = flags;
  handle_new->module = module;
  *handle = handle_new;

 out:
  
  /* Deallocate resources.  */
  if (err)
    _gcry_pk_module_release (module);

  return err;
}


/* Destroys the handle HANDLE.  */
void
_gcry_ac_close (gcry_ac_handle_t handle)
{
  /* Release reference to pubkey module.  */
  if (handle)
    {
      _gcry_pk_module_release (handle->module);
      gcry_free (handle);
    }
}



/* 
 * Key management.
 */

/* Initialize a key from a given data set.  */
/* FIXME/Damn: the argument HANDLE is not only unnecessary, it is
   completely WRONG here.  */
gcry_error_t
_gcry_ac_key_init (gcry_ac_key_t *key, gcry_ac_handle_t handle,
		   gcry_ac_key_type_t type, gcry_ac_data_t data)
{
  gcry_ac_data_t data_new;
  gcry_ac_key_t key_new;
  gcry_error_t err;

  (void)handle;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  /* Allocate.  */
  key_new = gcry_malloc (sizeof (*key_new));
  if (! key_new)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  /* Copy data set.  */
  err = _gcry_ac_data_copy (&data_new, data);
  if (err)
    goto out;

  /* Done.  */
  key_new->data = data_new;
  key_new->type = type;
  *key = key_new;

 out:

  if (err)
    /* Deallocate resources.  */
    gcry_free (key_new);

  return err;
}


/* Generates a new key pair via the handle HANDLE of NBITS bits and
   stores it in KEY_PAIR.  In case non-standard settings are wanted, a
   pointer to a structure of type gcry_ac_key_spec_<algorithm>_t,
   matching the selected algorithm, can be given as KEY_SPEC.
   MISC_DATA is not used yet.  */
gcry_error_t
_gcry_ac_key_pair_generate (gcry_ac_handle_t handle, unsigned int nbits,
			    void *key_spec,
			    gcry_ac_key_pair_t *key_pair,
			    gcry_mpi_t **misc_data)
{
  gcry_sexp_t genkey_sexp_request;
  gcry_sexp_t genkey_sexp_reply;
  gcry_ac_data_t key_data_secret;
  gcry_ac_data_t key_data_public;
  gcry_ac_key_pair_t key_pair_new;
  gcry_ac_key_t key_secret;
  gcry_ac_key_t key_public;
  gcry_sexp_t key_sexp;
  gcry_error_t err;
  char *genkey_format;
  size_t genkey_format_n;
  void **arg_list;
  size_t arg_list_n;
  unsigned int i;
  unsigned int j;

  (void)misc_data;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  key_data_secret = NULL;
  key_data_public = NULL;
  key_secret = NULL;
  key_public = NULL;
  genkey_format = NULL;
  arg_list = NULL;
  genkey_sexp_request = NULL;
  genkey_sexp_reply = NULL;
  key_sexp = NULL;

  /* Allocate key pair.  */
  key_pair_new = gcry_malloc (sizeof (struct gcry_ac_key_pair));
  if (! key_pair_new)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  /* Allocate keys.  */
  key_secret = gcry_malloc (sizeof (*key_secret));
  if (! key_secret)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }
  key_public = gcry_malloc (sizeof (*key_public));
  if (! key_public)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  /* Calculate size of the format string, that is used for creating
     the request S-expression.  */
  genkey_format_n = 22;

  /* Respect any relevant algorithm specific commands.  */
  if (key_spec)
    for (i = 0; i < DIM (ac_key_generate_specs); i++)
      if (handle->algorithm == ac_key_generate_specs[i].algorithm)
	genkey_format_n += 6;

  /* Create format string.  */
  genkey_format = gcry_malloc (genkey_format_n);
  if (! genkey_format)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  /* Fill format string.  */
  *genkey_format = 0;
  strcat (genkey_format, "(genkey(%s(nbits%d)");
  if (key_spec)
    for (i = 0; i < DIM (ac_key_generate_specs); i++)
      if (handle->algorithm == ac_key_generate_specs[i].algorithm)
	strcat (genkey_format, "(%s%m)");
  strcat (genkey_format, "))");

  /* Build list of argument pointers, the algorithm name and the nbits
     are always needed.  */
  arg_list_n = 2;

  /* Now the algorithm specific arguments.  */
  if (key_spec)
    for (i = 0; i < DIM (ac_key_generate_specs); i++)
      if (handle->algorithm == ac_key_generate_specs[i].algorithm)
	arg_list_n += 2;

  /* Allocate list.  */
  arg_list = gcry_malloc (sizeof (*arg_list) * arg_list_n);
  if (! arg_list)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  arg_list[0] = (void *) &handle->algorithm_name;
  arg_list[1] = (void *) &nbits;
  if (key_spec)
    for (j = 2, i = 0; i < DIM (ac_key_generate_specs); i++)
      if (handle->algorithm == ac_key_generate_specs[i].algorithm)
	{
	  /* Add name of this specification flag and the
	     according member of the spec strucuture.  */
	  arg_list[j++] = (void *)(&ac_key_generate_specs[i].name);
	  arg_list[j++] = (void *)
	    (((char *) key_spec)
	     + ac_key_generate_specs[i].offset);
	  /* FIXME: above seems to suck.  */
	}

  /* Construct final request S-expression.  */
  err = gcry_sexp_build_array (&genkey_sexp_request,
			       NULL, genkey_format, arg_list);
  if (err)
    goto out;

  /* Perform genkey operation.  */
  err = gcry_pk_genkey (&genkey_sexp_reply, genkey_sexp_request);
  if (err)
    goto out;

  key_sexp = gcry_sexp_find_token (genkey_sexp_reply, "private-key", 0);
  if (! key_sexp)
    {
      err = gcry_error (GPG_ERR_INTERNAL);
      goto out;
    }
  err = ac_data_extract ("private-key", handle->algorithm_name,
			 key_sexp, &key_data_secret);
  if (err)
    goto out;

  gcry_sexp_release (key_sexp);
  key_sexp = gcry_sexp_find_token (genkey_sexp_reply, "public-key", 0);
  if (! key_sexp)
    {
      err = gcry_error (GPG_ERR_INTERNAL);
      goto out;
    }
  err = ac_data_extract ("public-key", handle->algorithm_name,
			 key_sexp, &key_data_public);
  if (err)
    goto out;

  /* Done.  */

  key_secret->type = GCRY_AC_KEY_SECRET;
  key_secret->data = key_data_secret;
  key_public->type = GCRY_AC_KEY_PUBLIC;
  key_public->data = key_data_public;
  key_pair_new->secret = key_secret;
  key_pair_new->public = key_public;
  *key_pair = key_pair_new;

 out:

  /* Deallocate resources.  */
  
  gcry_free (genkey_format);
  gcry_free (arg_list);
  gcry_sexp_release (genkey_sexp_request);
  gcry_sexp_release (genkey_sexp_reply);
  gcry_sexp_release (key_sexp);
  if (err)
    {
      _gcry_ac_data_destroy (key_data_secret);
      _gcry_ac_data_destroy (key_data_public);
      gcry_free (key_secret);
      gcry_free (key_public);
      gcry_free (key_pair_new);
    }

  return err;
}

/* Returns the key of type WHICH out of the key pair KEY_PAIR.  */
gcry_ac_key_t
_gcry_ac_key_pair_extract (gcry_ac_key_pair_t key_pair, 
                           gcry_ac_key_type_t which)
{
  gcry_ac_key_t key;

  if (fips_mode ())
    return NULL;

  switch (which)
    {
    case GCRY_AC_KEY_SECRET:
      key = key_pair->secret;
      break;

    case GCRY_AC_KEY_PUBLIC:
      key = key_pair->public;
      break;

    default:
      key = NULL;
      break;
    }

  return key;
}

/* Destroys the key KEY.  */
void
_gcry_ac_key_destroy (gcry_ac_key_t key)
{
  unsigned int i;

  if (key)
    {
      if (key->data)
        {
          for (i = 0; i < key->data->data_n; i++)
            {
              if (key->data->data[i].mpi)
                gcry_mpi_release (key->data->data[i].mpi);
              if (key->data->data[i].name)
                gcry_free (key->data->data[i].name);
            }
          gcry_free (key->data->data);
          gcry_free (key->data);
        }
      gcry_free (key);
    }
}

/* Destroys the key pair KEY_PAIR.  */
void
_gcry_ac_key_pair_destroy (gcry_ac_key_pair_t key_pair)
{
  if (key_pair)
    {
      gcry_ac_key_destroy (key_pair->secret);
      gcry_ac_key_destroy (key_pair->public);
      gcry_free (key_pair);
    }
}

/* Returns the data set contained in the key KEY.  */
gcry_ac_data_t
_gcry_ac_key_data_get (gcry_ac_key_t key)
{
  if (fips_mode ())
    return NULL;
  return key->data;
}

/* Verifies that the key KEY is sane via HANDLE.  */
gcry_error_t
_gcry_ac_key_test (gcry_ac_handle_t handle, gcry_ac_key_t key)
{
  gcry_sexp_t key_sexp;
  gcry_error_t err;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  key_sexp = NULL;
  err = ac_data_construct (ac_key_identifiers[key->type], 0, 0,
			   handle->algorithm_name, key->data, &key_sexp);
  if (err)
    goto out;

  err = gcry_pk_testkey (key_sexp);

 out:

  gcry_sexp_release (key_sexp);

  return gcry_error (err);
}

/* Stores the number of bits of the key KEY in NBITS via HANDLE.  */
gcry_error_t
_gcry_ac_key_get_nbits (gcry_ac_handle_t handle,
			gcry_ac_key_t key, unsigned int *nbits)
{
  gcry_sexp_t key_sexp;
  gcry_error_t err;
  unsigned int n;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  key_sexp = NULL;

  err = ac_data_construct (ac_key_identifiers[key->type],
			   0, 0, handle->algorithm_name, key->data, &key_sexp);
  if (err)
    goto out;

  n = gcry_pk_get_nbits (key_sexp);
  if (! n)
    {
      err = gcry_error (GPG_ERR_PUBKEY_ALGO);
      goto out;
    }

  *nbits = n;

 out:

  gcry_sexp_release (key_sexp);

  return err;
}

/* Writes the 20 byte long key grip of the key KEY to KEY_GRIP via
   HANDLE.  */
gcry_error_t
_gcry_ac_key_get_grip (gcry_ac_handle_t handle,
		       gcry_ac_key_t key, unsigned char *key_grip)
{
  gcry_sexp_t key_sexp;
  gcry_error_t err;
  unsigned char *ret;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  key_sexp = NULL;
  err = ac_data_construct (ac_key_identifiers[key->type], 0, 0,
			   handle->algorithm_name, key->data, &key_sexp);
  if (err)
    goto out;

  ret = gcry_pk_get_keygrip (key_sexp, key_grip);
  if (! ret)
    {
      err = gcry_error (GPG_ERR_INV_OBJ);
      goto out;
    }

  err = 0;

 out:

  gcry_sexp_release (key_sexp);

  return err;
}




/* 
 * Functions performing cryptographic operations.
 */

/* Encrypts the plain text MPI value DATA_PLAIN with the key public
   KEY under the control of the flags FLAGS and stores the resulting
   data set into DATA_ENCRYPTED.  */
gcry_error_t
_gcry_ac_data_encrypt (gcry_ac_handle_t handle,
		       unsigned int flags,
		       gcry_ac_key_t key,
		       gcry_mpi_t data_plain,
		       gcry_ac_data_t *data_encrypted)
{
  gcry_ac_data_t data_encrypted_new;
  gcry_ac_data_t data_value;
  gcry_sexp_t sexp_request;
  gcry_sexp_t sexp_reply;
  gcry_sexp_t sexp_key;
  gcry_error_t err;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  data_encrypted_new = NULL;
  sexp_request = NULL;
  sexp_reply = NULL;
  data_value = NULL;
  sexp_key = NULL;

  if (key->type != GCRY_AC_KEY_PUBLIC)
    {
      err = gcry_error (GPG_ERR_WRONG_KEY_USAGE);
      goto out;
    }

  err = ac_data_construct (ac_key_identifiers[key->type], 0, 0,
			   handle->algorithm_name, key->data, &sexp_key);
  if (err)
    goto out;

  err = _gcry_ac_data_new (&data_value);
  if (err)
    goto out;

  err = _gcry_ac_data_set (data_value, 0, "value", data_plain);
  if (err)
    goto out;

  err = ac_data_construct ("data", 1, flags, handle->algorithm_name,
			   data_value, &sexp_request);
  if (err)
    goto out;

  /* FIXME: error vs. errcode? */

  err = gcry_pk_encrypt (&sexp_reply, sexp_request, sexp_key);
  if (err)
    goto out;

  /* Extract data.  */
  err = ac_data_extract ("enc-val", handle->algorithm_name,
			 sexp_reply, &data_encrypted_new);
  if (err)
    goto out;

  *data_encrypted = data_encrypted_new;

 out:

  /* Deallocate resources.  */

  gcry_sexp_release (sexp_request);
  gcry_sexp_release (sexp_reply);
  gcry_sexp_release (sexp_key);
  _gcry_ac_data_destroy (data_value);

  return err;
}

/* Decrypts the encrypted data contained in the data set
   DATA_ENCRYPTED with the secret key KEY under the control of the
   flags FLAGS and stores the resulting plain text MPI value in
   DATA_PLAIN.  */
gcry_error_t
_gcry_ac_data_decrypt (gcry_ac_handle_t handle,
		       unsigned int flags,
		       gcry_ac_key_t key,
		       gcry_mpi_t *data_plain,
		       gcry_ac_data_t data_encrypted)
{
  gcry_mpi_t data_decrypted;
  gcry_sexp_t sexp_request;
  gcry_sexp_t sexp_reply;
  gcry_sexp_t sexp_value;
  gcry_sexp_t sexp_key;
  gcry_error_t err;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  sexp_request = NULL;
  sexp_reply = NULL;
  sexp_value = NULL;
  sexp_key = NULL;

  if (key->type != GCRY_AC_KEY_SECRET)
    {
      err = gcry_error (GPG_ERR_WRONG_KEY_USAGE);
      goto out;
    }

  err = ac_data_construct (ac_key_identifiers[key->type], 0, 0,
			   handle->algorithm_name, key->data, &sexp_key);
  if (err)
    goto out;

  /* Create S-expression from data.  */
  err = ac_data_construct ("enc-val", 1, flags, handle->algorithm_name,
			   data_encrypted, &sexp_request);
  if (err)
    goto out;

  /* Decrypt.  */
  err = gcry_pk_decrypt (&sexp_reply, sexp_request, sexp_key);
  if (err)
    goto out;

  /* Extract plain text. */
  sexp_value = gcry_sexp_find_token (sexp_reply, "value", 0);
  if (! sexp_value)
    {
      /* FIXME?  */
      err = gcry_error (GPG_ERR_GENERAL);
      goto out;
    }

  data_decrypted = gcry_sexp_nth_mpi (sexp_value, 1, GCRYMPI_FMT_USG);
  if (! data_decrypted)
    {
      err = gcry_error (GPG_ERR_GENERAL);
      goto out;
    }

  *data_plain = data_decrypted;

 out:

  /* Deallocate resources.  */
  gcry_sexp_release (sexp_request);
  gcry_sexp_release (sexp_reply);
  gcry_sexp_release (sexp_value);
  gcry_sexp_release (sexp_key);

  return gcry_error (err);

}

/* Signs the data contained in DATA with the secret key KEY and stores
   the resulting signature data set in DATA_SIGNATURE.  */
gcry_error_t
_gcry_ac_data_sign (gcry_ac_handle_t handle,
		    gcry_ac_key_t key,
		    gcry_mpi_t data,
		    gcry_ac_data_t *data_signature)
{
  gcry_ac_data_t data_signed;
  gcry_ac_data_t data_value;
  gcry_sexp_t sexp_request;
  gcry_sexp_t sexp_reply;
  gcry_sexp_t sexp_key;
  gcry_error_t err;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  data_signed = NULL;
  data_value = NULL;
  sexp_request = NULL;
  sexp_reply = NULL;
  sexp_key = NULL;

  if (key->type != GCRY_AC_KEY_SECRET)
    {
      err = gcry_error (GPG_ERR_WRONG_KEY_USAGE);
      goto out;
    }

  err = ac_data_construct (ac_key_identifiers[key->type], 0, 0,
			   handle->algorithm_name, key->data, &sexp_key);
  if (err)
    goto out;

  err = _gcry_ac_data_new (&data_value);
  if (err)
    goto out;

  err = _gcry_ac_data_set (data_value, 0, "value", data);
  if (err)
    goto out;

  /* Create S-expression holding the data.  */
  err = ac_data_construct ("data", 1, 0, NULL, data_value, &sexp_request);
  if (err)
    goto out;

  /* Sign.  */
  err = gcry_pk_sign (&sexp_reply, sexp_request, sexp_key);
  if (err)
    goto out;

  /* Extract data.  */
  err = ac_data_extract ("sig-val", handle->algorithm_name,
			 sexp_reply, &data_signed);
  if (err)
    goto out;

  /* Done.  */
  *data_signature = data_signed;

 out:

  gcry_sexp_release (sexp_request);
  gcry_sexp_release (sexp_reply);
  gcry_sexp_release (sexp_key);
  _gcry_ac_data_destroy (data_value);

  return gcry_error (err);
}


/* Verifies that the signature contained in the data set
   DATA_SIGNATURE is indeed the result of signing the data contained
   in DATA with the secret key belonging to the public key KEY.  */
gcry_error_t
_gcry_ac_data_verify (gcry_ac_handle_t handle,
		      gcry_ac_key_t key,
		      gcry_mpi_t data,
		      gcry_ac_data_t data_signature)
{
  gcry_sexp_t sexp_signature;
  gcry_ac_data_t data_value;
  gcry_sexp_t sexp_data;
  gcry_sexp_t sexp_key;
  gcry_error_t err;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  sexp_signature = NULL;
  data_value = NULL;
  sexp_data = NULL;
  sexp_key = NULL;

  err = ac_data_construct ("public-key", 0, 0,
			   handle->algorithm_name, key->data, &sexp_key);
  if (err)
    goto out;

  if (key->type != GCRY_AC_KEY_PUBLIC)
    {
      err = gcry_error (GPG_ERR_WRONG_KEY_USAGE);
      goto out;
    }

  /* Construct S-expression holding the signature data.  */
  err = ac_data_construct ("sig-val", 1, 0, handle->algorithm_name,
			   data_signature, &sexp_signature);
  if (err)
    goto out;

  err = _gcry_ac_data_new (&data_value);
  if (err)
    goto out;

  err = _gcry_ac_data_set (data_value, 0, "value", data);
  if (err)
    goto out;

  /* Construct S-expression holding the data.  */
  err = ac_data_construct ("data", 1, 0, NULL, data_value, &sexp_data);
  if (err)
    goto out;

  /* Verify signature.  */
  err = gcry_pk_verify (sexp_signature, sexp_data, sexp_key);

 out:

  gcry_sexp_release (sexp_signature);
  gcry_sexp_release (sexp_data);
  gcry_sexp_release (sexp_key);
  _gcry_ac_data_destroy (data_value);

  return gcry_error (err);
}




/*
 * Implementation of encoding methods (em).
 */

/* Type for functions that encode or decode (hence the name) a
   message.  */
typedef gcry_error_t (*gcry_ac_em_dencode_t) (unsigned int flags,
						 void *options,
						 gcry_ac_io_t *ac_io_read,
						 gcry_ac_io_t *ac_io_write);

/* Fill the buffer BUFFER which is BUFFER_N bytes long with non-zero
   random bytes of random level LEVEL.  */
static void
em_randomize_nonzero (unsigned char *buffer, size_t buffer_n,
		      gcry_random_level_t level)
{
  unsigned char *buffer_rand;
  unsigned int buffer_rand_n;
  unsigned int zeros;
  unsigned int i;
  unsigned int j;

  for (i = 0; i < buffer_n; i++)
    buffer[i] = 0;
  
  do
    {
      /* Count zeros.  */
      for (i = zeros = 0; i < buffer_n; i++)
	if (! buffer[i])
	  zeros++;

      if (zeros)
	{
	  /* Get random bytes.  */
	  buffer_rand_n = zeros + (zeros / 128);
	  buffer_rand = gcry_random_bytes_secure (buffer_rand_n, level);

	  /* Substitute zeros with non-zero random bytes.  */
	  for (i = j = 0; zeros && (i < buffer_n) && (j < buffer_rand_n); i++)
	    if (! buffer[i])
	      {
		while ((j < buffer_rand_n) && (! buffer_rand[j]))
		  j++;
		if (j < buffer_rand_n)
		  {
		    buffer[i] = buffer_rand[j++];
		    zeros--;
		  }
		else
		  break;
	      }
	  gcry_free (buffer_rand);
	}
    }
  while (zeros);
}

/* Encode a message according to the Encoding Method for Encryption
   `PKCS-V1_5' (EME-PKCS-V1_5).  */
static gcry_error_t
eme_pkcs_v1_5_encode (unsigned int flags, void *opts,
		      gcry_ac_io_t *ac_io_read,
		      gcry_ac_io_t *ac_io_write)
{
  gcry_ac_eme_pkcs_v1_5_t *options;
  gcry_error_t err;
  unsigned char *buffer;
  unsigned char *ps;
  unsigned char *m;
  size_t m_n;
  unsigned int ps_n;
  unsigned int k;

  (void)flags;

  options = opts;
  buffer = NULL;
  m = NULL;

  err = _gcry_ac_io_read_all (ac_io_read, &m, &m_n);
  if (err)
    goto out;

  /* Figure out key length in bytes.  */
  k = options->key_size / 8;

  if (m_n > k - 11)
    {
      /* Key is too short for message.  */
      err = gcry_error (GPG_ERR_TOO_SHORT);
      goto out;
    }

  /* According to this encoding method, the first byte of the encoded
     message is zero.  This byte will be lost anyway, when the encoded
     message is to be converted into an MPI, that's why we skip
     it.  */

  /* Allocate buffer.  */
  buffer = gcry_malloc (k - 1);
  if (! buffer)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  /* Generate an octet string PS of length k - mLen - 3 consisting
     of pseudorandomly generated nonzero octets.  The length of PS
     will be at least eight octets.  */
  ps_n = k - m_n - 3;
  ps = buffer + 1;
  em_randomize_nonzero (ps, ps_n, GCRY_STRONG_RANDOM);

  /* Concatenate PS, the message M, and other padding to form an
     encoded message EM of length k octets as:

     EM = 0x00 || 0x02 || PS || 0x00 || M.  */

  buffer[0] = 0x02;
  buffer[ps_n + 1] = 0x00;
  memcpy (buffer + ps_n + 2, m, m_n);

  err = _gcry_ac_io_write (ac_io_write, buffer, k - 1);

 out:

  gcry_free (buffer);
  gcry_free (m);

  return err;
}

/* Decode a message according to the Encoding Method for Encryption
   `PKCS-V1_5' (EME-PKCS-V1_5).  */
static gcry_error_t
eme_pkcs_v1_5_decode (unsigned int flags, void *opts,
		      gcry_ac_io_t *ac_io_read,
		      gcry_ac_io_t *ac_io_write)
{
  gcry_ac_eme_pkcs_v1_5_t *options;
  unsigned char *buffer;
  unsigned char *em;
  size_t em_n;
  gcry_error_t err;
  unsigned int i;
  unsigned int k;

  (void)flags;

  options = opts;
  buffer = NULL;
  em = NULL;

  err = _gcry_ac_io_read_all (ac_io_read, &em, &em_n);
  if (err)
    goto out;

  /* Figure out key size.  */
  k = options->key_size / 8;

  /* Search for zero byte.  */
  for (i = 0; (i < em_n) && em[i]; i++);

  /* According to this encoding method, the first byte of the encoded
     message should be zero.  This byte is lost.  */

  if (! ((em_n >= 10)
	 && (em_n == (k - 1))
	 && (em[0] == 0x02)
	 && (i < em_n)
	 && ((i - 1) >= 8)))
    {
      err = gcry_error (GPG_ERR_DECRYPT_FAILED);
      goto out;
    }

  i++;
  buffer = gcry_malloc (em_n - i);
  if (! buffer)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  memcpy (buffer, em + i, em_n - i);
  err = _gcry_ac_io_write (ac_io_write, buffer, em_n - i);

 out:

  gcry_free (buffer);
  gcry_free (em);

  return err;
}

static gcry_error_t
emsa_pkcs_v1_5_encode_data_cb (void *opaque,
			       unsigned char *buffer, size_t buffer_n)
{
  gcry_md_hd_t md_handle;

  md_handle = opaque;
  gcry_md_write (md_handle, buffer, buffer_n);

  return 0;
}


/* Encode a message according to the Encoding Method for Signatures
   with Appendix `PKCS-V1_5' (EMSA-PKCS-V1_5).  */
static gcry_error_t
emsa_pkcs_v1_5_encode (unsigned int flags, void *opts,
		       gcry_ac_io_t *ac_io_read,
		       gcry_ac_io_t *ac_io_write)
{
  gcry_ac_emsa_pkcs_v1_5_t *options;
  gcry_error_t err;
  gcry_md_hd_t md;
  unsigned char *t;
  size_t t_n;
  unsigned char *h;
  size_t h_n;
  unsigned char *ps;
  size_t ps_n;
  unsigned char *buffer;
  size_t buffer_n;
  unsigned char asn[100];	/* FIXME, always enough?  */
  size_t asn_n;
  unsigned int i;

  (void)flags;
  
  options = opts;
  buffer = NULL;
  md = NULL;
  ps = NULL;
  t = NULL;

  /* Create hashing handle and get the necessary information.  */
  err = gcry_md_open (&md, options->md, 0);
  if (err)
    goto out;

  asn_n = DIM (asn);
  err = gcry_md_algo_info (options->md, GCRYCTL_GET_ASNOID, asn, &asn_n);
  if (err)
    goto out;

  h_n = gcry_md_get_algo_dlen (options->md);

  err = _gcry_ac_io_process (ac_io_read, emsa_pkcs_v1_5_encode_data_cb, md);
  if (err)
    goto out;

  h = gcry_md_read (md, 0);

  /* Encode the algorithm ID for the hash function and the hash value
     into an ASN.1 value of type DigestInfo with the Distinguished
     Encoding Rules (DER), where the type DigestInfo has the syntax:

     DigestInfo ::== SEQUENCE {
     digestAlgorithm AlgorithmIdentifier,
     digest OCTET STRING
     }

     The first field identifies the hash function and the second
     contains the hash value.  Let T be the DER encoding of the
     DigestInfo value and let tLen be the length in octets of T.  */

  t_n = asn_n + h_n;
  t = gcry_malloc (t_n);
  if (! t)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  for (i = 0; i < asn_n; i++)
    t[i] = asn[i];
  for (i = 0; i < h_n; i++)
    t[asn_n + i] = h[i];

  /* If emLen < tLen + 11, output "intended encoded message length
     too short" and stop.  */
  if (options->em_n < t_n + 11)
    {
      err = gcry_error (GPG_ERR_TOO_SHORT);
      goto out;
    }

  /* Generate an octet string PS consisting of emLen - tLen - 3 octets
     with hexadecimal value 0xFF.  The length of PS will be at least 8
     octets.  */
  ps_n = options->em_n - t_n - 3;
  ps = gcry_malloc (ps_n);
  if (! ps)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }
  for (i = 0; i < ps_n; i++)
    ps[i] = 0xFF;

  /* Concatenate PS, the DER encoding T, and other padding to form the
     encoded message EM as:

     EM = 0x00 || 0x01 || PS || 0x00 || T.  */

  buffer_n = ps_n + t_n + 3;
  buffer = gcry_malloc (buffer_n);
  if (! buffer)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }

  buffer[0] = 0x00;
  buffer[1] = 0x01;
  for (i = 0; i < ps_n; i++)
    buffer[2 + i] = ps[i];
  buffer[2 + ps_n] = 0x00;
  for (i = 0; i < t_n; i++)
    buffer[3 + ps_n + i] = t[i];

  err = _gcry_ac_io_write (ac_io_write, buffer, buffer_n);

 out:

  gcry_md_close (md);

  gcry_free (buffer);
  gcry_free (ps);
  gcry_free (t);

  return err;
}

/* `Actions' for data_dencode().  */
typedef enum dencode_action
  {
    DATA_ENCODE,
    DATA_DECODE,
  }
dencode_action_t;

/* Encode or decode a message according to the the encoding method
   METHOD; ACTION specifies wether the message that is contained in
   BUFFER_IN and of length BUFFER_IN_N should be encoded or decoded.
   The resulting message will be stored in a newly allocated buffer in
   BUFFER_OUT and BUFFER_OUT_N.  */
static gcry_error_t
ac_data_dencode (gcry_ac_em_t method, dencode_action_t action,
		 unsigned int flags, void *options,
		 gcry_ac_io_t *ac_io_read,
		 gcry_ac_io_t *ac_io_write)
{
  struct
  {
    gcry_ac_em_t method;
    gcry_ac_em_dencode_t encode;
    gcry_ac_em_dencode_t decode;
  } methods[] =
    {
      { GCRY_AC_EME_PKCS_V1_5,
	eme_pkcs_v1_5_encode, eme_pkcs_v1_5_decode },
      { GCRY_AC_EMSA_PKCS_V1_5,
	emsa_pkcs_v1_5_encode, NULL },
    };
  size_t methods_n;
  gcry_error_t err;
  unsigned int i;

  methods_n = sizeof (methods) / sizeof (*methods);

  for (i = 0; i < methods_n; i++)
    if (methods[i].method == method)
      break;
  if (i == methods_n)
    {
      err = gcry_error (GPG_ERR_NOT_FOUND);	/* FIXME? */
      goto out;
    }

  err = 0;
  switch (action)
    {
    case DATA_ENCODE:
      if (methods[i].encode)
	/* FIXME? */
	err = (*methods[i].encode) (flags, options, ac_io_read, ac_io_write);
      break;

    case DATA_DECODE:
      if (methods[i].decode)
	/* FIXME? */
	err = (*methods[i].decode) (flags, options, ac_io_read, ac_io_write);
      break;

    default:
      err = gcry_error (GPG_ERR_INV_ARG);
      break;
    }

 out:

  return err;
}

/* Encode a message according to the encoding method METHOD.  OPTIONS
   must be a pointer to a method-specific structure
   (gcry_ac_em*_t).  */
gcry_error_t
_gcry_ac_data_encode (gcry_ac_em_t method,
		      unsigned int flags, void *options,
		      gcry_ac_io_t *ac_io_read,
		      gcry_ac_io_t *ac_io_write)
{
  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  return ac_data_dencode (method, DATA_ENCODE, flags, options,
			  ac_io_read, ac_io_write);
}

/* Dencode a message according to the encoding method METHOD.  OPTIONS
   must be a pointer to a method-specific structure
   (gcry_ac_em*_t).  */
gcry_error_t
_gcry_ac_data_decode (gcry_ac_em_t method,
		      unsigned int flags, void *options,
		      gcry_ac_io_t *ac_io_read,
		      gcry_ac_io_t *ac_io_write)
{
  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  return ac_data_dencode (method, DATA_DECODE, flags, options,
			  ac_io_read, ac_io_write);
}

/* Convert an MPI into an octet string.  */
void
_gcry_ac_mpi_to_os (gcry_mpi_t mpi, unsigned char *os, size_t os_n)
{
  unsigned long digit;
  gcry_mpi_t base;
  unsigned int i;
  unsigned int n;
  gcry_mpi_t m;
  gcry_mpi_t d;

  if (fips_mode ())
    return;

  base = gcry_mpi_new (0);
  gcry_mpi_set_ui (base, 256);

  n = 0;
  m = gcry_mpi_copy (mpi);
  while (gcry_mpi_cmp_ui (m, 0))
    {
      n++;
      gcry_mpi_div (m, NULL, m, base, 0);
    }

  gcry_mpi_set (m, mpi);
  d = gcry_mpi_new (0);
  for (i = 0; (i < n) && (i < os_n); i++)
    {
      gcry_mpi_mod (d, m, base);
      _gcry_mpi_get_ui (d, &digit);
      gcry_mpi_div (m, NULL, m, base, 0);
      os[os_n - i - 1] = (digit & 0xFF);
    }

  for (; i < os_n; i++)
    os[os_n - i - 1] = 0;

  gcry_mpi_release (base);
  gcry_mpi_release (d);
  gcry_mpi_release (m);
}

/* Convert an MPI into an newly allocated octet string.  */
gcry_error_t
_gcry_ac_mpi_to_os_alloc (gcry_mpi_t mpi, unsigned char **os, size_t *os_n)
{
  unsigned char *buffer;
  size_t buffer_n;
  gcry_error_t err;
  unsigned int nbits;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  nbits = gcry_mpi_get_nbits (mpi);
  buffer_n = (nbits + 7) / 8;
  buffer = gcry_malloc (buffer_n);
  if (! buffer)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }
      
  _gcry_ac_mpi_to_os (mpi, buffer, buffer_n);
  *os = buffer;
  *os_n = buffer_n;
  err = 0;

 out:

  return err;
}


/* Convert an octet string into an MPI.  */
void
_gcry_ac_os_to_mpi (gcry_mpi_t mpi, unsigned char *os, size_t os_n)
{
  unsigned int i;
  gcry_mpi_t xi;
  gcry_mpi_t x;
  gcry_mpi_t a;
  
  if (fips_mode ())
    return;

  a = gcry_mpi_new (0);
  gcry_mpi_set_ui (a, 1);
  x = gcry_mpi_new (0);
  gcry_mpi_set_ui (x, 0);
  xi = gcry_mpi_new (0);

  for (i = 0; i < os_n; i++)
    {
      gcry_mpi_mul_ui (xi, a, os[os_n - i - 1]);
      gcry_mpi_add (x, x, xi);
      gcry_mpi_mul_ui (a, a, 256);
    }
      
  gcry_mpi_release (xi);
  gcry_mpi_release (a);

  gcry_mpi_set (mpi, x);
  gcry_mpi_release (x);		/* FIXME: correct? */
}



/* 
 * Implementation of Encryption Schemes (ES) and Signature Schemes
 * with Appendix (SSA).
 */

/* Schemes consist of two things: encoding methods and cryptographic
   primitives.

   Since encoding methods are accessible through a common API with
   method-specific options passed as an anonymous struct, schemes have
   to provide functions that construct this method-specific structure;
   this is what the functions of type `gcry_ac_dencode_prepare_t' are
   there for.  */

typedef gcry_error_t (*gcry_ac_dencode_prepare_t) (gcry_ac_handle_t handle,
						   gcry_ac_key_t key,
						   void *opts,
						   void *opts_em);

/* The `dencode_prepare' function for ES-PKCS-V1_5.  */
static gcry_error_t
ac_es_dencode_prepare_pkcs_v1_5 (gcry_ac_handle_t handle, gcry_ac_key_t key,
				 void *opts, void *opts_em)
{
  gcry_ac_eme_pkcs_v1_5_t *options_em;
  unsigned int nbits;
  gcry_error_t err;

  (void)opts;

  err = _gcry_ac_key_get_nbits (handle, key, &nbits);
  if (err)
    goto out;

  options_em = opts_em;
  options_em->key_size = nbits;

 out:

  return err;
}

/* The `dencode_prepare' function for SSA-PKCS-V1_5.  */
static gcry_error_t
ac_ssa_dencode_prepare_pkcs_v1_5 (gcry_ac_handle_t handle, gcry_ac_key_t key,
				  void *opts, void *opts_em)
{
  gcry_ac_emsa_pkcs_v1_5_t *options_em;
  gcry_ac_ssa_pkcs_v1_5_t *options;
  gcry_error_t err;
  unsigned int k;

  options_em = opts_em;
  options = opts;

  err = _gcry_ac_key_get_nbits (handle, key, &k);
  if (err)
    goto out;

  k = (k + 7) / 8;
  options_em->md = options->md;
  options_em->em_n = k;

 out:

  return err;
}

/* Type holding the information about each supported
   Encryption/Signature Scheme.  */
typedef struct ac_scheme
{
  gcry_ac_scheme_t scheme;
  gcry_ac_em_t scheme_encoding;
  gcry_ac_dencode_prepare_t dencode_prepare;
  size_t options_em_n;
} ac_scheme_t;

/* List of supported Schemes.  */
static ac_scheme_t ac_schemes[] =
  {
    { GCRY_AC_ES_PKCS_V1_5, GCRY_AC_EME_PKCS_V1_5,
      ac_es_dencode_prepare_pkcs_v1_5,
      sizeof (gcry_ac_eme_pkcs_v1_5_t) },
    { GCRY_AC_SSA_PKCS_V1_5, GCRY_AC_EMSA_PKCS_V1_5,
      ac_ssa_dencode_prepare_pkcs_v1_5,
      sizeof (gcry_ac_emsa_pkcs_v1_5_t) }
  };

/* Lookup a scheme by it's ID.  */
static ac_scheme_t *
ac_scheme_get (gcry_ac_scheme_t scheme)
{
  ac_scheme_t *ac_scheme;
  unsigned int i;

  for (i = 0; i < DIM (ac_schemes); i++)
    if (scheme == ac_schemes[i].scheme)
      break;
  if (i == DIM (ac_schemes))
    ac_scheme = NULL;
  else
    ac_scheme = ac_schemes + i;

  return ac_scheme;
}

/* Prepares the encoding/decoding by creating an according option
   structure.  */
static gcry_error_t
ac_dencode_prepare (gcry_ac_handle_t handle, gcry_ac_key_t key, void *opts,
		    ac_scheme_t scheme, void **opts_em)
{
  gcry_error_t err;
  void *options_em;

  options_em = gcry_malloc (scheme.options_em_n);
  if (! options_em)
    {
      err = gcry_error_from_errno (errno);
      goto out;
    }
  
  err = (*scheme.dencode_prepare) (handle, key, opts, options_em);
  if (err)
    goto out;

  *opts_em = options_em;

 out:

  if (err)
    free (options_em);

  return err;
}

/* Convert a data set into a single MPI; currently, this is only
   supported for data sets containing a single MPI.  */
static gcry_error_t
ac_data_set_to_mpi (gcry_ac_data_t data, gcry_mpi_t *mpi)
{
  gcry_error_t err;
  gcry_mpi_t mpi_new;
  unsigned int elems;

  elems = _gcry_ac_data_length (data);

  if (elems != 1)
    {
      /* FIXME: I guess, we should be more flexible in this respect by
	 allowing the actual encryption/signature schemes to implement
	 this conversion mechanism.  */
      err = gcry_error (GPG_ERR_CONFLICT);
      goto out;
    }

  err = _gcry_ac_data_get_index (data, GCRY_AC_FLAG_COPY, 0, NULL, &mpi_new);
  if (err)
    goto out;

  *mpi = mpi_new;

 out:

  return err;
}

/* Encrypts the plain text message contained in M, which is of size
   M_N, with the public key KEY_PUBLIC according to the Encryption
   Scheme SCHEME_ID.  HANDLE is used for accessing the low-level
   cryptographic primitives.  If OPTS is not NULL, it has to be an
   anonymous structure specific to the chosen scheme (gcry_ac_es_*_t).
   The encrypted message will be stored in C and C_N.  */
gcry_error_t
_gcry_ac_data_encrypt_scheme (gcry_ac_handle_t handle,
			      gcry_ac_scheme_t scheme_id,
			      unsigned int flags, void *opts,
			      gcry_ac_key_t key,
			      gcry_ac_io_t *io_message,
			      gcry_ac_io_t *io_cipher)
{
  gcry_error_t err;
  gcry_ac_io_t io_em;
  unsigned char *em;
  size_t em_n;
  gcry_mpi_t mpi_plain;
  gcry_ac_data_t data_encrypted;
  gcry_mpi_t mpi_encrypted;
  unsigned char *buffer;
  size_t buffer_n;
  void *opts_em;
  ac_scheme_t *scheme;

  (void)flags;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  data_encrypted = NULL;
  mpi_encrypted = NULL;
  mpi_plain = NULL;
  opts_em = NULL;
  buffer = NULL;
  em = NULL;

  scheme = ac_scheme_get (scheme_id);
  if (! scheme)
    {
      err = gcry_error (GPG_ERR_NO_ENCRYPTION_SCHEME);
      goto out;
    }

  if (key->type != GCRY_AC_KEY_PUBLIC)
    {
      err = gcry_error (GPG_ERR_WRONG_KEY_USAGE);
      goto out;
    }

  err = ac_dencode_prepare (handle, key, opts, *scheme, &opts_em);
  if (err)
    goto out;

  _gcry_ac_io_init (&io_em, GCRY_AC_IO_WRITABLE,
		    GCRY_AC_IO_STRING, &em, &em_n);

  err = _gcry_ac_data_encode (scheme->scheme_encoding, 0, opts_em,
			      io_message, &io_em);
  if (err)
    goto out;

  mpi_plain = gcry_mpi_snew (0);
  gcry_ac_os_to_mpi (mpi_plain, em, em_n);

  err = _gcry_ac_data_encrypt (handle, 0, key, mpi_plain, &data_encrypted);
  if (err)
    goto out;

  err = ac_data_set_to_mpi (data_encrypted, &mpi_encrypted);
  if (err)
    goto out;

  err = _gcry_ac_mpi_to_os_alloc (mpi_encrypted, &buffer, &buffer_n);
  if (err)
    goto out;

  err = _gcry_ac_io_write (io_cipher, buffer, buffer_n);

 out:

  gcry_ac_data_destroy (data_encrypted);
  gcry_mpi_release (mpi_encrypted);
  gcry_mpi_release (mpi_plain);
  gcry_free (opts_em);
  gcry_free (buffer);
  gcry_free (em);

  return err;
}

/* Decryptes the cipher message contained in C, which is of size C_N,
   with the secret key KEY_SECRET according to the Encryption Scheme
   SCHEME_ID.  Handle is used for accessing the low-level
   cryptographic primitives.  If OPTS is not NULL, it has to be an
   anonymous structure specific to the chosen scheme (gcry_ac_es_*_t).
   The decrypted message will be stored in M and M_N.  */
gcry_error_t
_gcry_ac_data_decrypt_scheme (gcry_ac_handle_t handle,
			      gcry_ac_scheme_t scheme_id,
			      unsigned int flags, void *opts,
			      gcry_ac_key_t key,
			      gcry_ac_io_t *io_cipher,
			      gcry_ac_io_t *io_message)
{
  gcry_ac_io_t io_em;
  gcry_error_t err;
  gcry_ac_data_t data_encrypted;
  unsigned char *em;
  size_t em_n;
  gcry_mpi_t mpi_encrypted;
  gcry_mpi_t mpi_decrypted;
  void *opts_em;
  ac_scheme_t *scheme;
  char *elements_enc;
  size_t elements_enc_n;
  unsigned char *c;
  size_t c_n;

  (void)flags;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  data_encrypted = NULL;
  mpi_encrypted = NULL;
  mpi_decrypted = NULL;
  elements_enc = NULL;
  opts_em = NULL;
  em = NULL;
  c = NULL;

  scheme = ac_scheme_get (scheme_id);
  if (! scheme)
    {
      err = gcry_error (GPG_ERR_NO_ENCRYPTION_SCHEME);
      goto out;
    }

  if (key->type != GCRY_AC_KEY_SECRET)
    {
      err = gcry_error (GPG_ERR_WRONG_KEY_USAGE);
      goto out;
    }

  err = _gcry_ac_io_read_all (io_cipher, &c, &c_n);
  if (err)
    goto out;

  mpi_encrypted = gcry_mpi_snew (0);
  gcry_ac_os_to_mpi (mpi_encrypted, c, c_n);

  err = _gcry_pk_get_elements (handle->algorithm, &elements_enc, NULL);
  if (err)
    goto out;

  elements_enc_n = strlen (elements_enc);
  if (elements_enc_n != 1)
    {
      /* FIXME? */
      err = gcry_error (GPG_ERR_CONFLICT);
      goto out;
    }

  err = _gcry_ac_data_new (&data_encrypted);
  if (err)
    goto out;

  err = _gcry_ac_data_set (data_encrypted, GCRY_AC_FLAG_COPY | GCRY_AC_FLAG_DEALLOC,
			   elements_enc, mpi_encrypted);
  if (err)
    goto out;

  err = _gcry_ac_data_decrypt (handle, 0, key, &mpi_decrypted, data_encrypted);
  if (err)
    goto out;

  err = _gcry_ac_mpi_to_os_alloc (mpi_decrypted, &em, &em_n);
  if (err)
    goto out;

  err = ac_dencode_prepare (handle, key, opts, *scheme, &opts_em);
  if (err)
    goto out;

  _gcry_ac_io_init (&io_em, GCRY_AC_IO_READABLE,
		    GCRY_AC_IO_STRING, em, em_n);

  err = _gcry_ac_data_decode (scheme->scheme_encoding, 0, opts_em,
			      &io_em, io_message);
  if (err)
    goto out;

 out:
  
  _gcry_ac_data_destroy (data_encrypted);
  gcry_mpi_release (mpi_encrypted);
  gcry_mpi_release (mpi_decrypted);
  free (elements_enc);
  gcry_free (opts_em);
  gcry_free (em);
  gcry_free (c);

  return err;
}


/* Signs the message contained in M, which is of size M_N, with the
   secret key KEY according to the Signature Scheme SCHEME_ID.  Handle
   is used for accessing the low-level cryptographic primitives.  If
   OPTS is not NULL, it has to be an anonymous structure specific to
   the chosen scheme (gcry_ac_ssa_*_t).  The signed message will be
   stored in S and S_N.  */
gcry_error_t
_gcry_ac_data_sign_scheme (gcry_ac_handle_t handle,
			   gcry_ac_scheme_t scheme_id,
			   unsigned int flags, void *opts,
			   gcry_ac_key_t key,
			   gcry_ac_io_t *io_message,
			   gcry_ac_io_t *io_signature)
{
  gcry_ac_io_t io_em;
  gcry_error_t err;
  gcry_ac_data_t data_signed;
  unsigned char *em;
  size_t em_n;
  gcry_mpi_t mpi;
  void *opts_em;
  unsigned char *buffer;
  size_t buffer_n;
  gcry_mpi_t mpi_signed;
  ac_scheme_t *scheme;

  (void)flags;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  data_signed = NULL;
  mpi_signed = NULL;
  opts_em = NULL;
  buffer = NULL;
  mpi = NULL;
  em = NULL;

  if (key->type != GCRY_AC_KEY_SECRET)
    {
      err = gcry_error (GPG_ERR_WRONG_KEY_USAGE);
      goto out;
    }

  scheme = ac_scheme_get (scheme_id);
  if (! scheme)
    {
      /* FIXME: adjust api of scheme_get in respect to err codes.  */
      err = gcry_error (GPG_ERR_NO_SIGNATURE_SCHEME);
      goto out;
    }

  err = ac_dencode_prepare (handle, key, opts, *scheme, &opts_em);
  if (err)
    goto out;

  _gcry_ac_io_init (&io_em, GCRY_AC_IO_WRITABLE,
		    GCRY_AC_IO_STRING, &em, &em_n);

  err = _gcry_ac_data_encode (scheme->scheme_encoding, 0, opts_em,
			      io_message, &io_em);
  if (err)
    goto out;

  mpi = gcry_mpi_new (0);
  _gcry_ac_os_to_mpi (mpi, em, em_n);

  err = _gcry_ac_data_sign (handle, key, mpi, &data_signed);
  if (err)
    goto out;

  err = ac_data_set_to_mpi (data_signed, &mpi_signed);
  if (err)
    goto out;

  err = _gcry_ac_mpi_to_os_alloc (mpi_signed, &buffer, &buffer_n);
  if (err)
    goto out;

  err = _gcry_ac_io_write (io_signature, buffer, buffer_n);

 out:

  _gcry_ac_data_destroy (data_signed);
  gcry_mpi_release (mpi_signed);
  gcry_mpi_release (mpi);
  gcry_free (opts_em);
  gcry_free (buffer);
  gcry_free (em);

  return err;
}

/* Verifies that the signature contained in S, which is of length S_N,
   is indeed the result of signing the message contained in M, which
   is of size M_N, with the secret key belonging to the public key
   KEY_PUBLIC.  If OPTS is not NULL, it has to be an anonymous
   structure (gcry_ac_ssa_*_t) specific to the Signature Scheme, whose
   ID is contained in SCHEME_ID.  */
gcry_error_t
_gcry_ac_data_verify_scheme (gcry_ac_handle_t handle,
			     gcry_ac_scheme_t scheme_id,
			     unsigned int flags, void *opts,
			     gcry_ac_key_t key,
			     gcry_ac_io_t *io_message,
			     gcry_ac_io_t *io_signature)
{
  gcry_ac_io_t io_em;
  gcry_error_t err;
  gcry_ac_data_t data_signed;
  unsigned char *em;
  size_t em_n;
  void *opts_em;
  gcry_mpi_t mpi_signature;
  gcry_mpi_t mpi_data;
  ac_scheme_t *scheme;
  char *elements_sig;
  size_t elements_sig_n;
  unsigned char *s;
  size_t s_n;

  (void)flags;

  if (fips_mode ())
    return gpg_error (GPG_ERR_NOT_SUPPORTED);

  mpi_signature = NULL;
  elements_sig = NULL;
  data_signed = NULL;
  mpi_data = NULL;
  opts_em = NULL;
  em = NULL;
  s = NULL;

  if (key->type != GCRY_AC_KEY_PUBLIC)
    {
      err = gcry_error (GPG_ERR_WRONG_KEY_USAGE);
      goto out;
    }

  scheme = ac_scheme_get (scheme_id);
  if (! scheme)
    {
      err = gcry_error (GPG_ERR_NO_SIGNATURE_SCHEME);
      goto out;
    }

  err = ac_dencode_prepare (handle, key, opts, *scheme, &opts_em);
  if (err)
    goto out;

  _gcry_ac_io_init (&io_em, GCRY_AC_IO_WRITABLE,
		    GCRY_AC_IO_STRING, &em, &em_n);

  err = _gcry_ac_data_encode (scheme->scheme_encoding, 0, opts_em,
			      io_message, &io_em);
  if (err)
    goto out;

  mpi_data = gcry_mpi_new (0);
  _gcry_ac_os_to_mpi (mpi_data, em, em_n);

  err = _gcry_ac_io_read_all (io_signature, &s, &s_n);
  if (err)
    goto out;

  mpi_signature = gcry_mpi_new (0);
  _gcry_ac_os_to_mpi (mpi_signature, s, s_n);

  err = _gcry_pk_get_elements (handle->algorithm, NULL, &elements_sig);
  if (err)
    goto out;

  elements_sig_n = strlen (elements_sig);
  if (elements_sig_n != 1)
    {
      /* FIXME? */
      err = gcry_error (GPG_ERR_CONFLICT);
      goto out;
    }

  err = _gcry_ac_data_new (&data_signed);
  if (err)
    goto out;

  err = _gcry_ac_data_set (data_signed, GCRY_AC_FLAG_COPY | GCRY_AC_FLAG_DEALLOC,
			   elements_sig, mpi_signature);
  if (err)
    goto out;

  gcry_mpi_release (mpi_signature);
  mpi_signature = NULL;
  
  err = _gcry_ac_data_verify (handle, key, mpi_data, data_signed);

 out:

  _gcry_ac_data_destroy (data_signed);
  gcry_mpi_release (mpi_signature);
  gcry_mpi_release (mpi_data);
  free (elements_sig);
  gcry_free (opts_em);
  gcry_free (em);
  gcry_free (s);

  return err;
}


/* 
 * General functions.
 */

gcry_err_code_t
_gcry_ac_init (void)
{
  if (fips_mode ())
    return GPG_ERR_NOT_SUPPORTED;

  return 0;
}