summaryrefslogtreecommitdiff
path: root/source4/heimdal/lib/hx509/crypto.c
blob: 96d9693cc25f58081afd9f52561ed729f2be6694 (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
/*
 * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan
 * (Royal Institute of Technology, Stockholm, Sweden). 
 * All rights reserved. 
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions 
 * are met: 
 *
 * 1. Redistributions of source code must retain the above copyright 
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright 
 *    notice, this list of conditions and the following disclaimer in the 
 *    documentation and/or other materials provided with the distribution. 
 *
 * 3. Neither the name of the Institute nor the names of its contributors 
 *    may be used to endorse or promote products derived from this software 
 *    without specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE 
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
 * SUCH DAMAGE. 
 */

#include "hx_locl.h"
RCSID("$Id: crypto.c 20939 2007-06-06 20:53:02Z lha $");

struct hx509_crypto;

struct signature_alg;

enum crypto_op_type {
    COT_SIGN
};

struct hx509_generate_private_context {
    const heim_oid *key_oid;
    int isCA;
    unsigned long num_bits;
};

struct hx509_private_key_ops {
    const char *pemtype;
    const heim_oid *(*key_oid)(void);
    int (*get_spki)(hx509_context,
		    const hx509_private_key,
		    SubjectPublicKeyInfo *);
    int (*export)(hx509_context context,
		  const hx509_private_key,
		  heim_octet_string *);
    int (*import)(hx509_context,
		  const void *data,
		  size_t len,
		  hx509_private_key private_key);
    int (*generate_private_key)(hx509_context,
				struct hx509_generate_private_context *,
				hx509_private_key);
    int (*handle_alg)(const hx509_private_key,
		      const AlgorithmIdentifier *,
		      enum crypto_op_type);
    int (*sign)(hx509_context context,
		const hx509_private_key,
		const AlgorithmIdentifier *,
		const heim_octet_string *,
		AlgorithmIdentifier *,
		heim_octet_string *);
#if 0
    const AlgorithmIdentifier *(*preferred_sig_alg)
	(const hx509_private_key,
	 const hx509_peer_info);
    int (*unwrap)(hx509_context context,
		  const hx509_private_key,
		  const AlgorithmIdentifier *,
		  const heim_octet_string *,
		  heim_octet_string *);
#endif
};

struct hx509_private_key {
    unsigned int ref;
    const struct signature_alg *md;
    const heim_oid *signature_alg;
    union {
	RSA *rsa;
	void *keydata;
    } private_key;
    /* new crypto layer */
    hx509_private_key_ops *ops;
};

/*
 *
 */

struct signature_alg {
    const char *name;
    const heim_oid *(*sig_oid)(void);
    const AlgorithmIdentifier *(*sig_alg)(void);
    const heim_oid *(*key_oid)(void);
    const heim_oid *(*digest_oid)(void);
    int flags;
#define PROVIDE_CONF 1
#define REQUIRE_SIGNER 2

#define SIG_DIGEST	0x100
#define SIG_PUBLIC_SIG	0x200
#define SIG_SECRET	0x400

    int (*verify_signature)(hx509_context context,
			    const struct signature_alg *,
			    const Certificate *,
			    const AlgorithmIdentifier *,
			    const heim_octet_string *,
			    const heim_octet_string *);
    int (*create_signature)(hx509_context,
			    const struct signature_alg *,
			    const hx509_private_key,
			    const AlgorithmIdentifier *,
			    const heim_octet_string *,
			    AlgorithmIdentifier *,
			    heim_octet_string *);
};

/*
 *
 */

static BIGNUM *
heim_int2BN(const heim_integer *i)
{
    BIGNUM *bn;

    bn = BN_bin2bn(i->data, i->length, NULL);
    BN_set_negative(bn, i->negative);
    return bn;
}

/*
 *
 */

static int
set_digest_alg(DigestAlgorithmIdentifier *id,
	       const heim_oid *oid,
	       const void *param, size_t length)
{
    int ret;
    if (param) {
	id->parameters = malloc(sizeof(*id->parameters));
	if (id->parameters == NULL)
	    return ENOMEM;
	id->parameters->data = malloc(length);
	if (id->parameters->data == NULL) {
	    free(id->parameters);
	    id->parameters = NULL;
	    return ENOMEM;
	}
	memcpy(id->parameters->data, param, length);
	id->parameters->length = length;
    } else
	id->parameters = NULL;
    ret = der_copy_oid(oid, &id->algorithm);
    if (ret) {
	if (id->parameters) {
	    free(id->parameters->data);
	    free(id->parameters);
	    id->parameters = NULL;
	}
	return ret;
    }
    return 0;
}

/*
 *
 */

static int
rsa_verify_signature(hx509_context context,
		     const struct signature_alg *sig_alg,
		     const Certificate *signer,
		     const AlgorithmIdentifier *alg,
		     const heim_octet_string *data,
		     const heim_octet_string *sig)
{
    const SubjectPublicKeyInfo *spi;
    DigestInfo di;
    unsigned char *to;
    int tosize, retsize;
    int ret;
    RSA *rsa;
    RSAPublicKey pk;
    size_t size;

    memset(&di, 0, sizeof(di));

    spi = &signer->tbsCertificate.subjectPublicKeyInfo;

    rsa = RSA_new();
    if (rsa == NULL) {
	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
	return ENOMEM;
    }
    ret = decode_RSAPublicKey(spi->subjectPublicKey.data,
			      spi->subjectPublicKey.length / 8,
			      &pk, &size);
    if (ret) {
	hx509_set_error_string(context, 0, ret, "Failed to decode RSAPublicKey");
	goto out;
    }

    rsa->n = heim_int2BN(&pk.modulus);
    rsa->e = heim_int2BN(&pk.publicExponent);

    free_RSAPublicKey(&pk);

    if (rsa->n == NULL || rsa->e == NULL) {
	ret = ENOMEM;
	hx509_set_error_string(context, 0, ret, "out of memory");
	goto out;
    }

    tosize = RSA_size(rsa);
    to = malloc(tosize);
    if (to == NULL) {
	ret = ENOMEM;
	hx509_set_error_string(context, 0, ret, "out of memory");
	goto out;
    }

    retsize = RSA_public_decrypt(sig->length, (unsigned char *)sig->data, 
				 to, rsa, RSA_PKCS1_PADDING);
    if (retsize <= 0) {
	ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
	hx509_set_error_string(context, 0, ret, 
			       "RSA public decrypt failed: %d", retsize);
	free(to);
	goto out;
    }
    if (retsize > tosize)
	_hx509_abort("internal rsa decryption failure: ret > tosize");
    ret = decode_DigestInfo(to, retsize, &di, &size);
    free(to);
    if (ret) {
	goto out;
    }

    /* Check for extra data inside the sigature */
    if (size != retsize) {
	ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
	hx509_set_error_string(context, 0, ret, "size from decryption mismatch");
	goto out;
    }

    if (sig_alg->digest_oid &&
	der_heim_oid_cmp(&di.digestAlgorithm.algorithm, 
		     (*sig_alg->digest_oid)()) != 0) 
    {
	ret = HX509_CRYPTO_OID_MISMATCH;
	hx509_set_error_string(context, 0, ret, "object identifier in RSA sig mismatch");
	goto out;
    }

    /* verify that the parameters are NULL or the NULL-type */
    if (di.digestAlgorithm.parameters != NULL &&
	(di.digestAlgorithm.parameters->length != 2 ||
	 memcmp(di.digestAlgorithm.parameters->data, "\x05\x00", 2) != 0))
    {
	ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
	hx509_set_error_string(context, 0, ret, "Extra parameters inside RSA signature");
	goto out;
    }

    ret = _hx509_verify_signature(context,
				  NULL,
				  &di.digestAlgorithm,
				  data,
				  &di.digest);
 out:
    free_DigestInfo(&di);
    RSA_free(rsa);
    return ret;
}

static int
rsa_create_signature(hx509_context context,
		     const struct signature_alg *sig_alg,
		     const hx509_private_key signer,
		     const AlgorithmIdentifier *alg,
		     const heim_octet_string *data,
		     AlgorithmIdentifier *signatureAlgorithm,
		     heim_octet_string *sig)
{
    const AlgorithmIdentifier *digest_alg;
    heim_octet_string indata;
    const heim_oid *sig_oid;
    DigestInfo di;
    size_t size;
    int ret;
    
    if (alg)
	sig_oid = &alg->algorithm;
    else
	sig_oid = signer->signature_alg;

    if (der_heim_oid_cmp(sig_oid, oid_id_pkcs1_sha256WithRSAEncryption()) == 0) {
	digest_alg = hx509_signature_sha256();
    } else if (der_heim_oid_cmp(sig_oid, oid_id_pkcs1_sha1WithRSAEncryption()) == 0) {
	digest_alg = hx509_signature_sha1();
    } else if (der_heim_oid_cmp(sig_oid, oid_id_pkcs1_md5WithRSAEncryption()) == 0) {
	digest_alg = hx509_signature_md5();
    } else if (der_heim_oid_cmp(sig_oid, oid_id_pkcs1_md5WithRSAEncryption()) == 0) {
	digest_alg = hx509_signature_md5();
    } else if (der_heim_oid_cmp(sig_oid, oid_id_dsa_with_sha1()) == 0) {
	digest_alg = hx509_signature_sha1();
    } else if (der_heim_oid_cmp(sig_oid, oid_id_pkcs1_rsaEncryption()) == 0) {
	digest_alg = hx509_signature_sha1();
    } else
	return HX509_ALG_NOT_SUPP;

    if (signatureAlgorithm) {
	ret = set_digest_alg(signatureAlgorithm, sig_oid, "\x05\x00", 2);
	if (ret) {
	    hx509_clear_error_string(context);
	    return ret;
	}
    }

    memset(&di, 0, sizeof(di));

    ret = _hx509_create_signature(context,
				  NULL,
				  digest_alg,
				  data,
				  &di.digestAlgorithm,
				  &di.digest);
    if (ret)
	return ret;
    ASN1_MALLOC_ENCODE(DigestInfo,
		       indata.data,
		       indata.length,
		       &di,
		       &size,
		       ret);
    free_DigestInfo(&di);
    if (ret) {
	hx509_set_error_string(context, 0, ret, "out of memory");
	return ret;
    }
    if (indata.length != size)
	_hx509_abort("internal ASN.1 encoder error");

    sig->length = RSA_size(signer->private_key.rsa);
    sig->data = malloc(sig->length);
    if (sig->data == NULL) {
	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
	return ENOMEM;
    }

    ret = RSA_private_encrypt(indata.length, indata.data, 
			      sig->data, 
			      signer->private_key.rsa,
			      RSA_PKCS1_PADDING);
    der_free_octet_string(&indata);
    if (ret <= 0) {
	ret = HX509_CMS_FAILED_CREATE_SIGATURE;
	hx509_set_error_string(context, 0, ret,
			       "RSA private decrypt failed: %d", ret);
	return ret;
    }
    if (ret > sig->length)
	_hx509_abort("RSA signature prelen longer the output len");

    sig->length = ret;
    
    return 0;
}

static int
rsa_private_key_import(hx509_context context,
		       const void *data,
		       size_t len,
		       hx509_private_key private_key)
{
    const unsigned char *p = data;

    private_key->private_key.rsa = 
	d2i_RSAPrivateKey(NULL, &p, len);
    if (private_key->private_key.rsa == NULL) {
	hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
			       "Failed to parse RSA key");
	return HX509_PARSING_KEY_FAILED;
    }
    private_key->signature_alg = oid_id_pkcs1_sha1WithRSAEncryption();

    return 0;
}

static int
rsa_private_key2SPKI(hx509_context context,
		     hx509_private_key private_key,
		     SubjectPublicKeyInfo *spki)
{
    int len, ret;

    memset(spki, 0, sizeof(*spki));

    len = i2d_RSAPublicKey(private_key->private_key.rsa, NULL);

    spki->subjectPublicKey.data = malloc(len);
    if (spki->subjectPublicKey.data == NULL) {
	hx509_set_error_string(context, 0, ENOMEM, "malloc - out of memory");
	return ENOMEM;
    }
    spki->subjectPublicKey.length = len * 8;

    ret = set_digest_alg(&spki->algorithm,oid_id_pkcs1_rsaEncryption(), 
			 "\x05\x00", 2);
    if (ret) {
	hx509_set_error_string(context, 0, ret, "malloc - out of memory");
	free(spki->subjectPublicKey.data);
	spki->subjectPublicKey.data = NULL;
	spki->subjectPublicKey.length = 0;
	return ret;
    }

    {
	unsigned char *pp = spki->subjectPublicKey.data;
	i2d_RSAPublicKey(private_key->private_key.rsa, &pp);
    }

    return 0;
}

static int
rsa_generate_private_key(hx509_context context, 
			 struct hx509_generate_private_context *ctx,
			 hx509_private_key private_key)
{
    BIGNUM *e;
    int ret;
    unsigned long bits;

    static const int default_rsa_e = 65537;
    static const int default_rsa_bits = 1024;

    private_key->private_key.rsa = RSA_new();
    if (private_key->private_key.rsa == NULL) {
	hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
			       "Failed to generate RSA key");
	return HX509_PARSING_KEY_FAILED;
    }
    
    e = BN_new();
    BN_set_word(e, default_rsa_e);

    bits = default_rsa_bits;

    if (ctx->num_bits)
	bits = ctx->num_bits;
    else if (ctx->isCA)
	bits *= 2;

    ret = RSA_generate_key_ex(private_key->private_key.rsa, bits, e, NULL);
    BN_free(e);
    if (ret != 1) {
	hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
			       "Failed to generate RSA key");
	return HX509_PARSING_KEY_FAILED;
    }
    private_key->signature_alg = oid_id_pkcs1_sha1WithRSAEncryption();

    return 0;
}

static int 
rsa_private_key_export(hx509_context context,
		       const hx509_private_key key,
		       heim_octet_string *data)
{
    int ret;

    data->data = NULL;
    data->length = 0;

    ret = i2d_RSAPrivateKey(key->private_key.rsa, NULL);
    if (ret <= 0) {
	ret = EINVAL;
	hx509_set_error_string(context, 0, ret,
			       "Private key is not exportable");
	return ret;
    }

    data->data = malloc(ret);
    if (data->data == NULL) {
	ret = ENOMEM;
	hx509_set_error_string(context, 0, ret, "malloc out of memory");
	return ret;
    }
    data->length = ret;
    
    {
	unsigned char *p = data->data;
	i2d_RSAPrivateKey(key->private_key.rsa, &p);
    }

    return 0;
}


static hx509_private_key_ops rsa_private_key_ops = {
    "RSA PRIVATE KEY",
    oid_id_pkcs1_rsaEncryption,
    rsa_private_key2SPKI,
    rsa_private_key_export,
    rsa_private_key_import,
    rsa_generate_private_key
};


/*
 *
 */

static int
dsa_verify_signature(hx509_context context,
		     const struct signature_alg *sig_alg,
		     const Certificate *signer,
		     const AlgorithmIdentifier *alg,
		     const heim_octet_string *data,
		     const heim_octet_string *sig)
{
    const SubjectPublicKeyInfo *spi;
    DSAPublicKey pk;
    DSAParams param;
    size_t size;
    DSA *dsa;
    int ret;

    spi = &signer->tbsCertificate.subjectPublicKeyInfo;

    dsa = DSA_new();
    if (dsa == NULL) {
	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
	return ENOMEM;
    }

    ret = decode_DSAPublicKey(spi->subjectPublicKey.data,
			      spi->subjectPublicKey.length / 8,
			      &pk, &size);
    if (ret)
	goto out;

    dsa->pub_key = heim_int2BN(&pk);

    free_DSAPublicKey(&pk);

    if (dsa->pub_key == NULL) {
	ret = ENOMEM;
	hx509_set_error_string(context, 0, ret, "out of memory");
	goto out;
    }

    if (spi->algorithm.parameters == NULL) {
	ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
	hx509_set_error_string(context, 0, ret, "DSA parameters missing");
	goto out;
    }

    ret = decode_DSAParams(spi->algorithm.parameters->data,
			   spi->algorithm.parameters->length,
			   &param,
			   &size);
    if (ret) {
	hx509_set_error_string(context, 0, ret, "DSA parameters failed to decode");
	goto out;
    }

    dsa->p = heim_int2BN(&param.p);
    dsa->q = heim_int2BN(&param.q);
    dsa->g = heim_int2BN(&param.g);

    free_DSAParams(&param);

    if (dsa->p == NULL || dsa->q == NULL || dsa->g == NULL) {
	ret = ENOMEM;
	hx509_set_error_string(context, 0, ret, "out of memory");
	goto out;
    }

    ret = DSA_verify(-1, data->data, data->length,
		     (unsigned char*)sig->data, sig->length,
		     dsa);
    if (ret == 1)
	ret = 0;
    else if (ret == 0 || ret == -1) {
	ret = HX509_CRYPTO_BAD_SIGNATURE;
	hx509_set_error_string(context, 0, ret, "BAD DSA sigature");
    } else {
	ret = HX509_CRYPTO_SIG_INVALID_FORMAT;
	hx509_set_error_string(context, 0, ret, "Invalid format of DSA sigature");
    }

 out:
    DSA_free(dsa);

    return ret;
}

#if 0
static int
dsa_parse_private_key(hx509_context context,
		      const void *data,
		      size_t len,
		      hx509_private_key private_key)
{
    const unsigned char *p = data;

    private_key->private_key.dsa = 
	d2i_DSAPrivateKey(NULL, &p, len);
    if (private_key->private_key.dsa == NULL)
	return EINVAL;
    private_key->signature_alg = oid_id_dsa_with_sha1();

    return 0;
/* else */
    hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
			   "No support to parse DSA keys");
    return HX509_PARSING_KEY_FAILED;
}
#endif


static int
sha1_verify_signature(hx509_context context,
		      const struct signature_alg *sig_alg,
		      const Certificate *signer,
		      const AlgorithmIdentifier *alg,
		      const heim_octet_string *data,
		      const heim_octet_string *sig)
{
    unsigned char digest[SHA_DIGEST_LENGTH];
    SHA_CTX m;
    
    if (sig->length != SHA_DIGEST_LENGTH) {
	hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT,
			       "SHA1 sigature have wrong length");
	return HX509_CRYPTO_SIG_INVALID_FORMAT;
    }

    SHA1_Init(&m);
    SHA1_Update(&m, data->data, data->length);
    SHA1_Final (digest, &m);
	
    if (memcmp(digest, sig->data, SHA_DIGEST_LENGTH) != 0) {
	hx509_set_error_string(context, 0, HX509_CRYPTO_BAD_SIGNATURE,
			       "Bad SHA1 sigature");
	return HX509_CRYPTO_BAD_SIGNATURE;
    }

    return 0;
}

static int
sha256_create_signature(hx509_context context,
			const struct signature_alg *sig_alg,
			const hx509_private_key signer,
			const AlgorithmIdentifier *alg,
			const heim_octet_string *data,
			AlgorithmIdentifier *signatureAlgorithm,
			heim_octet_string *sig)
{
    SHA256_CTX m;
    
    memset(sig, 0, sizeof(*sig));

    if (signatureAlgorithm) {
	int ret;
	ret = set_digest_alg(signatureAlgorithm, (*sig_alg->sig_oid)(),
			     "\x05\x00", 2);
	if (ret)
	    return ret;
    }
	    

    sig->data = malloc(SHA256_DIGEST_LENGTH);
    if (sig->data == NULL) {
	sig->length = 0;
	return ENOMEM;
    }
    sig->length = SHA256_DIGEST_LENGTH;

    SHA256_Init(&m);
    SHA256_Update(&m, data->data, data->length);
    SHA256_Final (sig->data, &m);

    return 0;
}

static int
sha256_verify_signature(hx509_context context,
			const struct signature_alg *sig_alg,
			const Certificate *signer,
			const AlgorithmIdentifier *alg,
			const heim_octet_string *data,
			const heim_octet_string *sig)
{
    unsigned char digest[SHA256_DIGEST_LENGTH];
    SHA256_CTX m;
    
    if (sig->length != SHA256_DIGEST_LENGTH) {
	hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT,
			       "SHA256 sigature have wrong length");
	return HX509_CRYPTO_SIG_INVALID_FORMAT;
    }

    SHA256_Init(&m);
    SHA256_Update(&m, data->data, data->length);
    SHA256_Final (digest, &m);
	
    if (memcmp(digest, sig->data, SHA256_DIGEST_LENGTH) != 0) {
	hx509_set_error_string(context, 0, HX509_CRYPTO_BAD_SIGNATURE,
			       "Bad SHA256 sigature");
	return HX509_CRYPTO_BAD_SIGNATURE;
    }

    return 0;
}

static int
sha1_create_signature(hx509_context context,
		      const struct signature_alg *sig_alg,
		      const hx509_private_key signer,
		      const AlgorithmIdentifier *alg,
		      const heim_octet_string *data,
		      AlgorithmIdentifier *signatureAlgorithm,
		      heim_octet_string *sig)
{
    SHA_CTX m;
    
    memset(sig, 0, sizeof(*sig));

    if (signatureAlgorithm) {
	int ret;
	ret = set_digest_alg(signatureAlgorithm, (*sig_alg->sig_oid)(), 
			     "\x05\x00", 2);
	if (ret)
	    return ret;
    }
	    

    sig->data = malloc(SHA_DIGEST_LENGTH);
    if (sig->data == NULL) {
	sig->length = 0;
	return ENOMEM;
    }
    sig->length = SHA_DIGEST_LENGTH;

    SHA1_Init(&m);
    SHA1_Update(&m, data->data, data->length);
    SHA1_Final (sig->data, &m);

    return 0;
}

static int
md5_verify_signature(hx509_context context,
		     const struct signature_alg *sig_alg,
		     const Certificate *signer,
		     const AlgorithmIdentifier *alg,
		     const heim_octet_string *data,
		     const heim_octet_string *sig)
{
    unsigned char digest[MD5_DIGEST_LENGTH];
    MD5_CTX m;
    
    if (sig->length != MD5_DIGEST_LENGTH) {
	hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT,
			       "MD5 sigature have wrong length");
	return HX509_CRYPTO_SIG_INVALID_FORMAT;
    }

    MD5_Init(&m);
    MD5_Update(&m, data->data, data->length);
    MD5_Final (digest, &m);
	
    if (memcmp(digest, sig->data, MD5_DIGEST_LENGTH) != 0) {
	hx509_set_error_string(context, 0, HX509_CRYPTO_BAD_SIGNATURE,
			       "Bad MD5 sigature");
	return HX509_CRYPTO_BAD_SIGNATURE;
    }

    return 0;
}

static int
md2_verify_signature(hx509_context context,
		     const struct signature_alg *sig_alg,
		     const Certificate *signer,
		     const AlgorithmIdentifier *alg,
		     const heim_octet_string *data,
		     const heim_octet_string *sig)
{
    unsigned char digest[MD2_DIGEST_LENGTH];
    MD2_CTX m;
    
    if (sig->length != MD2_DIGEST_LENGTH) {
	hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT,
			       "MD2 sigature have wrong length");
	return HX509_CRYPTO_SIG_INVALID_FORMAT;
    }

    MD2_Init(&m);
    MD2_Update(&m, data->data, data->length);
    MD2_Final (digest, &m);
	
    if (memcmp(digest, sig->data, MD2_DIGEST_LENGTH) != 0) {
	hx509_set_error_string(context, 0, HX509_CRYPTO_BAD_SIGNATURE,
			       "Bad MD2 sigature");
	return HX509_CRYPTO_BAD_SIGNATURE;
    }

    return 0;
}

static const struct signature_alg pkcs1_rsa_sha1_alg = {
    "rsa",
    oid_id_pkcs1_rsaEncryption,
    hx509_signature_rsa_with_sha1,
    oid_id_pkcs1_rsaEncryption,
    NULL,
    PROVIDE_CONF|REQUIRE_SIGNER|SIG_PUBLIC_SIG,
    rsa_verify_signature,
    rsa_create_signature
};

static const struct signature_alg rsa_with_sha256_alg = {
    "rsa-with-sha256",
    oid_id_pkcs1_sha256WithRSAEncryption,
    hx509_signature_rsa_with_sha256,
    oid_id_pkcs1_rsaEncryption,
    oid_id_sha256,
    PROVIDE_CONF|REQUIRE_SIGNER|SIG_PUBLIC_SIG,
    rsa_verify_signature,
    rsa_create_signature
};

static const struct signature_alg rsa_with_sha1_alg = {
    "rsa-with-sha1",
    oid_id_pkcs1_sha1WithRSAEncryption,
    hx509_signature_rsa_with_sha1,
    oid_id_pkcs1_rsaEncryption,
    oid_id_secsig_sha_1,
    PROVIDE_CONF|REQUIRE_SIGNER|SIG_PUBLIC_SIG,
    rsa_verify_signature,
    rsa_create_signature
};

static const struct signature_alg rsa_with_md5_alg = {
    "rsa-with-md5",
    oid_id_pkcs1_md5WithRSAEncryption,
    hx509_signature_rsa_with_md5,
    oid_id_pkcs1_rsaEncryption,
    oid_id_rsa_digest_md5,
    PROVIDE_CONF|REQUIRE_SIGNER|SIG_PUBLIC_SIG,
    rsa_verify_signature,
    rsa_create_signature
};

static const struct signature_alg rsa_with_md2_alg = {
    "rsa-with-md2",
    oid_id_pkcs1_md2WithRSAEncryption,
    hx509_signature_rsa_with_md2,
    oid_id_pkcs1_rsaEncryption,
    oid_id_rsa_digest_md2,
    PROVIDE_CONF|REQUIRE_SIGNER|SIG_PUBLIC_SIG,
    rsa_verify_signature,
    rsa_create_signature
};

static const struct signature_alg dsa_sha1_alg = {
    "dsa-with-sha1",
    oid_id_dsa_with_sha1,
    NULL,
    oid_id_dsa, 
    oid_id_secsig_sha_1,
    PROVIDE_CONF|REQUIRE_SIGNER|SIG_PUBLIC_SIG,
    dsa_verify_signature,
    /* create_signature */ NULL,
};

static const struct signature_alg sha256_alg = {
    "sha-256",
    oid_id_sha256,
    hx509_signature_sha256,
    NULL,
    NULL,
    SIG_DIGEST,
    sha256_verify_signature,
    sha256_create_signature
};

static const struct signature_alg sha1_alg = {
    "sha1",
    oid_id_secsig_sha_1,
    hx509_signature_sha1,
    NULL,
    NULL,
    SIG_DIGEST,
    sha1_verify_signature,
    sha1_create_signature
};

static const struct signature_alg md5_alg = {
    "rsa-md5",
    oid_id_rsa_digest_md5,
    hx509_signature_md5,
    NULL,
    NULL,
    SIG_DIGEST,
    md5_verify_signature
};

static const struct signature_alg md2_alg = {
    "rsa-md2",
    oid_id_rsa_digest_md2,
    hx509_signature_md2,
    NULL,
    NULL,
    SIG_DIGEST,
    md2_verify_signature
};

/* 
 * Order matter in this structure, "best" first for each "key
 * compatible" type (type is RSA, DSA, none, etc)
 */

static const struct signature_alg *sig_algs[] = {
    &rsa_with_sha256_alg,
    &rsa_with_sha1_alg,
    &pkcs1_rsa_sha1_alg,
    &rsa_with_md5_alg,
    &rsa_with_md2_alg,
    &pkcs1_rsa_sha1_alg,
    &dsa_sha1_alg,
    &sha256_alg,
    &sha1_alg,
    &md5_alg,
    &md2_alg,
    NULL
};

static const struct signature_alg *
find_sig_alg(const heim_oid *oid)
{
    int i;
    for (i = 0; sig_algs[i]; i++)
	if (der_heim_oid_cmp((*sig_algs[i]->sig_oid)(), oid) == 0)
	    return sig_algs[i];
    return NULL;
}

/*
 *
 */

static struct hx509_private_key_ops *private_algs[] = {
    &rsa_private_key_ops,
    NULL
};

static hx509_private_key_ops *
find_private_alg(const heim_oid *oid)
{
    int i;
    for (i = 0; private_algs[i]; i++) {
	if (private_algs[i]->key_oid == NULL)
	    continue;
	if (der_heim_oid_cmp((*private_algs[i]->key_oid)(), oid) == 0)
	    return private_algs[i];
    }
    return NULL;
}


int
_hx509_verify_signature(hx509_context context,
			const Certificate *signer,
			const AlgorithmIdentifier *alg,
			const heim_octet_string *data,
			const heim_octet_string *sig)
{
    const struct signature_alg *md;

    md = find_sig_alg(&alg->algorithm);
    if (md == NULL) {
	hx509_clear_error_string(context);
	return HX509_SIG_ALG_NO_SUPPORTED;
    }
    if (signer && (md->flags & PROVIDE_CONF) == 0) {
	hx509_clear_error_string(context);
	return HX509_CRYPTO_SIG_NO_CONF;
    }
    if (signer == NULL && (md->flags & REQUIRE_SIGNER)) {
	    hx509_clear_error_string(context);
	return HX509_CRYPTO_SIGNATURE_WITHOUT_SIGNER;
    }
    if (md->key_oid && signer) {
	const SubjectPublicKeyInfo *spi;
	spi = &signer->tbsCertificate.subjectPublicKeyInfo;

	if (der_heim_oid_cmp(&spi->algorithm.algorithm, (*md->key_oid)()) != 0) {
	    hx509_clear_error_string(context);
	    return HX509_SIG_ALG_DONT_MATCH_KEY_ALG;
	}
    }
    return (*md->verify_signature)(context, md, signer, alg, data, sig);
}

int
_hx509_verify_signature_bitstring(hx509_context context,
				  const Certificate *signer,
				  const AlgorithmIdentifier *alg,
				  const heim_octet_string *data,
				  const heim_bit_string *sig)
{
    heim_octet_string os;

    if (sig->length & 7) {
	hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT,
			       "signature not multiple of 8 bits");
	return HX509_CRYPTO_SIG_INVALID_FORMAT;
    }

    os.data = sig->data;
    os.length = sig->length / 8;
    
    return _hx509_verify_signature(context, signer, alg, data, &os);
}

int
_hx509_create_signature(hx509_context context,
			const hx509_private_key signer,
			const AlgorithmIdentifier *alg,
			const heim_octet_string *data,
			AlgorithmIdentifier *signatureAlgorithm,
			heim_octet_string *sig)
{
    const struct signature_alg *md;

    if (signer && signer->ops && signer->ops->handle_alg &&
	(*signer->ops->handle_alg)(signer, alg, COT_SIGN))
    {
	return (*signer->ops->sign)(context, signer, alg, data, 
				    signatureAlgorithm, sig);
    }

    md = find_sig_alg(&alg->algorithm);
    if (md == NULL) {
	hx509_set_error_string(context, 0, HX509_SIG_ALG_NO_SUPPORTED,
	    "algorithm no supported");
	return HX509_SIG_ALG_NO_SUPPORTED;
    }

    if (signer && (md->flags & PROVIDE_CONF) == 0) {
	hx509_set_error_string(context, 0, HX509_SIG_ALG_NO_SUPPORTED,
	    "algorithm provides no conf");
	return HX509_CRYPTO_SIG_NO_CONF;
    }

    return (*md->create_signature)(context, md, signer, alg, data, 
				   signatureAlgorithm, sig);
}

int
_hx509_create_signature_bitstring(hx509_context context,
				  const hx509_private_key signer,
				  const AlgorithmIdentifier *alg,
				  const heim_octet_string *data,
				  AlgorithmIdentifier *signatureAlgorithm,
				  heim_bit_string *sig)
{
    heim_octet_string os;
    int ret;

    ret = _hx509_create_signature(context, signer, alg,
				  data, signatureAlgorithm, &os);
    if (ret)
	return ret;
    sig->data = os.data;
    sig->length = os.length * 8;
    return 0;
}

int
_hx509_public_encrypt(hx509_context context,
		      const heim_octet_string *cleartext,
		      const Certificate *cert,
		      heim_oid *encryption_oid,
		      heim_octet_string *ciphertext)
{
    const SubjectPublicKeyInfo *spi;
    unsigned char *to;
    int tosize;
    int ret;
    RSA *rsa;
    RSAPublicKey pk;
    size_t size;

    ciphertext->data = NULL;
    ciphertext->length = 0;

    spi = &cert->tbsCertificate.subjectPublicKeyInfo;

    rsa = RSA_new();
    if (rsa == NULL) {
	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
	return ENOMEM;
    }

    ret = decode_RSAPublicKey(spi->subjectPublicKey.data,
			      spi->subjectPublicKey.length / 8,
			      &pk, &size);
    if (ret) {
	RSA_free(rsa);
	hx509_set_error_string(context, 0, ret, "RSAPublicKey decode failure");
	return ret;
    }
    rsa->n = heim_int2BN(&pk.modulus);
    rsa->e = heim_int2BN(&pk.publicExponent);

    free_RSAPublicKey(&pk);

    if (rsa->n == NULL || rsa->e == NULL) {
	RSA_free(rsa);
	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
	return ENOMEM;
    }

    tosize = RSA_size(rsa);
    to = malloc(tosize);
    if (to == NULL) {
	RSA_free(rsa);
	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
	return ENOMEM;
    }

    ret = RSA_public_encrypt(cleartext->length, 
			     (unsigned char *)cleartext->data, 
			     to, rsa, RSA_PKCS1_PADDING);
    RSA_free(rsa);
    if (ret <= 0) {
	free(to);
	hx509_set_error_string(context, 0, HX509_CRYPTO_RSA_PUBLIC_ENCRYPT,
			       "RSA public encrypt failed with %d", ret);
	return HX509_CRYPTO_RSA_PUBLIC_ENCRYPT;
    }
    if (ret > tosize)
	_hx509_abort("internal rsa decryption failure: ret > tosize");

    ciphertext->length = ret;
    ciphertext->data = to;

    ret = der_copy_oid(oid_id_pkcs1_rsaEncryption(), encryption_oid);
    if (ret) {
	der_free_octet_string(ciphertext);
	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
	return ENOMEM;
    }

    return 0;
}

int
_hx509_private_key_private_decrypt(hx509_context context,
				   const heim_octet_string *ciphertext,
				   const heim_oid *encryption_oid,
				   hx509_private_key p,
				   heim_octet_string *cleartext)
{
    int ret;

    cleartext->data = NULL;
    cleartext->length = 0;

    if (p->private_key.rsa == NULL) {
	hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING,
			       "Private RSA key missing");
	return HX509_PRIVATE_KEY_MISSING;
    }

    cleartext->length = RSA_size(p->private_key.rsa);
    cleartext->data = malloc(cleartext->length);
    if (cleartext->data == NULL) {
	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
	return ENOMEM;
    }
    ret = RSA_private_decrypt(ciphertext->length, ciphertext->data,
			      cleartext->data,
			      p->private_key.rsa,
			      RSA_PKCS1_PADDING);
    if (ret <= 0) {
	der_free_octet_string(cleartext);
	hx509_set_error_string(context, 0, HX509_CRYPTO_RSA_PRIVATE_DECRYPT,
			       "Failed to decrypt using private key: %d", ret);
	return HX509_CRYPTO_RSA_PRIVATE_DECRYPT;
    }
    if (cleartext->length < ret)
	_hx509_abort("internal rsa decryption failure: ret > tosize");

    cleartext->length = ret;

    return 0;
}


int
_hx509_parse_private_key(hx509_context context,
			 const heim_oid *key_oid,
			 const void *data,
			 size_t len,
			 hx509_private_key *private_key)
{
    struct hx509_private_key_ops *ops;
    int ret;

    *private_key = NULL;

    ops = find_private_alg(key_oid);
    if (ops == NULL) {
	hx509_clear_error_string(context);
	return HX509_SIG_ALG_NO_SUPPORTED;
    }

    ret = _hx509_private_key_init(private_key, ops, NULL);
    if (ret) {
	hx509_set_error_string(context, 0, ret, "out of memory");
	return ret;
    }

    ret = (*ops->import)(context, data, len, *private_key);
    if (ret)
	_hx509_private_key_free(private_key);

    return ret;
}

/*
 *
 */

int
_hx509_private_key2SPKI(hx509_context context,
			hx509_private_key private_key,
			SubjectPublicKeyInfo *spki)
{
    const struct hx509_private_key_ops *ops = private_key->ops;
    if (ops == NULL || ops->get_spki == NULL) {
	hx509_set_error_string(context, 0, HX509_UNIMPLEMENTED_OPERATION,
			       "Private key have no key2SPKI function");
	return HX509_UNIMPLEMENTED_OPERATION;
    }
    return (*ops->get_spki)(context, private_key, spki);
}

int
_hx509_generate_private_key_init(hx509_context context,
				 const heim_oid *oid,
				 struct hx509_generate_private_context **ctx)
{
    *ctx = NULL;

    if (der_heim_oid_cmp(oid, oid_id_pkcs1_rsaEncryption()) != 0) {
	hx509_set_error_string(context, 0, EINVAL, 
			       "private key not an RSA key");
	return EINVAL;
    }

    *ctx = calloc(1, sizeof(**ctx));
    if (*ctx == NULL) {
	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
	return ENOMEM;
    }
    (*ctx)->key_oid = oid;

    return 0;
}

int
_hx509_generate_private_key_is_ca(hx509_context context,
				  struct hx509_generate_private_context *ctx)
{
    ctx->isCA = 1;
    return 0;
}

int
_hx509_generate_private_key_bits(hx509_context context,
				 struct hx509_generate_private_context *ctx,
				 unsigned long bits)
{
    ctx->num_bits = bits;
    return 0;
}


void
_hx509_generate_private_key_free(struct hx509_generate_private_context **ctx)
{
    free(*ctx);
    *ctx = NULL;
}

int
_hx509_generate_private_key(hx509_context context,
			    struct hx509_generate_private_context *ctx,
			    hx509_private_key *private_key)
{
    struct hx509_private_key_ops *ops;
    int ret;

    *private_key = NULL;

    ops = find_private_alg(ctx->key_oid);
    if (ops == NULL) {
	hx509_clear_error_string(context);
	return HX509_SIG_ALG_NO_SUPPORTED;
    }

    ret = _hx509_private_key_init(private_key, ops, NULL);
    if (ret) {
	hx509_set_error_string(context, 0, ret, "out of memory");
	return ret;
    }

    ret = (*ops->generate_private_key)(context, ctx, *private_key);
    if (ret)
	_hx509_private_key_free(private_key);

    return ret;
}


/*
 *
 */

static const heim_octet_string null_entry_oid = { 2, rk_UNCONST("\x05\x00") };

static const unsigned sha512_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 3 };
const AlgorithmIdentifier _hx509_signature_sha512_data = { 
    { 9, rk_UNCONST(sha512_oid_tree) }, rk_UNCONST(&null_entry_oid)
};

static const unsigned sha384_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 2 };
const AlgorithmIdentifier _hx509_signature_sha384_data = { 
    { 9, rk_UNCONST(sha384_oid_tree) }, rk_UNCONST(&null_entry_oid)
};

static const unsigned sha256_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 1 };
const AlgorithmIdentifier _hx509_signature_sha256_data = { 
    { 9, rk_UNCONST(sha256_oid_tree) }, rk_UNCONST(&null_entry_oid)
};

static const unsigned sha1_oid_tree[] = { 1, 3, 14, 3, 2, 26 };
const AlgorithmIdentifier _hx509_signature_sha1_data = { 
    { 6, rk_UNCONST(sha1_oid_tree) }, rk_UNCONST(&null_entry_oid)
};

static const unsigned md5_oid_tree[] = { 1, 2, 840, 113549, 2, 5 };
const AlgorithmIdentifier _hx509_signature_md5_data = { 
    { 6, rk_UNCONST(md5_oid_tree) }, rk_UNCONST(&null_entry_oid)
};

static const unsigned md2_oid_tree[] = { 1, 2, 840, 113549, 2, 2 };
const AlgorithmIdentifier _hx509_signature_md2_data = { 
    { 6, rk_UNCONST(md2_oid_tree) }, rk_UNCONST(&null_entry_oid)
};

static const unsigned rsa_with_sha512_oid[] ={ 1, 2, 840, 113549, 1, 1, 13 };
const AlgorithmIdentifier _hx509_signature_rsa_with_sha512_data = { 
    { 7, rk_UNCONST(rsa_with_sha512_oid) }, NULL
};

static const unsigned rsa_with_sha384_oid[] ={ 1, 2, 840, 113549, 1, 1, 12 };
const AlgorithmIdentifier _hx509_signature_rsa_with_sha384_data = { 
    { 7, rk_UNCONST(rsa_with_sha384_oid) }, NULL
};

static const unsigned rsa_with_sha256_oid[] ={ 1, 2, 840, 113549, 1, 1, 11 };
const AlgorithmIdentifier _hx509_signature_rsa_with_sha256_data = { 
    { 7, rk_UNCONST(rsa_with_sha256_oid) }, NULL
};

static const unsigned rsa_with_sha1_oid[] ={ 1, 2, 840, 113549, 1, 1, 5 };
const AlgorithmIdentifier _hx509_signature_rsa_with_sha1_data = { 
    { 7, rk_UNCONST(rsa_with_sha1_oid) }, NULL
};

static const unsigned rsa_with_md5_oid[] ={ 1, 2, 840, 113549, 1, 1, 4 };
const AlgorithmIdentifier _hx509_signature_rsa_with_md5_data = { 
    { 7, rk_UNCONST(rsa_with_md5_oid) }, NULL
};

static const unsigned rsa_with_md2_oid[] ={ 1, 2, 840, 113549, 1, 1, 2 };
const AlgorithmIdentifier _hx509_signature_rsa_with_md2_data = { 
    { 7, rk_UNCONST(rsa_with_md2_oid) }, NULL
};

static const unsigned rsa_oid[] ={ 1, 2, 840, 113549, 1, 1, 1 };
const AlgorithmIdentifier _hx509_signature_rsa_data = { 
    { 7, rk_UNCONST(rsa_oid) }, NULL
};

static const unsigned des_rsdi_ede3_cbc_oid[] ={ 1, 2, 840, 113549, 3, 7 };
const AlgorithmIdentifier _hx509_des_rsdi_ede3_cbc_oid = {
    { 6, rk_UNCONST(des_rsdi_ede3_cbc_oid) }, NULL
};

static const unsigned aes128_cbc_oid[] ={ 2, 16, 840, 1, 101, 3, 4, 1, 2 };
const AlgorithmIdentifier _hx509_crypto_aes128_cbc_data = {
    { 9, rk_UNCONST(aes128_cbc_oid) }, NULL
};

static const unsigned aes256_cbc_oid[] ={ 2, 16, 840, 1, 101, 3, 4, 1, 42 };
const AlgorithmIdentifier _hx509_crypto_aes256_cbc_data = {
    { 9, rk_UNCONST(aes256_cbc_oid) }, NULL
};

const AlgorithmIdentifier *
hx509_signature_sha512(void)
{ return &_hx509_signature_sha512_data; }

const AlgorithmIdentifier *
hx509_signature_sha384(void)
{ return &_hx509_signature_sha384_data; }

const AlgorithmIdentifier *
hx509_signature_sha256(void)
{ return &_hx509_signature_sha256_data; }

const AlgorithmIdentifier *
hx509_signature_sha1(void)
{ return &_hx509_signature_sha1_data; }

const AlgorithmIdentifier *
hx509_signature_md5(void)
{ return &_hx509_signature_md5_data; }

const AlgorithmIdentifier *
hx509_signature_md2(void)
{ return &_hx509_signature_md2_data; }

const AlgorithmIdentifier *
hx509_signature_rsa_with_sha512(void)
{ return &_hx509_signature_rsa_with_sha512_data; }

const AlgorithmIdentifier *
hx509_signature_rsa_with_sha384(void)
{ return &_hx509_signature_rsa_with_sha384_data; }

const AlgorithmIdentifier *
hx509_signature_rsa_with_sha256(void)
{ return &_hx509_signature_rsa_with_sha256_data; }

const AlgorithmIdentifier *
hx509_signature_rsa_with_sha1(void)
{ return &_hx509_signature_rsa_with_sha1_data; }

const AlgorithmIdentifier *
hx509_signature_rsa_with_md5(void)
{ return &_hx509_signature_rsa_with_md5_data; }

const AlgorithmIdentifier *
hx509_signature_rsa_with_md2(void)
{ return &_hx509_signature_rsa_with_md2_data; }

const AlgorithmIdentifier *
hx509_signature_rsa(void)
{ return &_hx509_signature_rsa_data; }

const AlgorithmIdentifier *
hx509_crypto_des_rsdi_ede3_cbc(void)
{ return &_hx509_des_rsdi_ede3_cbc_oid; }

const AlgorithmIdentifier *
hx509_crypto_aes128_cbc(void)
{ return &_hx509_crypto_aes128_cbc_data; }

const AlgorithmIdentifier *
hx509_crypto_aes256_cbc(void)
{ return &_hx509_crypto_aes256_cbc_data; }

/*
 *
 */

const AlgorithmIdentifier * _hx509_crypto_default_sig_alg = 
    &_hx509_signature_rsa_with_sha1_data;
const AlgorithmIdentifier * _hx509_crypto_default_digest_alg = 
    &_hx509_signature_sha1_data;
const AlgorithmIdentifier * _hx509_crypto_default_secret_alg = 
    &_hx509_crypto_aes128_cbc_data;

/*
 *
 */

int
_hx509_private_key_init(hx509_private_key *key,
			hx509_private_key_ops *ops,
			void *keydata)
{
    *key = calloc(1, sizeof(**key));
    if (*key == NULL)
	return ENOMEM;
    (*key)->ref = 1;
    (*key)->ops = ops;
    (*key)->private_key.keydata = keydata;
    return 0;
}

hx509_private_key
_hx509_private_key_ref(hx509_private_key key)
{
    if (key->ref <= 0)
	_hx509_abort("refcount <= 0");
    key->ref++;
    if (key->ref == 0)
	_hx509_abort("refcount == 0");
    return key;
}

const char *
_hx509_private_pem_name(hx509_private_key key)
{
    return key->ops->pemtype;
}

int
_hx509_private_key_free(hx509_private_key *key)
{
    if (key == NULL || *key == NULL)
	return 0;

    if ((*key)->ref <= 0)
	_hx509_abort("refcount <= 0");
    if (--(*key)->ref > 0)
	return 0;

    if ((*key)->private_key.rsa)
	RSA_free((*key)->private_key.rsa);
    (*key)->private_key.rsa = NULL;
    free(*key);
    *key = NULL;
    return 0;
}

void
_hx509_private_key_assign_rsa(hx509_private_key key, void *ptr)
{
    if (key->private_key.rsa)
	RSA_free(key->private_key.rsa);
    key->private_key.rsa = ptr;
    key->signature_alg = oid_id_pkcs1_sha1WithRSAEncryption();
    key->md = &pkcs1_rsa_sha1_alg;
}

int 
_hx509_private_key_oid(hx509_context context,
		       const hx509_private_key key,
		       heim_oid *data)
{
    int ret;
    ret = der_copy_oid((*key->ops->key_oid)(), data);
    if (ret)
	hx509_set_error_string(context, 0, ret, "malloc out of memory");
    return ret;
}

int
_hx509_private_key_exportable(hx509_private_key key)
{
    if (key->ops->export == NULL)
	return 0;
    return 1;
}

int 
_hx509_private_key_export(hx509_context context,
			  const hx509_private_key key,
			  heim_octet_string *data)
{
    if (key->ops->export == NULL) {
	hx509_clear_error_string(context);
	return HX509_UNIMPLEMENTED_OPERATION;
    }
    return (*key->ops->export)(context, key, data);
}

/*
 *
 */

struct hx509cipher {
    const char *name;
    const heim_oid *(*oid_func)(void);
    const AlgorithmIdentifier *(*ai_func)(void);
    const EVP_CIPHER *(*evp_func)(void);
    int (*get_params)(hx509_context, const hx509_crypto,
		      const heim_octet_string *, heim_octet_string *);
    int (*set_params)(hx509_context, const heim_octet_string *, 
		      hx509_crypto, heim_octet_string *);
};

struct hx509_crypto_data {
    char *name;
    const struct hx509cipher *cipher;
    const EVP_CIPHER *c;
    heim_octet_string key;
    heim_oid oid;
    void *param;
};

/*
 *
 */

static const heim_oid *
oid_private_rc2_40(void)
{
    static unsigned oid_data[] = { 127, 1 };
    static const heim_oid oid = { 2, oid_data };

    return &oid;
}


/*
 *
 */

static int
CMSCBCParam_get(hx509_context context, const hx509_crypto crypto,
		 const heim_octet_string *ivec, heim_octet_string *param)
{
    size_t size;
    int ret;

    assert(crypto->param == NULL);
    if (ivec == NULL)
	return 0;

    ASN1_MALLOC_ENCODE(CMSCBCParameter, param->data, param->length,
		       ivec, &size, ret);
    if (ret == 0 && size != param->length)
	_hx509_abort("Internal asn1 encoder failure");
    if (ret)
	hx509_clear_error_string(context);
    return ret;
}

static int
CMSCBCParam_set(hx509_context context, const heim_octet_string *param,
		hx509_crypto crypto, heim_octet_string *ivec)
{
    int ret;
    if (ivec == NULL)
	return 0;

    ret = decode_CMSCBCParameter(param->data, param->length, ivec, NULL);
    if (ret)
	hx509_clear_error_string(context);

    return ret;
}

struct _RC2_params {
    int maximum_effective_key;
};

static int
CMSRC2CBCParam_get(hx509_context context, const hx509_crypto crypto,
		   const heim_octet_string *ivec, heim_octet_string *param)
{
    CMSRC2CBCParameter rc2params;
    const struct _RC2_params *p = crypto->param;
    int maximum_effective_key = 128;
    size_t size;
    int ret;

    memset(&rc2params, 0, sizeof(rc2params));

    if (p)
	maximum_effective_key = p->maximum_effective_key;

    switch(maximum_effective_key) {
    case 40:
	rc2params.rc2ParameterVersion = 160;
	break;
    case 64:
	rc2params.rc2ParameterVersion = 120;
	break;
    case 128:
	rc2params.rc2ParameterVersion = 58;
	break;
    }
    rc2params.iv = *ivec;

    ASN1_MALLOC_ENCODE(CMSRC2CBCParameter, param->data, param->length,
		       &rc2params, &size, ret);
    if (ret == 0 && size != param->length)
	_hx509_abort("Internal asn1 encoder failure");

    return ret;
}

static int
CMSRC2CBCParam_set(hx509_context context, const heim_octet_string *param,
		   hx509_crypto crypto, heim_octet_string *ivec)
{
    CMSRC2CBCParameter rc2param;
    struct _RC2_params *p;
    size_t size;
    int ret;

    ret = decode_CMSRC2CBCParameter(param->data, param->length,
				    &rc2param, &size);
    if (ret) {
	hx509_clear_error_string(context);
	return ret;
    }

    p = calloc(1, sizeof(*p));
    if (p == NULL) {
	free_CMSRC2CBCParameter(&rc2param);
	hx509_clear_error_string(context);
	return ENOMEM;
    }
    switch(rc2param.rc2ParameterVersion) {
    case 160:
	crypto->c = EVP_rc2_40_cbc();
	p->maximum_effective_key = 40;
	break;
    case 120:
	crypto->c = EVP_rc2_64_cbc();
	p->maximum_effective_key = 64;
	break;
    case 58:
	crypto->c = EVP_rc2_cbc();
	p->maximum_effective_key = 128;
	break;
    default:
	free_CMSRC2CBCParameter(&rc2param);
	return HX509_CRYPTO_SIG_INVALID_FORMAT;
    }
    if (ivec)
	ret = der_copy_octet_string(&rc2param.iv, ivec);
    free_CMSRC2CBCParameter(&rc2param);
    if (ret)
	hx509_clear_error_string(context);
    else
	crypto->param = p;

    return ret;
}

/*
 *
 */

static const struct hx509cipher ciphers[] = {
    {
	"rc2-cbc",
	oid_id_pkcs3_rc2_cbc,
	NULL,
	EVP_rc2_cbc,
	CMSRC2CBCParam_get,
	CMSRC2CBCParam_set
    },
    {
	"rc2-cbc",
	oid_id_rsadsi_rc2_cbc,
	NULL,
	EVP_rc2_cbc,
	CMSRC2CBCParam_get,
	CMSRC2CBCParam_set
    },
    {
	"rc2-40-cbc",
	oid_private_rc2_40,
	NULL,
	EVP_rc2_40_cbc,
	CMSRC2CBCParam_get,
	CMSRC2CBCParam_set
    },
    {
	"des-ede3-cbc",
	oid_id_pkcs3_des_ede3_cbc,
	NULL,
	EVP_des_ede3_cbc,
	CMSCBCParam_get,
	CMSCBCParam_set
    },
    {
	"des-ede3-cbc",
	oid_id_rsadsi_des_ede3_cbc,
	hx509_crypto_des_rsdi_ede3_cbc,
	EVP_des_ede3_cbc,
	CMSCBCParam_get,
	CMSCBCParam_set
    },
    {
	"aes-128-cbc",
	oid_id_aes_128_cbc,
	hx509_crypto_aes128_cbc,
	EVP_aes_128_cbc,
	CMSCBCParam_get,
	CMSCBCParam_set
    },
    {
	"aes-192-cbc",
	oid_id_aes_192_cbc,
	NULL,
	EVP_aes_192_cbc,
	CMSCBCParam_get,
	CMSCBCParam_set
    },
    {
	"aes-256-cbc",
	oid_id_aes_256_cbc,
	hx509_crypto_aes256_cbc,
	EVP_aes_256_cbc,
	CMSCBCParam_get,
	CMSCBCParam_set
    }
};

static const struct hx509cipher *
find_cipher_by_oid(const heim_oid *oid)
{
    int i;

    for (i = 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++)
	if (der_heim_oid_cmp(oid, (*ciphers[i].oid_func)()) == 0)
	    return &ciphers[i];

    return NULL;
}

static const struct hx509cipher *
find_cipher_by_name(const char *name)
{
    int i;

    for (i = 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++)
	if (strcasecmp(name, ciphers[i].name) == 0)
	    return &ciphers[i];

    return NULL;
}


const heim_oid *
hx509_crypto_enctype_by_name(const char *name)
{
    const struct hx509cipher *cipher;

    cipher = find_cipher_by_name(name);
    if (cipher == NULL)
	return NULL;
    return (*cipher->oid_func)();
}

int
hx509_crypto_init(hx509_context context,
		  const char *provider,
		  const heim_oid *enctype,
		  hx509_crypto *crypto)
{
    const struct hx509cipher *cipher;

    *crypto = NULL;

    cipher = find_cipher_by_oid(enctype);
    if (cipher == NULL) {
	hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
			       "Algorithm not supported");
	return HX509_ALG_NOT_SUPP;
    }

    *crypto = calloc(1, sizeof(**crypto));
    if (*crypto == NULL) {
	hx509_clear_error_string(context);
	return ENOMEM;
    }

    (*crypto)->cipher = cipher;
    (*crypto)->c = (*cipher->evp_func)();

    if (der_copy_oid(enctype, &(*crypto)->oid)) {
	hx509_crypto_destroy(*crypto);
	*crypto = NULL;
	hx509_clear_error_string(context);
	return ENOMEM;
    }

    return 0;
}

const char *
hx509_crypto_provider(hx509_crypto crypto)
{
    return "unknown";
}

void
hx509_crypto_destroy(hx509_crypto crypto)
{
    if (crypto->name)
	free(crypto->name);
    if (crypto->key.data)
	free(crypto->key.data);
    if (crypto->param)
	free(crypto->param);
    der_free_oid(&crypto->oid);
    memset(crypto, 0, sizeof(*crypto));
    free(crypto);
}

int
hx509_crypto_set_key_name(hx509_crypto crypto, const char *name)
{
    return 0;
}

int
hx509_crypto_set_key_data(hx509_crypto crypto, const void *data, size_t length)
{
    if (EVP_CIPHER_key_length(crypto->c) > length)
	return HX509_CRYPTO_INTERNAL_ERROR;

    if (crypto->key.data) {
	free(crypto->key.data);
	crypto->key.data = NULL;
	crypto->key.length = 0;
    }
    crypto->key.data = malloc(length);
    if (crypto->key.data == NULL)
	return ENOMEM;
    memcpy(crypto->key.data, data, length);
    crypto->key.length = length;

    return 0;
}

int
hx509_crypto_set_random_key(hx509_crypto crypto, heim_octet_string *key)
{
    if (crypto->key.data) {
	free(crypto->key.data);
	crypto->key.length = 0;
    }

    crypto->key.length = EVP_CIPHER_key_length(crypto->c);
    crypto->key.data = malloc(crypto->key.length);
    if (crypto->key.data == NULL) {
	crypto->key.length = 0;
	return ENOMEM;
    }
    if (RAND_bytes(crypto->key.data, crypto->key.length) <= 0) {
	free(crypto->key.data);
	crypto->key.data = NULL;
	crypto->key.length = 0;
	return HX509_CRYPTO_INTERNAL_ERROR;
    }
    if (key)
	return der_copy_octet_string(&crypto->key, key);
    else
	return 0;
}

int
hx509_crypto_set_params(hx509_context context,
			hx509_crypto crypto, 
			const heim_octet_string *param,
			heim_octet_string *ivec)
{
    return (*crypto->cipher->set_params)(context, param, crypto, ivec);
}

int
hx509_crypto_get_params(hx509_context context,
			hx509_crypto crypto, 
			const heim_octet_string *ivec,
			heim_octet_string *param)
{
    return (*crypto->cipher->get_params)(context, crypto, ivec, param);
}

int
hx509_crypto_encrypt(hx509_crypto crypto,
		     const void *data,
		     const size_t length,
		     heim_octet_string *ivec,
		     heim_octet_string **ciphertext)
{
    EVP_CIPHER_CTX evp;
    size_t padsize;
    int ret;

    *ciphertext = NULL;

    EVP_CIPHER_CTX_init(&evp);

    ivec->length = EVP_CIPHER_iv_length(crypto->c);
    ivec->data = malloc(ivec->length);
    if (ivec->data == NULL) {
	ret = ENOMEM;
	goto out;
    }

    if (RAND_bytes(ivec->data, ivec->length) <= 0) {
	ret = HX509_CRYPTO_INTERNAL_ERROR;
	goto out;
    }

    ret = EVP_CipherInit_ex(&evp, crypto->c, NULL,
			    crypto->key.data, ivec->data, 1);
    if (ret != 1) {
	EVP_CIPHER_CTX_cleanup(&evp);
	ret = HX509_CRYPTO_INTERNAL_ERROR;
	goto out;
    }

    *ciphertext = calloc(1, sizeof(**ciphertext));
    if (*ciphertext == NULL) {
	ret = ENOMEM;
	goto out;
    }
    
    if (EVP_CIPHER_block_size(crypto->c) == 1) {
	padsize = 0;
    } else {
	int bsize = EVP_CIPHER_block_size(crypto->c);
	padsize = bsize - (length % bsize);
    }
    (*ciphertext)->length = length + padsize;
    (*ciphertext)->data = malloc(length + padsize);
    if ((*ciphertext)->data == NULL) {
	ret = ENOMEM;
	goto out;
    }
	
    memcpy((*ciphertext)->data, data, length);
    if (padsize) {
	int i;
	unsigned char *p = (*ciphertext)->data;
	p += length;
	for (i = 0; i < padsize; i++)
	    *p++ = padsize;
    }

    ret = EVP_Cipher(&evp, (*ciphertext)->data,
		     (*ciphertext)->data,
		     length + padsize);
    if (ret != 1) {
	ret = HX509_CRYPTO_INTERNAL_ERROR;
	goto out;
    }
    ret = 0;

 out:
    if (ret) {
	if (ivec->data) {
	    free(ivec->data);
	    memset(ivec, 0, sizeof(*ivec));
	}
	if (*ciphertext) {
	    if ((*ciphertext)->data) {
		free((*ciphertext)->data);
	    }
	    free(*ciphertext);
	    *ciphertext = NULL;
	}
    }
    EVP_CIPHER_CTX_cleanup(&evp);

    return ret;
}

int
hx509_crypto_decrypt(hx509_crypto crypto,
		     const void *data,
		     const size_t length,
		     heim_octet_string *ivec,
		     heim_octet_string *clear)
{
    EVP_CIPHER_CTX evp;
    void *idata = NULL;
    int ret;

    clear->data = NULL;
    clear->length = 0;

    if (ivec && EVP_CIPHER_iv_length(crypto->c) < ivec->length)
	return HX509_CRYPTO_INTERNAL_ERROR;

    if (crypto->key.data == NULL)
	return HX509_CRYPTO_INTERNAL_ERROR;

    if (ivec)
	idata = ivec->data;

    EVP_CIPHER_CTX_init(&evp);

    ret = EVP_CipherInit_ex(&evp, crypto->c, NULL,
			    crypto->key.data, idata, 0);
    if (ret != 1) {
	EVP_CIPHER_CTX_cleanup(&evp);
	return HX509_CRYPTO_INTERNAL_ERROR;
    }

    clear->length = length;
    clear->data = malloc(length);
    if (clear->data == NULL) {
	EVP_CIPHER_CTX_cleanup(&evp);
	clear->length = 0;
	return ENOMEM;
    }

    if (EVP_Cipher(&evp, clear->data, data, length) != 1) {
	return HX509_CRYPTO_INTERNAL_ERROR;
    }
    EVP_CIPHER_CTX_cleanup(&evp);

    if (EVP_CIPHER_block_size(crypto->c) > 1) {
	int padsize;
	unsigned char *p; 
	int j, bsize = EVP_CIPHER_block_size(crypto->c);

	if (clear->length < bsize) {
	    ret = HX509_CMS_PADDING_ERROR;
	    goto out;
	}

	p = clear->data;
	p += clear->length - 1;
	padsize = *p;
	if (padsize > bsize) {
	    ret = HX509_CMS_PADDING_ERROR;
	    goto out;
	}
	clear->length -= padsize;
	for (j = 0; j < padsize; j++) {
	    if (*p-- != padsize) {
		ret = HX509_CMS_PADDING_ERROR;
		goto out;
	    }
	}
    }

    return 0;

 out:
    if (clear->data)
	free(clear->data);
    clear->data = NULL;
    clear->length = 0;
    return ret;
}

typedef int (*PBE_string2key_func)(hx509_context,
				   const char *,
				   const heim_octet_string *,
				   hx509_crypto *, heim_octet_string *, 
				   heim_octet_string *,
				   const heim_oid *, const EVP_MD *);

static int
PBE_string2key(hx509_context context,
	       const char *password,
	       const heim_octet_string *parameters,
	       hx509_crypto *crypto, 
	       heim_octet_string *key, heim_octet_string *iv,
	       const heim_oid *enc_oid,
	       const EVP_MD *md)
{
    PKCS12_PBEParams p12params;
    int passwordlen;
    hx509_crypto c;
    int iter, saltlen, ret;
    unsigned char *salt;

    passwordlen = password ? strlen(password) : 0;

    if (parameters == NULL)
 	return HX509_ALG_NOT_SUPP;

    ret = decode_PKCS12_PBEParams(parameters->data,
				  parameters->length,
				  &p12params, NULL);
    if (ret)
	goto out;

    if (p12params.iterations)
	iter = *p12params.iterations;
    else
	iter = 1;
    salt = p12params.salt.data;
    saltlen = p12params.salt.length;

    if (!PKCS12_key_gen (password, passwordlen, salt, saltlen, 
			 PKCS12_KEY_ID, iter, key->length, key->data, md)) {
	ret = HX509_CRYPTO_INTERNAL_ERROR;
	goto out;
    }
    
    if (!PKCS12_key_gen (password, passwordlen, salt, saltlen, 
			 PKCS12_IV_ID, iter, iv->length, iv->data, md)) {
	ret = HX509_CRYPTO_INTERNAL_ERROR;
	goto out;
    }

    ret = hx509_crypto_init(context, NULL, enc_oid, &c);
    if (ret)
	goto out;

    ret = hx509_crypto_set_key_data(c, key->data, key->length);
    if (ret) {
	hx509_crypto_destroy(c);
	goto out;
    }

    *crypto = c;
out:
    free_PKCS12_PBEParams(&p12params);
    return ret;
}

static const heim_oid *
find_string2key(const heim_oid *oid, 
		const EVP_CIPHER **c, 
		const EVP_MD **md,
		PBE_string2key_func *s2k)
{
    if (der_heim_oid_cmp(oid, oid_id_pbewithSHAAnd40BitRC2_CBC()) == 0) {
	*c = EVP_rc2_40_cbc();
	*md = EVP_sha1();
	*s2k = PBE_string2key;
	return oid_private_rc2_40();
    } else if (der_heim_oid_cmp(oid, oid_id_pbeWithSHAAnd128BitRC2_CBC()) == 0) {
	*c = EVP_rc2_cbc();
	*md = EVP_sha1();
	*s2k = PBE_string2key;
	return oid_id_pkcs3_rc2_cbc();
#if 0
    } else if (der_heim_oid_cmp(oid, oid_id_pbeWithSHAAnd40BitRC4()) == 0) {
	*c = EVP_rc4_40();
	*md = EVP_sha1();
	*s2k = PBE_string2key;
	return NULL;
    } else if (der_heim_oid_cmp(oid, oid_id_pbeWithSHAAnd128BitRC4()) == 0) {
	*c = EVP_rc4();
	*md = EVP_sha1();
	*s2k = PBE_string2key;
	return oid_id_pkcs3_rc4();
#endif
    } else if (der_heim_oid_cmp(oid, oid_id_pbeWithSHAAnd3_KeyTripleDES_CBC()) == 0) {
	*c = EVP_des_ede3_cbc();
	*md = EVP_sha1();
	*s2k = PBE_string2key;
	return oid_id_pkcs3_des_ede3_cbc();
    }

    return NULL;
}


int
_hx509_pbe_decrypt(hx509_context context,
		   hx509_lock lock,
		   const AlgorithmIdentifier *ai,
		   const heim_octet_string *econtent,
		   heim_octet_string *content)
{
    const struct _hx509_password *pw;
    heim_octet_string key, iv;
    const heim_oid *enc_oid;
    const EVP_CIPHER *c;
    const EVP_MD *md;
    PBE_string2key_func s2k;
    int i, ret = 0;

    memset(&key, 0, sizeof(key));
    memset(&iv, 0, sizeof(iv));

    memset(content, 0, sizeof(*content));

    enc_oid = find_string2key(&ai->algorithm, &c, &md, &s2k);
    if (enc_oid == NULL) {
	hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
			       "String to key algorithm not supported");
	ret = HX509_ALG_NOT_SUPP;
	goto out;
    }

    key.length = EVP_CIPHER_key_length(c);
    key.data = malloc(key.length);
    if (key.data == NULL) {
	ret = ENOMEM;
	hx509_clear_error_string(context);
	goto out;
    }

    iv.length = EVP_CIPHER_iv_length(c);
    iv.data = malloc(iv.length);
    if (iv.data == NULL) {
	ret = ENOMEM;
	hx509_clear_error_string(context);
	goto out;
    }

    pw = _hx509_lock_get_passwords(lock);

    ret = HX509_CRYPTO_INTERNAL_ERROR;
    for (i = 0; i < pw->len + 1; i++) {
	hx509_crypto crypto;
	const char *password;

	if (i < pw->len)
	    password = pw->val[i];
	else if (i < pw->len + 1)
	    password = "";
	else
	    password = NULL;

	ret = (*s2k)(context, password, ai->parameters, &crypto, 
		     &key, &iv, enc_oid, md);
	if (ret)
	    goto out;

	ret = hx509_crypto_decrypt(crypto,
				   econtent->data,
				   econtent->length,
				   &iv,
				   content);
	hx509_crypto_destroy(crypto);
	if (ret == 0)
	    goto out;
				   
    }
out:
    if (key.data)
	der_free_octet_string(&key);
    if (iv.data)
	der_free_octet_string(&iv);
    return ret;
}

/*
 *
 */


int
_hx509_match_keys(hx509_cert c, hx509_private_key private_key)
{
    const Certificate *cert;
    const SubjectPublicKeyInfo *spi;
    RSAPublicKey pk;
    RSA *rsa;
    size_t size;
    int ret;

    if (private_key->private_key.rsa == NULL)
	return 0;

    rsa = private_key->private_key.rsa;
    if (rsa->d == NULL || rsa->p == NULL || rsa->q == NULL)
	return 0;

    cert = _hx509_get_cert(c);
    spi = &cert->tbsCertificate.subjectPublicKeyInfo;

    rsa = RSA_new();
    if (rsa == NULL)
	return 0;

    ret = decode_RSAPublicKey(spi->subjectPublicKey.data,
			      spi->subjectPublicKey.length / 8,
			      &pk, &size);
    if (ret) {
	RSA_free(rsa);
	return 0;
    }
    rsa->n = heim_int2BN(&pk.modulus);
    rsa->e = heim_int2BN(&pk.publicExponent);

    free_RSAPublicKey(&pk);

    rsa->d = BN_dup(private_key->private_key.rsa->d);
    rsa->p = BN_dup(private_key->private_key.rsa->p);
    rsa->q = BN_dup(private_key->private_key.rsa->q);
    rsa->dmp1 = BN_dup(private_key->private_key.rsa->dmp1);
    rsa->dmq1 = BN_dup(private_key->private_key.rsa->dmq1);
    rsa->iqmp = BN_dup(private_key->private_key.rsa->iqmp);

    if (rsa->n == NULL || rsa->e == NULL || 
	rsa->d == NULL || rsa->p == NULL|| rsa->q == NULL ||
	rsa->dmp1 == NULL || rsa->dmq1 == NULL) {
	RSA_free(rsa);
	return 0;
    }

    ret = RSA_check_key(rsa);
    RSA_free(rsa);

    return ret == 1;
}

static const heim_oid *
find_keytype(const hx509_private_key key)
{
    const struct signature_alg *md;

    if (key == NULL)
	return NULL;

    md = find_sig_alg(key->signature_alg);
    if (md == NULL)
	return NULL;
    return (*md->key_oid)();
}


int
hx509_crypto_select(const hx509_context context,
		    int type,
		    const hx509_private_key source,
		    hx509_peer_info peer,
		    AlgorithmIdentifier *selected)
{
    const AlgorithmIdentifier *def;
    size_t i, j;
    int ret, bits;

    memset(selected, 0, sizeof(*selected));

    if (type == HX509_SELECT_DIGEST) {
	bits = SIG_DIGEST;
	def = _hx509_crypto_default_digest_alg;
    } else if (type == HX509_SELECT_PUBLIC_SIG) {
	bits = SIG_PUBLIC_SIG;
	/* XXX depend on `source´ and `peer´ */
	def = _hx509_crypto_default_sig_alg;
    } else if (type == HX509_SELECT_SECRET_ENC) {
	bits = SIG_SECRET;
	def = _hx509_crypto_default_secret_alg;
    } else {
	hx509_set_error_string(context, 0, EINVAL, 
			       "Unknown type %d of selection", type);
	return EINVAL;
    }

    if (peer) {
	const heim_oid *keytype = NULL;

	keytype = find_keytype(source);

	for (i = 0; i < peer->len; i++) {
	    for (j = 0; sig_algs[j]; j++) {
		if ((sig_algs[j]->flags & bits) != bits)
		    continue;
		if (der_heim_oid_cmp((*sig_algs[j]->sig_oid)(), 
				     &peer->val[i].algorithm) != 0)
		    continue;
		if (keytype && sig_algs[j]->key_oid && 
		    der_heim_oid_cmp(keytype, (*sig_algs[j]->key_oid)()))
		    continue;

		/* found one, use that */
		ret = copy_AlgorithmIdentifier(&peer->val[i], selected);
		if (ret)
		    hx509_clear_error_string(context);
		return ret;
	    }
	    if (bits & SIG_SECRET) {
		const struct hx509cipher *cipher;

		cipher = find_cipher_by_oid(&peer->val[i].algorithm);
		if (cipher == NULL)
		    continue;
		if (cipher->ai_func == NULL)
		    continue;
		ret = copy_AlgorithmIdentifier(cipher->ai_func(), selected);
		if (ret)
		    hx509_clear_error_string(context);
		return ret;
	    }
	}
    }

    /* use default */
    ret = copy_AlgorithmIdentifier(def, selected);
    if (ret)
	hx509_clear_error_string(context);
    return ret;
}

int
hx509_crypto_available(hx509_context context,
		       int type,
		       hx509_cert source,
		       AlgorithmIdentifier **val,
		       unsigned int *plen)
{
    const heim_oid *keytype = NULL;
    unsigned int len, i;
    void *ptr;
    int bits, ret;

    *val = NULL;

    if (type == HX509_SELECT_ALL) {
	bits = SIG_DIGEST | SIG_PUBLIC_SIG | SIG_SECRET;
    } else if (type == HX509_SELECT_DIGEST) {
	bits = SIG_DIGEST;
    } else if (type == HX509_SELECT_PUBLIC_SIG) {
	bits = SIG_PUBLIC_SIG;
    } else {
	hx509_set_error_string(context, 0, EINVAL, 
			       "Unknown type %d of available", type);
	return EINVAL;
    }

    if (source)
	keytype = find_keytype(_hx509_cert_private_key(source));

    len = 0;
    for (i = 0; sig_algs[i]; i++) {
	if ((sig_algs[i]->flags & bits) == 0)
	    continue;
	if (sig_algs[i]->sig_alg == NULL)
	    continue;
	if (keytype && sig_algs[i]->key_oid && 
	    der_heim_oid_cmp((*sig_algs[i]->key_oid)(), keytype))
	    continue;

	/* found one, add that to the list */
	ptr = realloc(*val, sizeof(**val) * (len + 1));
	if (ptr == NULL)
	    goto out;
	*val = ptr;

	ret = copy_AlgorithmIdentifier((*sig_algs[i]->sig_alg)(), &(*val)[len]);
	if (ret)
	    goto out;
	len++;
    }

    /* Add AES */
    if (bits & SIG_SECRET) {

	for (i = 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++) {
	
	    if (ciphers[i].ai_func == NULL)
		continue;

	    ptr = realloc(*val, sizeof(**val) * (len + 1));
	    if (ptr == NULL)
		goto out;
	    *val = ptr;
	    
	    ret = copy_AlgorithmIdentifier((ciphers[i].ai_func)(), &(*val)[len]);
	    if (ret)
		goto out;
	    len++;
	}
    }

    *plen = len;
    return 0;

out:
    for (i = 0; i < len; i++)
	free_AlgorithmIdentifier(&(*val)[i]);
    free(*val);
    *val = NULL;
    hx509_set_error_string(context, 0, ENOMEM, "out of memory");
    return ENOMEM;
}

void
hx509_crypto_free_algs(AlgorithmIdentifier *val,
		       unsigned int len)
{
    unsigned int i;
    for (i = 0; i < len; i++)
	free_AlgorithmIdentifier(&val[i]);
    free(val);
}