summaryrefslogtreecommitdiffstats
path: root/contrib/pkcs11-keygen/openssl-0.9.8g-patch
blob: 6d93c687e3ecb507ca1bdaa6d4bd0714ad2d17a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
diff -r -u -N openssl-0.9.8g/Configure openssl/Configure
--- openssl-0.9.8g/Configure	2007-09-16 14:24:17.000000000 +0200
+++ openssl/Configure	2007-10-25 01:27:08.000000000 +0200
@@ -10,7 +10,7 @@
 
 # see INSTALL for instructions.
 
-my $usage="Usage: Configure [no-<cipher> ...] [enable-<cipher> ...] [-Dxxx] [-lxxx] [-Lxxx] [-fxxx] [-Kxxx] [no-hw-xxx|no-hw] [[no-]threads] [[no-]shared] [[no-]zlib|zlib-dynamic] [no-asm] [no-dso] [no-krb5] [386] [--prefix=DIR] [--openssldir=OPENSSLDIR] [--with-xxx[=vvv]] [--test-sanity] os/compiler[:flags]\n";
+my $usage="Usage: Configure  --pk11-libname=PK11_LIB_LOCATION [no-<cipher> ...] [enable-<cipher> ...] [-Dxxx] [-lxxx] [-Lxxx] [-fxxx] [-Kxxx] [no-hw-xxx|no-hw] [[no-]threads] [[no-]shared] [[no-]zlib|zlib-dynamic] [no-asm] [no-dso] [no-krb5] [386] [--prefix=DIR] [--openssldir=OPENSSLDIR] [--with-xxx[=vvv]] [--test-sanity] os/compiler[:flags]\n";
 
 # Options:
 #
@@ -19,6 +19,9 @@
 # --prefix      prefix for the OpenSSL include, lib and bin directories
 #               (Default: the OPENSSLDIR directory)
 #
+# --pk11_libname  PKCS#11 library name.
+#               (Default: none)
+#
 # --install_prefix  Additional prefix for package builders (empty by
 #               default).  This needn't be set in advance, you can
 #               just as well use "make INSTALL_PREFIX=/whatever install".
@@ -560,6 +563,8 @@
 my $idx_ranlib = $idx++;
 my $idx_arflags = $idx++;
 
+my $pk11_libname="";
+
 my $prefix="";
 my $openssldir="";
 my $exe_ext="";
@@ -738,6 +743,10 @@
 				{
 				$flags.=$_." ";
 				}
+                        elsif (/^--pk11-libname=(.*)$/)
+                                {
+                                $pk11_libname=$1;
+                                }
 			elsif (/^--prefix=(.*)$/)
 				{
 				$prefix=$1;
@@ -861,6 +870,13 @@
 	exit 0;
 }
 
+if (! $pk11_libname)
+        {
+        print STDERR "You must set --pk11-libname for PKCS#11 library.\n";
+        print STDERR "See README.pkcs11 for more information.\n";
+        exit 1;
+        }
+
 if ($target =~ m/^CygWin32(-.*)$/) {
 	$target = "Cygwin".$1;
 }
@@ -986,6 +1002,8 @@
 if ($flags ne "")	{ $cflags="$flags$cflags"; }
 else			{ $no_user_cflags=1;       }
 
+$cflags="-DPK11_LIB_LOCATION=\"$pk11_libname\" $cflags";
+
 # Kerberos settings.  The flavor must be provided from outside, either through
 # the script "config" or manually.
 if (!$no_krb5)
@@ -1319,6 +1337,7 @@
 	s/^VERSION=.*/VERSION=$version/;
 	s/^MAJOR=.*/MAJOR=$major/;
 	s/^MINOR=.*/MINOR=$minor/;
+	s/^PK11_LIB_LOCATION=.*/PK11_LIB_LOCATION=$pk11_libname/;
 	s/^SHLIB_VERSION_NUMBER=.*/SHLIB_VERSION_NUMBER=$shlib_version_number/;
 	s/^SHLIB_VERSION_HISTORY=.*/SHLIB_VERSION_HISTORY=$shlib_version_history/;
 	s/^SHLIB_MAJOR=.*/SHLIB_MAJOR=$shlib_major/;
diff -r -u -N openssl-0.9.8g/crypto/engine/cryptoki.h openssl/crypto/engine/cryptoki.h
--- openssl-0.9.8g/crypto/engine/cryptoki.h	1970-01-01 01:00:00.000000000 +0100
+++ openssl/crypto/engine/cryptoki.h	2007-10-25 01:27:09.000000000 +0200
@@ -0,0 +1,103 @@
+/*
+ * CDDL HEADER START
+ *
+ * The contents of this file are subject to the terms of the
+ * Common Development and Distribution License, Version 1.0 only
+ * (the "License").  You may not use this file except in compliance
+ * with the License.
+ *
+ * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+ * or http://www.opensolaris.org/os/licensing.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ *
+ * When distributing Covered Code, include this CDDL HEADER in each
+ * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+ * If applicable, add the following below this CDDL HEADER, with the
+ * fields enclosed by brackets "[]" replaced with your own identifying
+ * information: Portions Copyright [yyyy] [name of copyright owner]
+ *
+ * CDDL HEADER END
+ */
+/*
+ * Copyright 2003 Sun Microsystems, Inc.   All rights reserved.
+ * Use is subject to license terms.
+ */
+
+#ifndef	_CRYPTOKI_H
+#define	_CRYPTOKI_H
+
+#pragma ident	"@(#)cryptoki.h	1.2	05/06/08 SMI"
+
+#ifdef	__cplusplus
+extern "C" {
+#endif
+
+#ifndef	CK_PTR
+#define	CK_PTR *
+#endif
+
+#ifndef CK_DEFINE_FUNCTION
+#define	CK_DEFINE_FUNCTION(returnType, name) returnType name
+#endif
+
+#ifndef CK_DECLARE_FUNCTION
+#define	CK_DECLARE_FUNCTION(returnType, name) returnType name
+#endif
+
+#ifndef CK_DECLARE_FUNCTION_POINTER
+#define	CK_DECLARE_FUNCTION_POINTER(returnType, name) returnType (* name)
+#endif
+
+#ifndef CK_CALLBACK_FUNCTION
+#define	CK_CALLBACK_FUNCTION(returnType, name) returnType (* name)
+#endif
+
+#ifndef NULL_PTR
+#include <unistd.h>	/* For NULL */
+#define	NULL_PTR NULL
+#endif
+
+/*
+ * pkcs11t.h defines TRUE and FALSE in a way that upsets lint
+ */
+#ifndef	CK_DISABLE_TRUE_FALSE
+#define	CK_DISABLE_TRUE_FALSE
+#ifndef	TRUE
+#define	TRUE	1
+#endif /* TRUE */
+#ifndef	FALSE
+#define	FALSE	0
+#endif /* FALSE */
+#endif /* CK_DISABLE_TRUE_FALSE */
+
+#undef CK_PKCS11_FUNCTION_INFO
+
+#include "pkcs11.h"
+
+/* Solaris specific functions */
+
+#include <stdlib.h>
+
+/*
+ * SUNW_C_GetMechSession will initialize the framework and do all
+ * the necessary PKCS#11 calls to create a session capable of
+ * providing operations on the requested mechanism
+ */
+CK_RV SUNW_C_GetMechSession(CK_MECHANISM_TYPE mech,
+    CK_SESSION_HANDLE_PTR hSession);
+
+/*
+ * SUNW_C_KeyToObject will create a secret key object for the given
+ * mechanism from the rawkey data.
+ */
+CK_RV SUNW_C_KeyToObject(CK_SESSION_HANDLE hSession,
+    CK_MECHANISM_TYPE mech, const void *rawkey, size_t rawkey_len,
+    CK_OBJECT_HANDLE_PTR obj);
+
+
+#ifdef	__cplusplus
+}
+#endif
+
+#endif	/* _CRYPTOKI_H */
diff -r -u -N openssl-0.9.8g/crypto/engine/eng_all.c openssl/crypto/engine/eng_all.c
--- openssl-0.9.8g/crypto/engine/eng_all.c	2007-01-04 23:55:25.000000000 +0100
+++ openssl/crypto/engine/eng_all.c	2007-10-25 01:27:09.000000000 +0200
@@ -107,6 +107,9 @@
 #if defined(__OpenBSD__) || defined(__FreeBSD__)
 	ENGINE_load_cryptodev();
 #endif
+#ifndef OPENSSL_NO_HW_PKCS11
+	ENGINE_load_pk11();
+#endif
 #endif
 	}
 
diff -r -u -N openssl-0.9.8g/crypto/engine/engine.h openssl/crypto/engine/engine.h
--- openssl-0.9.8g/crypto/engine/engine.h	2005-11-06 18:48:59.000000000 +0100
+++ openssl/crypto/engine/engine.h	2007-10-25 01:27:09.000000000 +0200
@@ -332,6 +332,7 @@
 void ENGINE_load_ubsec(void);
 #endif
 void ENGINE_load_cryptodev(void);
+void ENGINE_load_pk11(void);
 void ENGINE_load_padlock(void);
 void ENGINE_load_builtin_engines(void);
 
diff -r -u -N openssl-0.9.8g/crypto/engine/hw_pk11.c openssl/crypto/engine/hw_pk11.c
--- openssl-0.9.8g/crypto/engine/hw_pk11.c	1970-01-01 01:00:00.000000000 +0100
+++ openssl/crypto/engine/hw_pk11.c	2007-10-29 23:31:11.000000000 +0100
@@ -0,0 +1,2153 @@
+/*
+ * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
+ * Use is subject to license terms.
+ */
+
+#pragma ident	"@(#)hw_pk11.c	1.12	07/07/05 SMI"
+
+/* crypto/engine/hw_pk11.c */
+/* This product includes software developed by the OpenSSL Project for 
+ * use in the OpenSSL Toolkit (http://www.openssl.org/).
+ *
+ * This project also referenced hw_pkcs11-0.9.7b.patch written by 
+ * Afchine Madjlessi.
+ */
+/* ====================================================================
+ * Copyright (c) 2000-2001 The OpenSSL Project.  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. All advertising materials mentioning features or use of this
+ *    software must display the following acknowledgment:
+ *    "This product includes software developed by the OpenSSL Project
+ *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
+ *
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ *    endorse or promote products derived from this software without
+ *    prior written permission. For written permission, please contact
+ *    licensing@OpenSSL.org.
+ *
+ * 5. Products derived from this software may not be called "OpenSSL"
+ *    nor may "OpenSSL" appear in their names without prior written
+ *    permission of the OpenSSL Project.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ *    acknowledgment:
+ *    "This product includes software developed by the OpenSSL Project
+ *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED 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 OpenSSL PROJECT OR
+ * ITS 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.
+ * ====================================================================
+ *
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com).  This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+ *
+ */
+
+#include <stdio.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <openssl/e_os2.h>
+#include <openssl/engine.h>
+#include <openssl/dso.h>
+#include <openssl/err.h>
+#include <openssl/bn.h>
+#include <openssl/md5.h>
+#include <openssl/pem.h>
+#include <openssl/rsa.h>
+#include <openssl/rand.h>
+#include <openssl/objects.h>
+#include <openssl/x509.h>
+#include <cryptlib.h>
+
+#ifndef OPENSSL_NO_HW
+#ifndef OPENSSL_NO_HW_PK11
+
+#undef DEBUG_SLOT_SELECTION
+
+#include "cryptoki.h"
+#include "pkcs11.h"
+#include "hw_pk11_err.c"
+
+
+/* The head of the free PK11 session list */
+static struct PK11_SESSION_st *free_session = NULL;
+
+/* Create all secret key objects in a global session so that they are available
+ * to use for other sessions. These other sessions may be opened or closed
+ * without losing the secret key objects */
+static CK_SESSION_HANDLE	global_session = CK_INVALID_HANDLE;
+
+/* ENGINE level stuff */
+static int pk11_init(ENGINE *e);
+static int pk11_library_init(ENGINE *e);
+static int pk11_finish(ENGINE *e);
+static int pk11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)());
+static int pk11_destroy(ENGINE *e);
+
+/* RAND stuff */
+static void pk11_rand_seed(const void *buf, int num);
+static void pk11_rand_add(const void *buf, int num, double add_entropy);
+static void pk11_rand_cleanup(void);
+static int pk11_rand_bytes(unsigned char *buf, int num);
+static int pk11_rand_status(void);
+
+/* These functions are also used in other files */
+PK11_SESSION *pk11_get_session();
+void pk11_return_session(PK11_SESSION *sp);
+int pk11_destroy_rsa_key_objects(PK11_SESSION *session);
+int pk11_destroy_dsa_key_objects(PK11_SESSION *session);
+int pk11_destroy_dh_key_objects(PK11_SESSION *session);
+
+/* Local helper functions */
+static int pk11_free_all_sessions();
+static int pk11_setup_session(PK11_SESSION *sp);
+static int pk11_destroy_cipher_key_objects(PK11_SESSION *session);
+static int pk11_destroy_object(CK_SESSION_HANDLE session, 
+	CK_OBJECT_HANDLE oh);
+static const char *get_PK11_LIBNAME(void);
+static void free_PK11_LIBNAME(void);
+static long set_PK11_LIBNAME(const char *name);
+
+/* Symmetric cipher and digest support functions */
+static int cipher_nid_to_pk11(int nid);
+static int pk11_usable_ciphers(const int **nids);
+static int pk11_usable_digests(const int **nids);
+static int pk11_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
+	const unsigned char *iv, int enc);
+static int pk11_cipher_final(PK11_SESSION *sp);
+static int pk11_cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
+	const unsigned char *in, unsigned int inl);
+static int pk11_cipher_cleanup(EVP_CIPHER_CTX *ctx);
+static int pk11_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
+	const int **nids, int nid);
+static int pk11_engine_digests(ENGINE *e, const EVP_MD **digest,
+	const int **nids, int nid);
+static CK_OBJECT_HANDLE pk11_get_cipher_key(EVP_CIPHER_CTX *ctx, 
+	const unsigned char *key, CK_KEY_TYPE key_type, PK11_SESSION *sp);
+static void check_new_cipher_key(PK11_SESSION *sp, const unsigned char *key);
+static int md_nid_to_pk11(int nid);
+static int pk11_digest_init(EVP_MD_CTX *ctx);
+static int pk11_digest_update(EVP_MD_CTX *ctx,const void *data,
+	size_t count);
+static int pk11_digest_final(EVP_MD_CTX *ctx,unsigned char *md);
+static int pk11_digest_copy(EVP_MD_CTX *to,const EVP_MD_CTX *from);
+static int pk11_digest_cleanup(EVP_MD_CTX *ctx);
+
+static int pk11_choose_slot();
+static int pk11_count_symmetric_cipher(int slot_id, CK_MECHANISM_TYPE mech,
+    int *current_slot_n_cipher, int *local_cipher_nids, int id);
+static int pk11_count_digest(int slot_id, CK_MECHANISM_TYPE mech,
+    int *current_slot_n_digest, int *local_digest_nids, int id);
+
+/* Index for the supported ciphers */
+#define PK11_DES_CBC		0
+#define PK11_DES3_CBC		1
+#define PK11_AES_CBC		2
+#define PK11_RC4		3
+
+/* Index for the supported digests */
+#define PK11_MD5		0
+#define PK11_SHA1		1
+
+#define PK11_CIPHER_MAX		4	/* Max num of ciphers supported */
+#define PK11_DIGEST_MAX		2	/* Max num of digests supported */
+
+#define PK11_KEY_LEN_MAX	24
+
+static int cipher_nids[PK11_CIPHER_MAX];
+static int digest_nids[PK11_DIGEST_MAX];
+static int cipher_count		= 0;
+static int digest_count		= 0;
+static CK_BBOOL pk11_have_rsa	= CK_FALSE;
+static CK_BBOOL pk11_have_dsa	= CK_FALSE;
+static CK_BBOOL pk11_have_dh	= CK_FALSE;
+static CK_BBOOL pk11_have_random = CK_FALSE;
+
+typedef struct PK11_CIPHER_st 
+	{
+	int		id;
+	int		nid;
+	int		ivmax;
+	int		key_len;
+	CK_KEY_TYPE	key_type;
+	CK_MECHANISM_TYPE	mech_type;
+	} PK11_CIPHER;
+
+static PK11_CIPHER ciphers[] = 
+	{
+	{PK11_DES_CBC,  NID_des_cbc,      8,  8,   CKK_DES,  CKM_DES_CBC, },
+	{PK11_DES3_CBC, NID_des_ede3_cbc, 8,  24,  CKK_DES3, CKM_DES3_CBC, },
+	{PK11_AES_CBC,  NID_aes_128_cbc,  16, 16,  CKK_AES,  CKM_AES_CBC, },
+	{PK11_RC4,      NID_rc4,          0,  16,  CKK_RC4,  CKM_RC4, },
+	};
+
+typedef struct PK11_DIGEST_st
+	{
+	int		id;
+	int		nid;
+	CK_MECHANISM_TYPE	mech_type;
+	} PK11_DIGEST;
+
+static PK11_DIGEST digests[] = 
+	{
+	{PK11_MD5,	NID_md5,	CKM_MD5, },
+	{PK11_SHA1,	NID_sha1,	CKM_SHA_1, },
+	{0,		NID_undef,	0xFFFF, },
+	};
+
+/* Structure to be used for the cipher_data/md_data in 
+ * EVP_CIPHER_CTX/EVP_MD_CTX structures in order to use the same 
+ * pk11 session in multiple cipher_update calls
+ */
+typedef struct PK11_CIPHER_STATE_st
+	{
+	PK11_SESSION	*sp;
+	} PK11_CIPHER_STATE;
+
+
+/* libcrypto EVP stuff - this is how we get wired to EVP so the engine
+ * gets called when libcrypto requests a cipher NID.
+ * Note how the PK11_CIPHER_STATE is used here.
+ */
+
+/* DES CBC EVP */
+static const EVP_CIPHER pk11_des_cbc = 
+	{
+	NID_des_cbc,
+	8, 8, 8,
+	EVP_CIPH_CBC_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof(PK11_CIPHER_STATE),
+	EVP_CIPHER_set_asn1_iv,
+	EVP_CIPHER_get_asn1_iv,
+	NULL
+	};
+
+/* 3DES CBC EVP */
+static const EVP_CIPHER pk11_3des_cbc = 
+	{
+	NID_des_ede3_cbc,
+	8, 24, 8,
+	EVP_CIPH_CBC_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof(PK11_CIPHER_STATE),
+	EVP_CIPHER_set_asn1_iv,
+	EVP_CIPHER_get_asn1_iv,
+	NULL
+	};
+
+static const EVP_CIPHER pk11_aes_cbc = 
+	{
+	NID_aes_128_cbc,
+	16, 16, 16,
+	EVP_CIPH_CBC_MODE,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof(PK11_CIPHER_STATE),
+	EVP_CIPHER_set_asn1_iv,
+	EVP_CIPHER_get_asn1_iv,
+	NULL
+	};
+
+static const EVP_CIPHER pk11_rc4 =
+	{
+	NID_rc4,
+	1,16,0,
+	EVP_CIPH_VARIABLE_LENGTH,
+	pk11_cipher_init,
+	pk11_cipher_do_cipher,
+	pk11_cipher_cleanup,
+	sizeof(PK11_CIPHER_STATE),
+	NULL,
+	NULL,
+	NULL
+	};
+
+static const EVP_MD pk11_md5 =
+	{
+	NID_md5,
+	NID_md5WithRSAEncryption,
+	MD5_DIGEST_LENGTH,
+	0,
+	pk11_digest_init,
+	pk11_digest_update,
+	pk11_digest_final,
+	pk11_digest_copy,
+	pk11_digest_cleanup,
+	EVP_PKEY_RSA_method,
+	MD5_CBLOCK,
+	sizeof(PK11_CIPHER_STATE),
+	};
+
+static const EVP_MD pk11_sha1 =
+	{
+	NID_sha1,
+	NID_sha1WithRSAEncryption,
+	SHA_DIGEST_LENGTH,
+	0,
+	pk11_digest_init,
+	pk11_digest_update,
+	pk11_digest_final,
+	pk11_digest_copy,
+	pk11_digest_cleanup,
+	EVP_PKEY_RSA_method,
+	SHA_CBLOCK,
+	sizeof(PK11_CIPHER_STATE),
+	};
+
+/* Initialization function. Sets up various pk11 library components.
+ */
+/* The definitions for control commands specific to this engine
+ */
+#define PK11_CMD_SO_PATH		ENGINE_CMD_BASE
+#define PK11_CMD_PIN			(ENGINE_CMD_BASE+1)
+#define PK11_CMD_SLOT			(ENGINE_CMD_BASE+2)
+static const ENGINE_CMD_DEFN pk11_cmd_defns[] =
+	{
+		{
+		PK11_CMD_SO_PATH,
+		"SO_PATH",
+		"Specifies the path to the 'pkcs#11' shared library",
+		ENGINE_CMD_FLAG_STRING
+		},
+		{
+		PK11_CMD_PIN,
+		"PIN",
+		"Specifies the pin code",
+		ENGINE_CMD_FLAG_STRING
+		},
+		{
+		PK11_CMD_SLOT,
+		"SLOT",
+		"Specifies the slot (default is auto select)",
+		ENGINE_CMD_FLAG_NUMERIC,
+		},
+		{0, NULL, NULL, 0}
+	};
+
+
+static RAND_METHOD pk11_random =
+	{
+	pk11_rand_seed,
+	pk11_rand_bytes,
+	pk11_rand_cleanup,
+	pk11_rand_add,
+	pk11_rand_bytes,
+	pk11_rand_status
+	};
+
+
+/* Constants used when creating the ENGINE
+ */
+static const char *engine_pk11_id = "pkcs11";
+static const char *engine_pk11_name = "PKCS #11 engine support";
+
+CK_FUNCTION_LIST_PTR pFuncList = NULL;
+static const char PK11_GET_FUNCTION_LIST[] = "C_GetFunctionList";
+
+/* Cryptoki library
+ */
+static const char def_PK11_LIBNAME[] = PK11_LIB_LOCATION;
+
+static CK_BBOOL true = TRUE;
+static CK_BBOOL false = FALSE;
+static CK_SLOT_ID SLOTID = 0;
+static int pk11_auto_slot = 1;
+char *pk11_pin;
+static int pk11_library_initialized = 0;
+
+static DSO *pk11_dso = NULL;
+
+/*
+ * This internal function is used by ENGINE_pk11() and "dynamic" ENGINE support.
+ */
+static int bind_pk11(ENGINE *e)
+	{
+	const RSA_METHOD *rsa = NULL;
+	RSA_METHOD *pk11_rsa = PK11_RSA();
+
+	if (!pk11_library_initialized)
+		pk11_library_init(e);
+
+	if(!ENGINE_set_id(e, engine_pk11_id) ||
+	   !ENGINE_set_name(e, engine_pk11_name) ||
+	   !ENGINE_set_ciphers(e, pk11_engine_ciphers) ||
+	   !ENGINE_set_digests(e, pk11_engine_digests))
+	   	return 0;
+#ifndef OPENSSL_NO_RSA
+	if(pk11_have_rsa == CK_TRUE)
+		{
+		if(!ENGINE_set_RSA(e, PK11_RSA()) ||
+	           !ENGINE_set_load_privkey_function(e, pk11_load_privkey) ||
+	           !ENGINE_set_load_pubkey_function(e, pk11_load_pubkey))
+			return 0;
+#ifdef DEBUG_SLOT_SELECTION
+		fprintf(stderr, "OPENSSL_PKCS#11_ENGINE: registered RSA\n");
+#endif /* DEBUG_SLOT_SELECTION */
+		}
+#endif
+#ifndef OPENSSL_NO_DSA
+	if(pk11_have_dsa == CK_TRUE)
+		{	
+	  	if (!ENGINE_set_DSA(e, PK11_DSA()))
+			return 0;
+#ifdef DEBUG_SLOT_SELECTION
+		fprintf(stderr, "OPENSSL_PKCS#11_ENGINE: registered DSA\n");
+#endif /* DEBUG_SLOT_SELECTION */
+	    	}
+#endif
+#ifndef OPENSSL_NO_DH
+	if(pk11_have_dh == CK_TRUE)
+		{
+	  	if (!ENGINE_set_DH(e, PK11_DH()))
+			return 0;
+#ifdef DEBUG_SLOT_SELECTION
+		fprintf(stderr, "OPENSSL_PKCS#11_ENGINE: registered DH\n");
+#endif /* DEBUG_SLOT_SELECTION */
+	    	}
+#endif
+	if(pk11_have_random)
+		{
+		if(!ENGINE_set_RAND(e, &pk11_random))
+			return 0;
+#ifdef DEBUG_SLOT_SELECTION
+		fprintf(stderr, "OPENSSL_PKCS#11_ENGINE: registered random\n");
+#endif /* DEBUG_SLOT_SELECTION */
+		}
+	if(!ENGINE_set_init_function(e, pk11_init) ||
+	   !ENGINE_set_destroy_function(e, pk11_destroy) ||
+	   !ENGINE_set_finish_function(e, pk11_finish) ||
+	   !ENGINE_set_ctrl_function(e, pk11_ctrl) ||
+	   !ENGINE_set_cmd_defns(e, pk11_cmd_defns))
+		return 0;
+
+/* Apache calls OpenSSL function RSA_blinding_on() once during startup
+ * which in turn calls bn_mod_exp. Since we do not implement bn_mod_exp
+ * here, we wire it back to the OpenSSL software implementation. 
+ * Since it is used only once, performance is not a concern. */
+#ifndef OPENSSL_NO_RSA
+        rsa = RSA_PKCS1_SSLeay();
+        pk11_rsa->rsa_mod_exp = rsa->rsa_mod_exp;
+        pk11_rsa->bn_mod_exp = rsa->bn_mod_exp;
+#endif
+
+	/* Ensure the pk11 error handling is set up */
+	ERR_load_pk11_strings();
+	
+	return 1;
+	}
+
+/* Dynamic engine support is disabled at a higher level for Solaris
+ */
+#ifdef ENGINE_DYNAMIC_SUPPORT
+static int bind_helper(ENGINE *e, const char *id)
+	{
+	if (id && (strcmp(id, engine_pk11_id) != 0))
+		return 0;
+
+	if (!bind_pk11(e))
+		return 0;
+
+	return 1;
+	}	   
+
+IMPLEMENT_DYNAMIC_CHECK_FN()
+IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
+
+#else
+static ENGINE *engine_pk11(void)
+	{
+	ENGINE *ret = ENGINE_new();
+
+	if (!ret)
+		return NULL;
+
+	if (!bind_pk11(ret))
+		{
+		ENGINE_free(ret);
+		return NULL;
+		}
+
+	return ret;
+	}
+
+void ENGINE_load_pk11(void)
+	{
+	ENGINE *e_pk11 = NULL;
+
+	/* Do not use dynamic PKCS#11 library on Solaris due to 
+	 * security reasons. We will link it in statically
+	 */
+	/* Attempt to load PKCS#11 library 
+	 */
+	if (!pk11_dso)
+		pk11_dso = DSO_load(NULL, get_PK11_LIBNAME(), NULL, 0);
+
+	if (pk11_dso == NULL)
+		{
+		PK11err(PK11_F_LOAD, PK11_R_DSO_FAILURE);
+		return;
+		}
+
+	e_pk11 = engine_pk11();
+	if (!e_pk11) 
+		{
+		DSO_free(pk11_dso);
+		pk11_dso = NULL;
+		return;
+		}
+
+	/* At this point, the pk11 shared library is either dynamically
+	 * loaded or statically linked in. So, initialize the pk11 
+	 * library before calling ENGINE_set_default since the latter 
+	 * needs cipher and digest algorithm information
+	 */
+	if (!pk11_library_init(e_pk11))
+		{
+		DSO_free(pk11_dso);
+		pk11_dso = NULL;
+		ENGINE_free(e_pk11);
+		return;
+		}
+
+	ENGINE_add(e_pk11);
+
+	ENGINE_free(e_pk11);
+	ERR_clear_error();
+	}
+#endif
+
+/* These are the static string constants for the DSO file name and 
+ * the function symbol names to bind to. 
+ */
+static const char *PK11_LIBNAME = NULL;
+
+static const char *get_PK11_LIBNAME(void)
+	{
+	if (PK11_LIBNAME)
+		return PK11_LIBNAME;
+
+	return def_PK11_LIBNAME;
+	}
+
+static void free_PK11_LIBNAME(void)
+	{
+	if (PK11_LIBNAME)
+		OPENSSL_free((void*)PK11_LIBNAME);
+
+	PK11_LIBNAME = NULL;
+	}
+
+static long set_PK11_LIBNAME(const char *name)
+	{
+	free_PK11_LIBNAME();
+
+	return ((PK11_LIBNAME = BUF_strdup(name)) != NULL ? 1 : 0);
+	}
+
+/* Initialization function for the pk11 engine */
+static int pk11_init(ENGINE *e)
+{
+	return pk11_library_init(e);
+}
+
+/* Initialization function. Sets up various pk11 library components.
+ * It selects a slot based on predefined critiera. In the process, it also
+ * count how many ciphers and digests to support. Since the cipher and
+ * digest information is needed when setting default engine, this function
+ * needs to be called before calling ENGINE_set_default.
+ */
+static int pk11_library_init(ENGINE *e)
+	{
+	CK_C_GetFunctionList p;
+	CK_RV rv = CKR_OK;
+	CK_INFO info;
+	CK_ULONG ul_state_len;
+	char tmp_buf[20];
+
+	if (pk11_library_initialized)
+		return 1;
+	
+	if (pk11_dso == NULL)
+		{
+		PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
+		goto err;
+		}
+
+	/* get the C_GetFunctionList function from the loaded library
+	 */
+	p = (CK_C_GetFunctionList)DSO_bind_func(pk11_dso, 
+		PK11_GET_FUNCTION_LIST);
+	if ( !p )
+		{
+		PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
+		goto err;
+		}
+ 
+	/* get the full function list from the loaded library 
+	 */
+	rv = p(&pFuncList);
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_LIBRARY_INIT, PK11_R_DSO_FAILURE);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+ 
+	rv = pFuncList->C_Initialize(NULL_PTR);
+	if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
+		{
+		PK11err(PK11_F_LIBRARY_INIT, PK11_R_INITIALIZE);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	rv = pFuncList->C_GetInfo(&info);
+	if (rv != CKR_OK) 
+		{
+		PK11err(PK11_F_LIBRARY_INIT, PK11_R_GETINFO);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	if (pk11_choose_slot() == 0)
+		goto err;
+
+	if (global_session == CK_INVALID_HANDLE)
+		{
+		/* Open the global_session for the new process */
+		rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
+			NULL_PTR, NULL_PTR, &global_session);
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_LIBRARY_INIT, PK11_R_OPENSESSION);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+		}
+
+	/* Disable digest if C_GetOperationState is not supported since
+	 * this function is required by OpenSSL digest copy function */
+	if (pFuncList->C_GetOperationState(global_session, NULL, &ul_state_len)
+			== CKR_FUNCTION_NOT_SUPPORTED)
+		digest_count = 0;
+
+	pk11_library_initialized = 1;
+	return 1;
+
+err:
+
+	return 0;
+	}
+
+/* Destructor (complements the "ENGINE_pk11()" constructor)
+ */
+static int pk11_destroy(ENGINE *e)
+	{
+	free_PK11_LIBNAME();
+	ERR_unload_pk11_strings();
+	if (pk11_pin) {
+		memset(pk11_pin, 0, strlen(pk11_pin));
+		OPENSSL_free((void*)pk11_pin);
+	}
+	pk11_pin = NULL;
+	return 1;
+	}
+
+/* Termination function to clean up the session, the token, and 
+ * the pk11 library.
+ */
+static int pk11_finish(ENGINE *e)
+	{
+
+	if (pk11_pin) {
+		memset(pk11_pin, 0, strlen(pk11_pin));
+		OPENSSL_free((void*)pk11_pin);
+	}
+	pk11_pin = NULL;
+
+	if (pk11_dso == NULL)
+		{
+		PK11err(PK11_F_FINISH, PK11_R_NOT_LOADED);
+		goto err;
+		}
+
+	assert(pFuncList != NULL);
+
+	if (pk11_free_all_sessions() == 0)
+		goto err;
+
+	pFuncList->C_CloseSession(global_session);
+	
+	/* Since we are part of a library (libcrypto.so), calling this
+	 * function may have side-effects.
+	pFuncList->C_Finalize(NULL);
+	 */
+
+	if (!DSO_free(pk11_dso))
+		{
+		PK11err(PK11_F_FINISH, PK11_R_DSO_FAILURE);
+		goto err;
+		}
+	pk11_dso = NULL;
+	pFuncList = NULL;
+	pk11_library_initialized = 0;
+
+	return 1;
+
+err:
+	return 0;
+	}
+
+/* Standard engine interface function to set the dynamic library path */
+static int pk11_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)())
+	{
+	int initialized = ((pk11_dso == NULL) ? 0 : 1);
+
+	switch(cmd)
+		{
+	case PK11_CMD_SO_PATH:
+		if (p == NULL)
+			{
+			PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
+			return 0;
+			}
+
+		if (initialized)
+			{
+			PK11err(PK11_F_CTRL, PK11_R_ALREADY_LOADED);
+			return 0;
+			}
+
+		return set_PK11_LIBNAME((const char*)p);
+	case PK11_CMD_PIN:
+		if (pk11_pin) {
+			memset(pk11_pin, 0, strlen(pk11_pin));
+			OPENSSL_free((void*)pk11_pin);
+		}
+		pk11_pin = NULL;
+
+		if (p == NULL)
+			{
+			PK11err(PK11_F_CTRL, ERR_R_PASSED_NULL_PARAMETER);
+			return 0;
+			}
+
+		pk11_pin = BUF_strdup(p);
+		if (pk11_pin == NULL)
+			{
+			PK11err(PK11_F_GET_SESSION, PK11_R_MALLOC_FAILURE);
+			return 0;
+			}
+		return 1;
+	case PK11_CMD_SLOT:
+		SLOTID = (CK_SLOT_ID)i;
+#ifdef DEBUG_SLOT_SELECTION
+		fprintf(stderr, "OPENSSL_PKCS#11_ENGINE: slot set\n");
+#endif
+		return 1;
+	default:
+		break;
+		}
+
+	PK11err(PK11_F_CTRL,PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED);
+
+	return 0;
+	}
+
+
+/* Required function by the engine random interface. It does nothing here
+ */
+static void pk11_rand_cleanup(void)
+	{
+	return;
+	}
+
+static void pk11_rand_add(const void *buf, int num, double add)
+	{
+	PK11_SESSION *sp;
+
+	if ((sp = pk11_get_session()) == NULL)
+		return;
+
+	/* Ignore any errors (e.g. CKR_RANDOM_SEED_NOT_SUPPORTED) since 
+	 * the calling functions do not care anyway
+	 */
+	pFuncList->C_SeedRandom(sp->session, (unsigned char *) buf, num);
+	pk11_return_session(sp);
+
+	return;
+	}
+
+static void pk11_rand_seed(const void *buf, int num)
+	{
+	pk11_rand_add(buf, num, 0);
+	}
+
+static int pk11_rand_bytes(unsigned char *buf, int num)
+	{
+	CK_RV rv;
+	PK11_SESSION *sp;
+	
+	if ((sp = pk11_get_session()) == NULL)
+		return 0;
+	
+	rv = pFuncList->C_GenerateRandom(sp->session, buf, num);
+	if (rv != CKR_OK)
+		{
+		char tmp_buf[20];
+		PK11err(PK11_F_RAND_BYTES, PK11_R_GENERATERANDOM);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		pk11_return_session(sp);
+		return 0;
+		}
+
+	pk11_return_session(sp);
+	return 1;
+	}
+
+
+/* Required function by the engine random interface. It does nothing here
+ */
+static int pk11_rand_status(void)
+	{
+	return 1;
+	}
+
+
+PK11_SESSION *pk11_get_session()
+	{
+	PK11_SESSION *sp, *sp1;
+	CK_RV rv;
+	char tmp_buf[20];
+
+	CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+	if ((sp = free_session) == NULL)
+		{
+		if ((sp = OPENSSL_malloc(sizeof(PK11_SESSION))) == NULL)
+			{
+			PK11err(PK11_F_GET_SESSION, 
+				PK11_R_MALLOC_FAILURE);
+			goto err;
+			}
+		memset(sp, 0, sizeof(PK11_SESSION));
+		}
+	else
+		{
+		free_session = sp->next;
+		}
+
+	if (sp->pid != 0 && sp->pid != getpid())
+		{
+		/* We are a new process and thus need to free any inherated
+		 * PK11_SESSION objects.
+		 */
+		while ((sp1 = free_session) != NULL)
+			{
+			free_session = sp1->next;
+			OPENSSL_free(sp1);
+			}
+
+		/* Initialize the process */
+		rv = pFuncList->C_Initialize(NULL_PTR);
+		if ((rv != CKR_OK) && (rv != CKR_CRYPTOKI_ALREADY_INITIALIZED))
+			{
+			PK11err(PK11_F_GET_SESSION, PK11_R_INITIALIZE);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			OPENSSL_free(sp);
+			sp = NULL;
+			goto err;
+			}
+
+		/* Choose slot here since the slot table is different on 
+		 * this process.
+		 */
+		if (pk11_choose_slot() == 0)
+			goto err;
+
+		/* Open the global_session for the new process */
+		rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
+			NULL_PTR, NULL_PTR, &global_session);
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_GET_SESSION, PK11_R_OPENSESSION);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			OPENSSL_free(sp);
+			sp = NULL;
+			goto err;
+			}
+
+		/* It is an inherited session and needs re-initialization.
+		 */
+		if (pk11_setup_session(sp) == 0)
+			{
+			OPENSSL_free(sp);
+			sp = NULL;
+			}
+		}
+	else if (sp->pid == 0)
+		{
+		/* It is a new session and needs initialization.
+		 */
+		if (pk11_setup_session(sp) == 0)
+			{
+			OPENSSL_free(sp);
+			sp = NULL;
+			}
+		}
+
+err:
+	if (sp)
+		sp->next = NULL;
+
+	CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+
+	return sp;
+	}
+
+
+void pk11_return_session(PK11_SESSION *sp)
+	{
+	if (sp == NULL || sp->pid != getpid())
+		return;
+
+	
+	CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+
+	sp->next = free_session;
+	free_session = sp;
+
+	CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+	}
+
+
+/* Destroy all objects. This function is called when the engine is finished
+ */
+static int pk11_free_all_sessions()
+	{
+	CK_RV rv;
+	PK11_SESSION *sp = NULL;
+	pid_t mypid = getpid();
+	int ret = 0;
+
+	pk11_destroy_rsa_key_objects(NULL);
+	pk11_destroy_dsa_key_objects(NULL);
+	pk11_destroy_dh_key_objects(NULL);
+	pk11_destroy_cipher_key_objects(NULL);
+	
+	CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+	while ((sp = free_session) != NULL)
+		{
+		if (sp->session != CK_INVALID_HANDLE && sp->pid == mypid)
+			{
+			rv = pFuncList->C_CloseSession(sp->session);
+			if (rv != CKR_OK)
+				{
+				char tmp_buf[20];
+				PK11err(PK11_F_FREE_ALL_SESSIONS, 
+					PK11_R_CLOSESESSION);
+				snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+				ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+				}
+			}
+		if (sp->session_cipher != CK_INVALID_HANDLE && sp->pid == mypid)
+			{
+			rv = pFuncList->C_CloseSession(sp->session_cipher);
+			if (rv != CKR_OK)
+				{
+				char tmp_buf[20];
+				PK11err(PK11_F_FREE_ALL_SESSIONS, 
+					PK11_R_CLOSESESSION);
+				snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+				ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+				}
+			}
+		free_session = sp->next;
+		OPENSSL_free(sp);
+		}
+	ret = 1;
+err:
+	CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+
+	return ret;
+	}
+
+
+static int pk11_setup_session(PK11_SESSION *sp)
+	{
+	CK_RV rv;
+	sp->session = CK_INVALID_HANDLE;
+	rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
+		NULL_PTR, NULL_PTR, &sp->session);
+	if (rv == CKR_CRYPTOKI_NOT_INITIALIZED)
+		{
+		/*
+		 * We are probably a child process so force the
+		 * reinitialize of the session
+		 */
+		pk11_library_initialized = 0;
+		(void) pk11_library_init(NULL);
+		rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
+			NULL_PTR, NULL_PTR, &sp->session);
+		}
+	if (rv != CKR_OK)
+		{
+		char tmp_buf[20];
+		PK11err(PK11_F_SETUP_SESSION, PK11_R_OPENSESSION);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		return 0;
+		}
+
+	sp->session_cipher = CK_INVALID_HANDLE;
+	rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
+		NULL_PTR, NULL_PTR, &sp->session_cipher);
+	if (rv != CKR_OK)
+		{
+		char tmp_buf[20];
+
+		(void) pFuncList->C_CloseSession(sp->session);
+		sp->session = CK_INVALID_HANDLE;
+
+		PK11err(PK11_F_SETUP_SESSION, PK11_R_OPENSESSION);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		return 0;
+		}
+
+	sp->pid = getpid();
+	sp->rsa_pub_key = CK_INVALID_HANDLE;
+	sp->rsa_priv_key = CK_INVALID_HANDLE;
+	sp->dsa_pub_key = CK_INVALID_HANDLE;
+	sp->dsa_priv_key = CK_INVALID_HANDLE;
+	sp->dh_key = CK_INVALID_HANDLE;
+	sp->cipher_key = CK_INVALID_HANDLE;
+	sp->rsa = NULL;
+	sp->dsa = NULL;
+	sp->dh = NULL;
+	sp->encrypt = -1;
+
+	return 1;
+	}
+
+int pk11_destroy_rsa_key_objects(PK11_SESSION *session)
+	{
+	int ret = 0;
+	PK11_SESSION *sp = NULL;
+	PK11_SESSION *local_free_session;
+
+	CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+	if (session)
+		local_free_session = session;
+	else
+		local_free_session = free_session;
+	while ((sp = local_free_session) != NULL)
+		{
+		local_free_session = sp->next;
+
+		if (sp->rsa_pub_key != CK_INVALID_HANDLE)
+			{
+			if (pk11_destroy_object(sp->session, 
+				sp->rsa_pub_key) == 0)
+				goto err;
+			sp->rsa_pub_key = CK_INVALID_HANDLE;
+			}
+
+		if (sp->rsa_priv_key != CK_INVALID_HANDLE)
+			{
+			if ((sp->rsa->flags & RSA_FLAG_EXT_PKEY) == 0 &&
+			    pk11_destroy_object(sp->session, 
+				sp->rsa_priv_key) == 0)
+				goto err;
+			sp->rsa_priv_key = CK_INVALID_HANDLE;
+			}
+
+		sp->rsa = NULL;
+		}
+	ret = 1;
+err:
+	CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+
+	return ret;
+	}
+
+int pk11_destroy_dsa_key_objects(PK11_SESSION *session)
+	{
+	int ret = 0;
+	PK11_SESSION *sp = NULL;
+	PK11_SESSION *local_free_session;
+
+	CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+	if (session)
+		local_free_session = session;
+	else
+		local_free_session = free_session;
+	while ((sp = local_free_session) != NULL)
+		{
+		local_free_session = sp->next;
+
+		if (sp->dsa_pub_key != CK_INVALID_HANDLE)
+			{
+			if (pk11_destroy_object(sp->session, 
+				sp->dsa_pub_key) == 0)
+				goto err;
+			sp->dsa_pub_key = CK_INVALID_HANDLE;
+			}
+
+		if (sp->dsa_priv_key != CK_INVALID_HANDLE)
+			{
+			if (pk11_destroy_object(sp->session, 
+				sp->dsa_priv_key) == 0)
+				goto err;
+			sp->dsa_priv_key = CK_INVALID_HANDLE;
+			}
+
+		sp->dsa = NULL;
+		}
+	ret = 1;
+err:
+	CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+
+	return ret;
+	}
+
+int pk11_destroy_dh_key_objects(PK11_SESSION *session)
+	{
+	int ret = 0;
+	PK11_SESSION *sp = NULL;
+	PK11_SESSION *local_free_session;
+
+	CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+	if (session)
+		local_free_session = session;
+	else
+		local_free_session = free_session;
+	while ((sp = local_free_session) != NULL)
+		{
+		local_free_session = sp->next;
+
+		if (sp->dh_key != CK_INVALID_HANDLE)
+			{
+			if (pk11_destroy_object(sp->session, 
+				sp->dh_key) == 0)
+				goto err;
+			sp->dh_key = CK_INVALID_HANDLE;
+			}
+
+		sp->dh = NULL;
+		}
+	ret = 1;
+err:
+	CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+
+	return ret;
+	}
+
+static int pk11_destroy_object(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE oh)
+	{
+	CK_RV rv;
+	rv = pFuncList->C_DestroyObject(session, oh);
+	if (rv != CKR_OK)
+		{
+		char tmp_buf[20];
+		PK11err(PK11_F_DESTROY_OBJECT, PK11_R_DESTROYOBJECT);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", 
+			tmp_buf);
+		return 0;
+		}
+
+	return 1;
+	}
+
+
+/* Symmetric ciphers and digests support functions
+ */
+
+static int
+cipher_nid_to_pk11(int nid)
+	{
+	int i;
+
+	for (i = 0; i < PK11_CIPHER_MAX; i++)
+		if (ciphers[i].nid == nid)
+			return (ciphers[i].id);
+	return (-1);
+	}
+
+static int
+pk11_usable_ciphers(const int **nids)
+	{
+	if (cipher_count > 0)
+		*nids = cipher_nids;
+	else
+		*nids = NULL;
+	return (cipher_count);
+	}
+
+static int
+pk11_usable_digests(const int **nids)
+	{
+	if (digest_count > 0)
+		*nids = digest_nids;
+	else
+		*nids = NULL;
+	return (digest_count);
+	}
+
+static int
+pk11_cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key,
+    const unsigned char *iv, int enc)
+	{
+	CK_RV rv;
+	CK_MECHANISM mech;
+	int index;
+	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->cipher_data;
+	PK11_SESSION *sp;
+	PK11_CIPHER *pcp;
+	char tmp_buf[20];
+	
+	state->sp = NULL;
+
+	index = cipher_nid_to_pk11(ctx->cipher->nid);
+	if (index < 0 || index >= PK11_CIPHER_MAX)
+		return 0;
+
+	pcp = &ciphers[index];
+	if (ctx->cipher->iv_len > pcp->ivmax || ctx->key_len != pcp->key_len)
+		return 0;
+
+	if ((sp = pk11_get_session()) == NULL)
+		return 0;
+
+	/* if applicable, the mechanism parameter is used for IV */
+	mech.mechanism = pcp->mech_type;
+	mech.pParameter = NULL;
+	mech.ulParameterLen = 0;
+
+	/* The key object is destroyed here if it is not the current key
+	 */
+	check_new_cipher_key(sp, key);
+	
+	/* If the key is the same and the encryption is also the same,
+	 * then just reuse it
+	 */
+	if (sp->cipher_key != CK_INVALID_HANDLE && sp->encrypt == ctx->encrypt)
+		{
+		state->sp = sp;
+		return 1;
+		}
+
+	/* Check if the key has been invalidated. If so, a new key object
+	 * needs to be created.
+	 */
+	if (sp->cipher_key == CK_INVALID_HANDLE)
+		{
+		sp->cipher_key = pk11_get_cipher_key(
+			ctx, key, pcp->key_type, sp);
+		}
+
+	if (sp->encrypt != ctx->encrypt && sp->encrypt != -1)
+		{
+		/* The previous encryption/decryption
+		 * is different. Need to terminate the previous
+		 * active encryption/decryption here
+		 */
+		if (!pk11_cipher_final(sp))
+			{
+			pk11_return_session(sp);
+			return 0;
+			}
+		}
+
+	if (sp->cipher_key == CK_INVALID_HANDLE)
+		{
+		pk11_return_session(sp);
+		return 0;
+		}
+
+	if (ctx->cipher->iv_len > 0)
+		{
+		mech.pParameter = (void *) ctx->iv;
+		mech.ulParameterLen = ctx->cipher->iv_len;
+		}
+
+	/* If we get here, the encryption needs to be reinitialized */
+	if (ctx->encrypt)
+		{
+		rv = pFuncList->C_EncryptInit(sp->session_cipher, &mech, 
+			sp->cipher_key);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_CIPHER_INIT, PK11_R_ENCRYPTINIT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			pk11_return_session(sp);
+			return 0;
+			}
+		}
+	else
+		{
+		rv = pFuncList->C_DecryptInit(sp->session_cipher, &mech, 
+			sp->cipher_key);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_CIPHER_INIT, PK11_R_DECRYPTINIT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			pk11_return_session(sp);
+			return 0;
+			}
+		}
+
+	sp->encrypt = ctx->encrypt;
+	state->sp = sp;
+
+	return 1;
+	}
+
+/* When reusing the same key in an encryption/decryption session for a 
+ * decryption/encryption session, we need to close the active session
+ * and recreate a new one. Note that the key is in the global session so
+ * that it needs not be recreated.
+ *
+ * It is more appropriate to use C_En/DecryptFinish here. At the time of this
+ * development, these two functions in the PKCS#11 libraries used return
+ * unexpected errors when passing in 0 length output. It may be a good
+ * idea to try them again if performance is a problem here and fix
+ * C_En/DecryptFinial if there are bugs there causing the problem.
+ */
+static int
+pk11_cipher_final(PK11_SESSION *sp)
+	{
+	CK_RV rv;
+	char tmp_buf[20];
+
+	rv = pFuncList->C_CloseSession(sp->session_cipher);
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_CIPHER_FINAL, PK11_R_CLOSESESSION);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		return 0;
+		}
+
+	rv = pFuncList->C_OpenSession(SLOTID, CKF_SERIAL_SESSION,
+		NULL_PTR, NULL_PTR, &sp->session_cipher);
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_CIPHER_FINAL, PK11_R_OPENSESSION);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		return 0;
+		}
+
+	return 1;
+	}
+
+/* An engine interface function. The calling function allocates sufficient
+ * memory for the output buffer "out" to hold the results */
+static int
+pk11_cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
+	const unsigned char *in, unsigned int inl)
+	{
+	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->cipher_data;
+	PK11_SESSION *sp;
+	CK_RV rv;
+	unsigned long outl = inl;
+	char tmp_buf[20];
+
+	if (state == NULL || state->sp == NULL)
+		return 0;
+
+	sp = (PK11_SESSION *) state->sp;
+
+	if (!inl)
+		return 1;
+
+	/* RC4 is the only stream cipher we support */
+	if (ctx->cipher->nid != NID_rc4 && (inl % ctx->cipher->block_size) != 0)
+		return 0;
+
+	if (ctx->encrypt)
+		{
+		rv = pFuncList->C_EncryptUpdate(sp->session_cipher, 
+			(unsigned char *)in, inl, out, &outl);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_CIPHER_DO_CIPHER, 
+				PK11_R_ENCRYPTUPDATE);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			return 0;
+			}
+		}
+	else
+		{
+		rv = pFuncList->C_DecryptUpdate(sp->session_cipher, 
+			(unsigned char *)in, inl, out, &outl);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_CIPHER_DO_CIPHER, 
+				PK11_R_DECRYPTUPDATE);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			return 0;
+			}
+		}
+
+	/* for DES_CBC, DES3_CBC, AES_CBC, and RC4, the output size is always
+	 * the same size of input
+	 * The application has guaranteed to call the block ciphers with 
+	 * correctly aligned buffers.
+	 */
+	if (inl != outl)
+		return 0;
+
+	return 1;
+	}
+
+/* Return the session to the pool. The C_EncryptFinal and C_DecryptFinal are
+ * not used. Once a secret key is initialized, it is used until destroyed.
+ */
+static int
+pk11_cipher_cleanup(EVP_CIPHER_CTX *ctx)
+	{
+	PK11_CIPHER_STATE *state = ctx->cipher_data;
+
+	if (state != NULL && state->sp != NULL)
+		{
+		pk11_return_session(state->sp);
+		state->sp = NULL;
+		}
+
+	return 1;
+	}
+
+/* Registered by the ENGINE when used to find out how to deal with
+ * a particular NID in the ENGINE. This says what we'll do at the
+ * top level - note, that list is restricted by what we answer with
+ */
+static int
+pk11_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
+	const int **nids, int nid)
+	{
+	if (!cipher)
+		return (pk11_usable_ciphers(nids));
+
+	switch (nid)
+		{
+		case NID_des_ede3_cbc:
+			*cipher = &pk11_3des_cbc;
+			break;
+		case NID_des_cbc:
+			*cipher = &pk11_des_cbc;
+			break;
+		case NID_aes_128_cbc:
+			*cipher = &pk11_aes_cbc;
+			break;
+		case NID_rc4:
+			*cipher = &pk11_rc4;
+			break;
+		default:
+			*cipher = NULL;
+			break;
+		}
+	return (*cipher != NULL);
+	}
+
+static int
+pk11_engine_digests(ENGINE *e, const EVP_MD **digest,
+	const int **nids, int nid)
+	{
+	if (!digest)
+		return (pk11_usable_digests(nids));
+
+	switch (nid)
+		{
+		case NID_md5:
+			*digest = &pk11_md5; 
+			break;
+		case NID_sha1:
+			*digest = &pk11_sha1; 
+			break;
+		default:
+			*digest = NULL;
+			break;
+		}
+	return (*digest != NULL);
+	}
+
+
+/* Create a secret key object in a PKCS#11 session
+ */
+static CK_OBJECT_HANDLE pk11_get_cipher_key(EVP_CIPHER_CTX *ctx, 
+	const unsigned char *key, CK_KEY_TYPE key_type, PK11_SESSION *sp)
+	{
+	CK_RV rv;
+	CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+	CK_OBJECT_CLASS obj_key = CKO_SECRET_KEY;
+	CK_ULONG ul_key_attr_count = 6;
+	char tmp_buf[20];
+
+	CK_ATTRIBUTE  a_key_template[] =
+		{
+		{CKA_CLASS, (void*) NULL, sizeof(CK_OBJECT_CLASS)},
+		{CKA_KEY_TYPE, (void*) NULL, sizeof(CK_KEY_TYPE)},
+		{CKA_TOKEN, &false, sizeof(false)},
+		{CKA_ENCRYPT, &true, sizeof(true)},
+		{CKA_DECRYPT, &true, sizeof(true)},
+		{CKA_VALUE, (void*) NULL, 0},
+		};
+
+	/* Create secret key object in global_session. All other sessions
+	 * can use the key handles. Here is why:
+	 * OpenSSL will call EncryptInit and EncryptUpdate using a secret key.
+	 * It may then call DecryptInit and DecryptUpdate using the same key.
+	 * To use the same key object, we need to call EncryptFinal with
+	 * a 0 length message. Currently, this does not work for 3DES 
+	 * mechanism. To get around this problem, we close the session and
+	 * then create a new session to use the same key object. When a session
+	 * is closed, all the object handles will be invalid. Thus, create key 
+	 * objects in a global session, an individual session may be closed to
+	 * terminate the active operation.
+	 */
+	CK_SESSION_HANDLE session = global_session;
+	a_key_template[0].pValue = &obj_key;
+	a_key_template[1].pValue = &key_type;
+	a_key_template[5].pValue = (void *) key;
+	a_key_template[5].ulValueLen = (unsigned long) ctx->key_len;
+
+	rv = pFuncList->C_CreateObject(session, 
+		a_key_template, ul_key_attr_count, &h_key);
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_CIPHER_KEY, PK11_R_CREATEOBJECT);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	/* Save the key information used in this session.
+	 * The max can be saved is PK11_KEY_LEN_MAX.
+	 */
+	sp->key_len = ctx->key_len > PK11_KEY_LEN_MAX ? 
+		PK11_KEY_LEN_MAX : ctx->key_len;
+	memcpy(sp->key, key, sp->key_len);
+err:
+
+	return h_key;
+	}
+
+static int
+md_nid_to_pk11(int nid)
+	{
+	int i;
+
+	for (i = 0; i < PK11_DIGEST_MAX; i++)
+		if (digests[i].nid == nid)
+			return (digests[i].id);
+	return (-1);
+	}
+
+static int 
+pk11_digest_init(EVP_MD_CTX *ctx)
+        { 
+	CK_RV rv;
+	CK_MECHANISM mech;
+	int index;
+	PK11_SESSION *sp;
+	PK11_DIGEST *pdp;
+	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
+	
+	state->sp = NULL;
+
+	index = md_nid_to_pk11(ctx->digest->type);
+	if (index < 0 || index >= PK11_DIGEST_MAX)
+		return 0;
+
+	pdp = &digests[index];
+	if ((sp = pk11_get_session()) == NULL)
+		return 0;
+
+	/* at present, no parameter is needed for supported digests */
+	mech.mechanism = pdp->mech_type;
+	mech.pParameter = NULL;
+	mech.ulParameterLen = 0;
+
+	rv = pFuncList->C_DigestInit(sp->session, &mech);
+
+	if (rv != CKR_OK)
+		{
+		char tmp_buf[20];
+		PK11err(PK11_F_DIGEST_INIT, PK11_R_DIGESTINIT);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		pk11_return_session(sp);
+		return 0;
+		}
+
+	state->sp = sp;
+
+	return 1;
+	}
+
+static int 
+pk11_digest_update(EVP_MD_CTX *ctx,const void *data,size_t count)
+        { 
+	CK_RV rv;
+	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
+	
+	/* 0 length message will cause a failure in C_DigestFinal */
+	if (count == 0)
+		return 1;
+
+	if (state == NULL || state->sp == NULL)
+		return 0;
+
+	rv = pFuncList->C_DigestUpdate(state->sp->session, (CK_BYTE *) data,
+		count);
+
+	if (rv != CKR_OK)
+		{
+		char tmp_buf[20];
+		PK11err(PK11_F_DIGEST_UPDATE, PK11_R_DIGESTUPDATE);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		pk11_return_session(state->sp);
+		state->sp = NULL;
+		return 0;
+		}
+
+	return 1;
+	}
+
+static int 
+pk11_digest_final(EVP_MD_CTX *ctx,unsigned char *md)
+        { 
+	CK_RV rv;
+	unsigned long len;
+	PK11_CIPHER_STATE *state = (PK11_CIPHER_STATE *) ctx->md_data;
+	len = ctx->digest->md_size;
+	
+	if (state == NULL || state->sp == NULL)
+		return 0;
+
+	rv = pFuncList->C_DigestFinal(state->sp->session, md, &len);
+
+	if (rv != CKR_OK)
+		{
+		char tmp_buf[20];
+		PK11err(PK11_F_DIGEST_FINAL, PK11_R_DIGESTFINAL);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		pk11_return_session(state->sp);
+		state->sp = NULL;
+		return 0;
+		}
+
+	if (ctx->digest->md_size != len)
+		return 0;
+
+	/* Final is called and digest is returned, so return the session
+	 * to the pool
+	 */
+	pk11_return_session(state->sp);
+	state->sp = NULL;
+
+	return 1;
+	}
+
+static int 
+pk11_digest_copy(EVP_MD_CTX *to,const EVP_MD_CTX *from)
+        { 
+	CK_RV rv;
+	int ret = 0;
+	PK11_CIPHER_STATE *state, *state_to;
+	CK_BYTE_PTR pstate = NULL;
+	CK_ULONG ul_state_len;
+	char tmp_buf[20];
+	
+	/* The copy-from state */
+	state = (PK11_CIPHER_STATE *) from->md_data;
+	if (state == NULL || state->sp == NULL)
+		goto err;
+
+	/* Initialize the copy-to state */
+	if (!pk11_digest_init(to))
+		goto err;
+	state_to = (PK11_CIPHER_STATE *) to->md_data;
+
+	/* Get the size of the operation state of the copy-from session */
+	rv = pFuncList->C_GetOperationState(state->sp->session, NULL, 
+		&ul_state_len);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_DIGEST_COPY, PK11_R_GET_OPERATION_STATE);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+	if (ul_state_len == 0)
+		{
+		goto err;
+		}
+
+	pstate = OPENSSL_malloc(ul_state_len);
+	if (pstate == NULL)
+		{
+		RSAerr(PK11_F_DIGEST_COPY, PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+
+	/* Get the operation state of the copy-from session */
+	rv = pFuncList->C_GetOperationState(state->sp->session, pstate, 
+		&ul_state_len);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_DIGEST_COPY, PK11_R_GET_OPERATION_STATE);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	/* Set the operation state of the copy-to session */
+	rv = pFuncList->C_SetOperationState(state_to->sp->session, pstate, 
+		ul_state_len, 0, 0);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_DIGEST_COPY, PK11_R_SET_OPERATION_STATE);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	ret = 1;
+err:
+	if (pstate != NULL)
+		OPENSSL_free(pstate);
+
+	return ret;
+	}
+
+/* Return any pending session state to the pool */
+static int
+pk11_digest_cleanup(EVP_MD_CTX *ctx)
+	{
+	PK11_CIPHER_STATE *state = ctx->md_data;
+	unsigned char buf[EVP_MAX_MD_SIZE];
+
+	if (state != NULL && state->sp != NULL)
+		{
+		/*
+		 * If state->sp is not NULL then pk11_digest_final() has not
+		 * been called yet. We must call it now to free any memory
+		 * that might have been allocated in the token when
+		 * pk11_digest_init() was called.
+		 */
+		pk11_digest_final(ctx,buf);
+		pk11_return_session(state->sp);
+		state->sp = NULL;
+		}
+
+	return 1;
+	}
+
+/* Check if the new key is the same as the key object in the session.
+ * If the key is the same, no need to create a new key object. Otherwise,
+ * the old key object needs to be destroyed and a new one will be created
+ */
+static void check_new_cipher_key(PK11_SESSION *sp, const unsigned char *key)
+	{
+	if (memcmp(sp->key, key, sp->key_len) != 0)
+		pk11_destroy_cipher_key_objects(sp);
+	}
+
+/* Destroy one or more secret key objects. 
+ */
+static int pk11_destroy_cipher_key_objects(PK11_SESSION *session)
+	{
+	int ret = 0;
+	PK11_SESSION *sp = NULL;
+	PK11_SESSION *local_free_session;
+
+	CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+	if (session)
+		local_free_session = session;
+	else
+		local_free_session = free_session;
+	while ((sp = local_free_session) != NULL)
+		{
+		local_free_session = sp->next;
+
+		if (sp->cipher_key != CK_INVALID_HANDLE)
+			{
+			/* The secret key object is created in the 
+			 * global_session. See pk11_get_cipher_key
+			 */
+			if (pk11_destroy_object(global_session, 
+				sp->cipher_key) == 0)
+				goto err;
+			sp->cipher_key = CK_INVALID_HANDLE;
+			}
+		}
+	ret = 1;
+err:
+	CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+
+	return ret;
+	}
+
+
+/*
+ * Required mechanisms
+ *
+ * CKM_RSA_X_509
+ * CKM_RSA_PKCS
+ * CKM_DSA
+ *
+ * As long as these required mechanisms are met, it will return success. 
+ * Otherwise, it will return failure and the engine initialization will fail. 
+ * The application will then decide whether to use another engine or 
+ * no engine.
+ *
+ * Symmetric ciphers optionally supported
+ *
+ * CKM_DES3_CBC
+ * CKM_DES_CBC
+ * CKM_AES_CBC
+ * CKM_RC4
+ *
+ * Digests optionally supported
+ *
+ * CKM_MD5
+ * CKM_SHA_1
+ */
+
+static int 
+pk11_choose_slot()
+	{
+	CK_SLOT_ID_PTR pSlotList = NULL_PTR;
+	CK_ULONG ulSlotCount = 0;
+	CK_MECHANISM_INFO mech_info;
+	CK_TOKEN_INFO token_info;
+	int i;
+	CK_RV rv;
+	CK_SLOT_ID best_slot_sofar;
+	CK_BBOOL found_candidate_slot = CK_FALSE;
+	int slot_n_cipher = 0;
+	int slot_n_digest = 0;
+	CK_SLOT_ID current_slot = 0;
+	int current_slot_n_cipher = 0;
+	int current_slot_n_digest = 0;
+
+	int local_cipher_nids[PK11_CIPHER_MAX];
+	int local_digest_nids[PK11_DIGEST_MAX];
+	char tmp_buf[20];
+	int retval = 0;
+
+	if (!pk11_auto_slot)
+		return 1;
+
+	/* Get slot list for memory alloction */
+	rv = pFuncList->C_GetSlotList(0, NULL_PTR, &ulSlotCount);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		return retval;
+		}
+
+	if (ulSlotCount == 0) 
+		{
+		PK11err(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST);
+		return retval;
+		}
+
+	pSlotList = OPENSSL_malloc(ulSlotCount * sizeof (CK_SLOT_ID));
+
+	if (pSlotList == NULL) 
+		{
+		RSAerr(PK11_F_CHOOSE_SLOT,PK11_R_MALLOC_FAILURE);
+		return retval;
+		}
+
+	/* Get the slot list for processing */
+	rv = pFuncList->C_GetSlotList(0, pSlotList, &ulSlotCount);
+	if (rv != CKR_OK) 
+		{
+		PK11err(PK11_F_CHOOSE_SLOT, PK11_R_GETSLOTLIST);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		OPENSSL_free(pSlotList);
+		return retval;
+		}
+
+	for (i = 0; i < ulSlotCount; i++) 
+		{
+		CK_BBOOL slot_has_rsa = CK_FALSE;
+		CK_BBOOL slot_has_dsa = CK_FALSE;
+		CK_BBOOL slot_has_dh = CK_FALSE;
+		current_slot = pSlotList[i];
+		current_slot_n_cipher = 0;
+		current_slot_n_digest = 0;
+		memset(local_cipher_nids, 0, sizeof(local_cipher_nids));
+		memset(local_digest_nids, 0, sizeof(local_digest_nids));
+
+#ifdef DEBUG_SLOT_SELECTION
+		fprintf(stderr, "OPENSSL_PKCS#11_ENGINE: checking slot: %d\n",
+		    current_slot);
+#endif
+		/* Check if slot has random support. */
+		rv = pFuncList->C_GetTokenInfo(current_slot, &token_info);
+		if (rv != CKR_OK)
+			continue;
+
+		if (token_info.flags & CKF_RNG)
+			pk11_have_random = CK_TRUE;
+
+		/*
+		 * Check if this slot is capable of signing and
+		 * verifying with CKM_RSA_PKCS.
+		 */
+		rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_RSA_PKCS, 
+			&mech_info);
+
+		if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
+				(mech_info.flags & CKF_VERIFY)))
+			{
+			/*
+			 * Check if this slot is capable of encryption,
+			 * decryption, sign, and verify with CKM_RSA_X_509.
+			 */
+			rv = pFuncList->C_GetMechanismInfo(current_slot,
+			  CKM_RSA_X_509, &mech_info);
+
+			if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
+			    (mech_info.flags & CKF_VERIFY) &&
+			    (mech_info.flags & CKF_ENCRYPT) &&
+			    (mech_info.flags & CKF_VERIFY_RECOVER) &&
+			    (mech_info.flags & CKF_DECRYPT)))
+				slot_has_rsa = CK_TRUE;
+			}
+
+		/*
+		 * Check if this slot is capable of signing and
+		 * verifying with CKM_DSA.
+		 */
+		rv = pFuncList->C_GetMechanismInfo(current_slot, CKM_DSA, 
+			&mech_info);
+		if (rv == CKR_OK && ((mech_info.flags & CKF_SIGN) &&
+		    (mech_info.flags & CKF_VERIFY)))
+			slot_has_dsa = CK_TRUE;
+
+		/*
+		 * Check if this slot is capable of DH key generataion and
+		 * derivation.
+		 */
+		rv = pFuncList->C_GetMechanismInfo(current_slot,
+		  CKM_DH_PKCS_KEY_PAIR_GEN, &mech_info);
+
+		if (rv == CKR_OK && (mech_info.flags & CKF_GENERATE_KEY_PAIR))
+			{    
+			rv = pFuncList->C_GetMechanismInfo(current_slot,
+				CKM_DH_PKCS_DERIVE, &mech_info);
+			if (rv == CKR_OK && (mech_info.flags & CKF_DERIVE))
+				slot_has_dh = CK_TRUE;
+			}
+
+		if (!found_candidate_slot &&
+		    (slot_has_rsa || slot_has_dsa || slot_has_dh))
+			{
+#ifdef DEBUG_SLOT_SELECTION
+			fprintf(stderr,
+			    "OPENSSL_PKCS#11_ENGINE: potential slot: %d\n",
+			    current_slot);
+#endif
+			best_slot_sofar = current_slot;
+			pk11_have_rsa = slot_has_rsa;
+			pk11_have_dsa = slot_has_dsa;
+			pk11_have_dh = slot_has_dh;
+			found_candidate_slot = CK_TRUE;
+#ifdef DEBUG_SLOT_SELECTION
+			fprintf(stderr,
+		    	    "OPENSSL_PKCS#11_ENGINE: best so far slot: %d\n",
+		    	    best_slot_sofar);
+#endif
+			}
+
+		/* Count symmetric cipher support. */
+		if (!pk11_count_symmetric_cipher(current_slot, CKM_DES_CBC,
+				&current_slot_n_cipher, local_cipher_nids,
+				PK11_DES_CBC))
+			continue;
+		if (!pk11_count_symmetric_cipher(current_slot, CKM_DES3_CBC,
+				&current_slot_n_cipher, local_cipher_nids,
+				PK11_DES3_CBC))
+			continue;
+		if (!pk11_count_symmetric_cipher(current_slot, CKM_AES_CBC,
+				&current_slot_n_cipher, local_cipher_nids,
+				PK11_AES_CBC))
+			continue;
+		if (!pk11_count_symmetric_cipher(current_slot, CKM_RC4,
+				&current_slot_n_cipher, local_cipher_nids,
+				PK11_RC4))
+			continue;
+
+		/* Count digest support */
+		if (!pk11_count_digest(current_slot, CKM_MD5,
+				&current_slot_n_digest, local_digest_nids,
+				PK11_MD5))
+			continue;
+		if (!pk11_count_digest(current_slot, CKM_SHA_1,
+				&current_slot_n_digest, local_digest_nids,
+				PK11_SHA1))
+			continue;
+
+		/*
+		 * If the current slot supports more ciphers/digests than 
+		 * the previous best one we change the current best to this one.
+		 * otherwise leave it where it is.
+		 */
+		if (((current_slot_n_cipher > slot_n_cipher) &&
+		    (current_slot_n_digest > slot_n_digest)) &&
+		    ((slot_has_rsa == pk11_have_rsa) &&
+		     (slot_has_dsa == pk11_have_dsa) &&
+		     (slot_has_dh == pk11_have_dh)))
+			{
+			best_slot_sofar = current_slot;
+			slot_n_cipher = current_slot_n_cipher;
+			slot_n_digest = current_slot_n_digest;
+
+			memcpy(cipher_nids, local_cipher_nids, 
+				sizeof(local_cipher_nids));
+			memcpy(digest_nids, local_digest_nids, 
+				sizeof(local_digest_nids));
+			}
+
+		}
+
+	if (found_candidate_slot)
+		{
+		cipher_count = slot_n_cipher;
+		digest_count = slot_n_digest;
+		SLOTID = best_slot_sofar;
+		retval = 1;
+		}
+	else
+		{
+		cipher_count = 0;
+		digest_count = 0;
+		}
+
+#ifdef DEBUG_SLOT_SELECTION
+	fprintf(stderr,
+	  "OPENSSL_PKCS#11_ENGINE: choose slot: %d\n", SLOTID);
+	fprintf(stderr,
+	  "OPENSSL_PKCS#11_ENGINE: pk11_have_rsa %d\n", pk11_have_rsa);
+	fprintf(stderr,
+	  "OPENSSL_PKCS#11_ENGINE: pk11_have_dsa %d\n", pk11_have_dsa);
+	fprintf(stderr,
+	  "OPENSSL_PKCS#11_ENGINE: pk11_have_dh %d\n", pk11_have_dh);
+	fprintf(stderr,
+	  "OPENSSL_PKCS#11_ENGINE: pk11_have_random %d\n", pk11_have_random);
+#endif /* DEBUG_SLOT_SELECTION */
+		
+	if (pSlotList)
+		OPENSSL_free(pSlotList);
+
+	return retval;
+	}
+
+static int pk11_count_symmetric_cipher(int slot_id, CK_MECHANISM_TYPE mech,
+    int *current_slot_n_cipher, int *local_cipher_nids, int id)
+	{
+	CK_MECHANISM_INFO mech_info;
+	CK_RV rv;
+
+	rv = pFuncList->C_GetMechanismInfo(slot_id, mech, &mech_info);
+
+	if (rv != CKR_OK) 
+		return 0;
+
+	if ((mech_info.flags & CKF_ENCRYPT) &&
+			(mech_info.flags & CKF_DECRYPT))
+		{
+		local_cipher_nids[(*current_slot_n_cipher)++] = ciphers[id].nid;
+		}
+
+	return 1;
+	}
+
+
+static int pk11_count_digest(int slot_id, CK_MECHANISM_TYPE mech,
+    int *current_slot_n_digest, int *local_digest_nids, int id)
+	{
+	CK_MECHANISM_INFO mech_info;
+	CK_RV rv;
+
+	rv = pFuncList->C_GetMechanismInfo(slot_id, mech, &mech_info);
+
+	if (rv != CKR_OK) 
+		return 0;
+
+	if (mech_info.flags & CKF_DIGEST)
+		{
+		local_digest_nids[(*current_slot_n_digest)++] = digests[id].nid;
+		}
+
+	return 1;
+	}
+
+
+#endif
+#endif
+
diff -r -u -N openssl-0.9.8g/crypto/engine/hw_pk11_err.c openssl/crypto/engine/hw_pk11_err.c
--- openssl-0.9.8g/crypto/engine/hw_pk11_err.c	1970-01-01 01:00:00.000000000 +0100
+++ openssl/crypto/engine/hw_pk11_err.c	2007-10-25 01:27:09.000000000 +0200
@@ -0,0 +1,233 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
+ * Use is subject to license terms.
+ */
+#pragma ident	"@(#)hw_pk11_err.c	1.2	04/06/22 SMI"
+
+/* crypto/engine/hw_pk11_err.c */
+/* This product includes software developed by the OpenSSL Project for 
+ * use in the OpenSSL Toolkit (http://www.openssl.org/).
+ *
+ * This project also referenced hw_pkcs11-0.9.7b.patch written by 
+ * Afchine Madjlessi.
+ */
+/* ====================================================================
+ * Copyright (c) 2000-2001 The OpenSSL Project.  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. All advertising materials mentioning features or use of this
+ *    software must display the following acknowledgment:
+ *    "This product includes software developed by the OpenSSL Project
+ *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
+ *
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ *    endorse or promote products derived from this software without
+ *    prior written permission. For written permission, please contact
+ *    licensing@OpenSSL.org.
+ *
+ * 5. Products derived from this software may not be called "OpenSSL"
+ *    nor may "OpenSSL" appear in their names without prior written
+ *    permission of the OpenSSL Project.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ *    acknowledgment:
+ *    "This product includes software developed by the OpenSSL Project
+ *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED 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 OpenSSL PROJECT OR
+ * ITS 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.
+ * ====================================================================
+ *
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com).  This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+ *
+ */
+
+#include <stdio.h>
+#include <openssl/err.h>
+#include "hw_pk11_err.h"
+
+/* BEGIN ERROR CODES */
+#ifndef OPENSSL_NO_ERR
+static ERR_STRING_DATA pk11_str_functs[]=
+{
+    {ERR_PACK(0,PK11_F_INIT,0),	            "PK11_INIT"},
+    {ERR_PACK(0,PK11_F_FINISH,0),	    "PK11_FINISH"},
+    {ERR_PACK(0,PK11_F_DESTROY,0),	    "PK11_DESTROY"},
+    {ERR_PACK(0,PK11_F_CTRL,0),	            "PK11_CTRL"},
+    {ERR_PACK(0,PK11_F_RSA_INIT,0),	    "PK11_RSA_INIT"},
+    {ERR_PACK(0,PK11_F_RSA_FINISH,0),	    "PK11_RSA_FINISH"},
+    {ERR_PACK(0,PK11_F_GET_PUB_RSA_KEY,0),  "PK11_GET_PUB_RSA_KEY"},
+    {ERR_PACK(0,PK11_F_GET_PRIV_RSA_KEY,0), "PK11_GET_PRIV_RSA_KEY"},
+    {ERR_PACK(0,PK11_F_RSA_GEN_KEY,0),      "PK11_RSA_GEN_KEY"},
+    {ERR_PACK(0,PK11_F_RSA_PUB_ENC,0),      "PK11_RSA_PUB_ENC"},
+    {ERR_PACK(0,PK11_F_RSA_PRIV_ENC,0),     "PK11_RSA_PRIV_ENC"},
+    {ERR_PACK(0,PK11_F_RSA_PUB_DEC,0),      "PK11_RSA_PUB_DEC"},
+    {ERR_PACK(0,PK11_F_RSA_PRIV_DEC,0),     "PK11_RSA_PRIV_DEC"},
+    {ERR_PACK(0,PK11_F_RSA_SIGN,0),	    "PK11_RSA_SIGN"},
+    {ERR_PACK(0,PK11_F_RSA_VERIFY,0),	    "PK11_RSA_VERIFY"},
+    {ERR_PACK(0,PK11_F_RAND_ADD,0),	    "PK11_RAND_ADD"},
+    {ERR_PACK(0,PK11_F_RAND_BYTES,0),	    "PK11_RAND_BYTES"},
+    {ERR_PACK(0,PK11_F_GET_SESSION,0),      "PK11_GET_SESSION"},
+    {ERR_PACK(0,PK11_F_FREE_SESSION,0),     "PK11_FREE_SESSION"},
+    {ERR_PACK(0,PK11_F_LOAD_PUBKEY,0),      "PK11_LOAD_PUBKEY"},
+    {ERR_PACK(0,PK11_F_LOAD_PRIVKEY,0),     "PK11_LOAD_PRIV_KEY"},
+    {ERR_PACK(0,PK11_F_RSA_PUB_ENC_LOW,0),  "PK11_RSA_PUB_ENC_LOW"},
+    {ERR_PACK(0,PK11_F_RSA_PRIV_ENC_LOW,0), "PK11_RSA_PRIV_ENC_LOW"},
+    {ERR_PACK(0,PK11_F_RSA_PUB_DEC_LOW,0),  "PK11_RSA_PUB_DEC_LOW"},
+    {ERR_PACK(0,PK11_F_RSA_PRIV_DEC_LOW,0), "PK11_RSA_PRIV_DEC_LOW"},
+    {ERR_PACK(0,PK11_F_DSA_SIGN,0),         "PK11_DSA_SIGN"},
+    {ERR_PACK(0,PK11_F_DSA_VERIFY,0),       "PK11_DSA_VERIFY"},
+    {ERR_PACK(0,PK11_F_DSA_INIT,0),         "PK11_DSA_INIT"},
+    {ERR_PACK(0,PK11_F_DSA_FINISH,0),       "PK11_DSA_FINISH"},
+    {ERR_PACK(0,PK11_F_GET_PUB_DSA_KEY,0),  "PK11_GET_PUB_DSA_KEY"},
+    {ERR_PACK(0,PK11_F_GET_PRIV_DSA_KEY,0), "PK11_GET_PRIV_DSA_KEY"},
+    {ERR_PACK(0,PK11_F_DH_INIT,0),          "PK11_DH_INIT"},
+    {ERR_PACK(0,PK11_F_DH_FINISH,0),        "PK11_DH_FINISH"},
+    {ERR_PACK(0,PK11_F_MOD_EXP_DH,0),       "PK11_MOD_EXP_DH"},
+    {ERR_PACK(0,PK11_F_GET_DH_KEY,0),       "PK11_GET_DH_KEY"},
+    {ERR_PACK(0,PK11_F_FREE_ALL_SESSIONS,0),"PK11_FREE_ALL_SESSIONS"},
+    {ERR_PACK(0,PK11_F_SETUP_SESSION,0),    "PK11_SETUP_SESSION"},
+    {ERR_PACK(0,PK11_F_DESTROY_OBJECT,0),   "PK11_DESTROY_OBJECT"},
+    {ERR_PACK(0,PK11_F_CIPHER_INIT,0),      "PK11_CIPHER_INIT"},
+    {ERR_PACK(0,PK11_F_CIPHER_DO_CIPHER,0), "PK11_CIPHER_DO_CIPHER"},
+    {ERR_PACK(0,PK11_F_GET_CIPHER_KEY,0),   "PK11_GET_CIPHER_KEY"},
+    {ERR_PACK(0,PK11_F_DIGEST_INIT,0),      "PK11_DIGEST_INIT"},
+    {ERR_PACK(0,PK11_F_DIGEST_UPDATE,0),    "PK11_DIGEST_UPDATE"},
+    {ERR_PACK(0,PK11_F_DIGEST_FINAL,0),     "PK11_DIGEST_FINAL"},
+    {ERR_PACK(0,PK11_F_CHOOSE_SLOT,0),      "PK11_CHOOSE_SLOT"},
+    {ERR_PACK(0,PK11_F_CIPHER_FINAL,0),     "PK11_CIPHER_FINAL"},
+    {ERR_PACK(0,PK11_F_LIBRARY_INIT,0),     "PK11_LIBRARY_INIT"},
+    {ERR_PACK(0,PK11_F_LOAD,0),             "ENGINE_LOAD_PK11"},
+    {ERR_PACK(0,PK11_F_DH_GEN_KEY,0),       "PK11_DH_GEN_KEY"},
+    {ERR_PACK(0,PK11_F_DH_COMP_KEY,0),      "PK11_DH_COMP_KEY"},
+    {ERR_PACK(0,PK11_F_DIGEST_COPY,0),      "PK11_DIGEST_COPY"},
+    {0,NULL}
+};
+
+static ERR_STRING_DATA pk11_str_reasons[]=
+{
+    {PK11_R_ALREADY_LOADED                 ,"PKCS#11 DSO already loaded"},
+    {PK11_R_DSO_FAILURE                    ,"unable to load PKCS#11 DSO"},
+    {PK11_R_NOT_LOADED                     ,"PKCS#11 DSO not loaded"},
+    {PK11_R_PASSED_NULL_PARAMETER          ,"null parameter passed"},
+    {PK11_R_COMMAND_NOT_IMPLEMENTED        ,"command not implemented"},
+    {PK11_R_INITIALIZE                     ,"C_Initialize failed"},
+    {PK11_R_FINALIZE                       ,"C_Finalize failed"},
+    {PK11_R_GETINFO                        ,"C_GetInfo faile"},
+    {PK11_R_GETSLOTLIST                    ,"C_GetSlotList failed"},
+    {PK11_R_NO_MODULUS_OR_NO_EXPONENT      ,"no modulus or no exponent"},
+    {PK11_R_ATTRIBUT_SENSITIVE_OR_INVALID  ,"attr sensitive or invalid"},
+    {PK11_R_GETATTRIBUTVALUE               ,"C_GetAttributeValue failed"},
+    {PK11_R_NO_MODULUS                     ,"no modulus"},
+    {PK11_R_NO_EXPONENT                    ,"no exponent"},
+    {PK11_R_FINDOBJECTSINIT                ,"C_FindObjectsInit failed"},
+    {PK11_R_FINDOBJECTS                    ,"C_FindObjects failed"},
+    {PK11_R_FINDOBJECTSFINAL               ,"C_FindObjectsFinal failed"},
+    {PK11_R_CREATEOBJECT                   ,"C_CreateObject failed"},
+    {PK11_R_DESTROYOBJECT                  ,"C_DestroyObject failed"},
+    {PK11_R_OPENSESSION                    ,"C_OpenSession failed"},
+    {PK11_R_CLOSESESSION                   ,"C_CloseSession failed"},
+    {PK11_R_ENCRYPTINIT                    ,"C_EncryptInit failed"},
+    {PK11_R_ENCRYPT                        ,"C_Encrypt failed"},
+    {PK11_R_SIGNINIT                       ,"C_SignInit failed"},
+    {PK11_R_SIGN                           ,"C_Sign failed"},
+    {PK11_R_DECRYPTINIT                    ,"C_DecryptInit failed"},
+    {PK11_R_DECRYPT                        ,"C_Decrypt failed"},
+    {PK11_R_VERIFYINIT                     ,"C_VerifyRecover failed"},
+    {PK11_R_VERIFY                         ,"C_Verify failed	"},
+    {PK11_R_VERIFYRECOVERINIT              ,"C_VerifyRecoverInit failed"},
+    {PK11_R_VERIFYRECOVER                  ,"C_VerifyRecover failed"},
+    {PK11_R_GEN_KEY                        ,"C_GenerateKeyPair failed"},
+    {PK11_R_SEEDRANDOM                     ,"C_SeedRandom failed"},
+    {PK11_R_GENERATERANDOM                 ,"C_GenerateRandom failed"},
+    {PK11_R_INVALID_MESSAGE_LENGTH         ,"invalid message length"},
+    {PK11_R_UNKNOWN_ALGORITHM_TYPE         ,"unknown algorithm type"},
+    {PK11_R_UNKNOWN_ASN1_OBJECT_ID         ,"unknown asn1 onject id"},
+    {PK11_R_UNKNOWN_PADDING_TYPE           ,"unknown padding type"},
+    {PK11_R_PADDING_CHECK_FAILED           ,"padding check failed"},
+    {PK11_R_DIGEST_TOO_BIG                 ,"digest too big"},
+    {PK11_R_MALLOC_FAILURE                 ,"malloc failure"},
+    {PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED   ,"ctl command not implemented"},
+    {PK11_R_DATA_GREATER_THAN_MOD_LEN      ,"data is bigger than mod"},
+    {PK11_R_DATA_TOO_LARGE_FOR_MODULUS     ,"data is too larger for mod"},
+    {PK11_R_MISSING_KEY_COMPONENT          ,"a dsa component is missing"},
+    {PK11_R_INVALID_SIGNATURE_LENGTH       ,"invalid signature length"},
+    {PK11_R_INVALID_DSA_SIGNATURE_R        ,"missing r in dsa verify"},
+    {PK11_R_INVALID_DSA_SIGNATURE_S        ,"missing s in dsa verify"},
+    {PK11_R_INCONSISTENT_KEY               ,"inconsistent key type"},
+    {PK11_R_ENCRYPTUPDATE                  ,"C_EncryptUpdate failed"},
+    {PK11_R_DECRYPTUPDATE                  ,"C_DecryptUpdate failed"},
+    {PK11_R_DIGESTINIT                     ,"C_DigestInit failed"},
+    {PK11_R_DIGESTUPDATE                   ,"C_DigestUpdate failed"},
+    {PK11_R_DIGESTFINAL                    ,"C_DigestFinal failed"},
+    {PK11_R_ENCRYPTFINAL                   ,"C_EncryptFinal failed"},
+    {PK11_R_DECRYPTFINAL                   ,"C_DecryptFinal failed"},
+    {PK11_R_NO_PRNG_SUPPORT                ,"Slot does not support PRNG"},
+    {PK11_R_GETTOKENINFO                   ,"C_GetTokenInfo failed"},
+    {PK11_R_DERIVEKEY                      ,"C_DeriveKey failed"},
+    {PK11_R_GET_OPERATION_STATE            ,"C_GetOperationState failed"},
+    {PK11_R_SET_OPERATION_STATE            ,"C_SetOperationState failed"},
+    {0,NULL}
+};
+
+#endif	
+
+static int pk11_lib_error_code=0;
+static int pk11_error_init=1;
+
+static void ERR_load_pk11_strings(void)
+{
+    if (pk11_lib_error_code == 0)
+	pk11_lib_error_code = ERR_get_next_error_library();
+
+    if (pk11_error_init)
+    {
+	pk11_error_init=0;
+#ifndef OPENSSL_NO_ERR
+	ERR_load_strings(pk11_lib_error_code,pk11_str_functs);
+	ERR_load_strings(pk11_lib_error_code,pk11_str_reasons);
+#endif
+    }
+}
+
+static void ERR_unload_pk11_strings(void)
+{
+    if (pk11_error_init == 0)
+    {
+#ifndef OPENSSL_NO_ERR
+	ERR_unload_strings(pk11_lib_error_code,pk11_str_functs);
+	ERR_unload_strings(pk11_lib_error_code,pk11_str_reasons);
+#endif
+	pk11_error_init = 1;
+    }
+}
+
+static void ERR_pk11_error(int function, int reason, char *file, int line)
+{
+    if (pk11_lib_error_code == 0)
+	pk11_lib_error_code=ERR_get_next_error_library();
+    ERR_PUT_error(pk11_lib_error_code,function,reason,file,line);
+}
diff -r -u -N openssl-0.9.8g/crypto/engine/hw_pk11_err.h openssl/crypto/engine/hw_pk11_err.h
--- openssl-0.9.8g/crypto/engine/hw_pk11_err.h	1970-01-01 01:00:00.000000000 +0100
+++ openssl/crypto/engine/hw_pk11_err.h	2008-01-31 16:14:07.000000000 +0100
@@ -0,0 +1,247 @@
+/*
+ * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
+ * Use is subject to license terms.
+ */
+#pragma ident	"@(#)hw_pk11_err.h	1.2	04/06/22 SMI"
+
+/* crypto/engine/hw_pk11_err.h */
+/* This product includes software developed by the OpenSSL Project for 
+ * use in the OpenSSL Toolkit (http://www.openssl.org/).
+ *
+ * This project also referenced hw_pkcs11-0.9.7b.patch written by 
+ * Afchine Madjlessi.
+ */
+/* ====================================================================
+ * Copyright (c) 2000-2001 The OpenSSL Project.  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. All advertising materials mentioning features or use of this
+ *    software must display the following acknowledgment:
+ *    "This product includes software developed by the OpenSSL Project
+ *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
+ *
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ *    endorse or promote products derived from this software without
+ *    prior written permission. For written permission, please contact
+ *    licensing@OpenSSL.org.
+ *
+ * 5. Products derived from this software may not be called "OpenSSL"
+ *    nor may "OpenSSL" appear in their names without prior written
+ *    permission of the OpenSSL Project.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ *    acknowledgment:
+ *    "This product includes software developed by the OpenSSL Project
+ *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED 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 OpenSSL PROJECT OR
+ * ITS 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.
+ * ====================================================================
+ *
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com).  This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+ *
+ */
+
+#ifndef HW_PK11_ERR_H
+#define HW_PK11_ERR_H
+
+/* CRYPTO_LOCK_RSA is defined in OpenSSL for RSA method. Since this pk11
+ * engine replaces RSA method, we may reuse this lock here.
+ */
+#define CRYPTO_LOCK_PK11_ENGINE CRYPTO_LOCK_RSA
+
+static void ERR_load_pk11_strings(void);
+static void ERR_pk11_error(int function, int reason, char *file, int line);
+#define PK11err(f,r) ERR_pk11_error((f),(r),__FILE__,__LINE__)
+
+/* Error codes for the PK11 functions. */
+
+/* Function codes. */
+
+#define PK11_F_INIT 				100
+#define PK11_F_FINISH 				101
+#define PK11_F_DESTROY 				102
+#define PK11_F_CTRL 				103
+#define PK11_F_RSA_INIT 			104
+#define PK11_F_RSA_FINISH 			105
+#define PK11_F_GET_PUB_RSA_KEY 			106
+#define PK11_F_GET_PRIV_RSA_KEY 		107
+#define PK11_F_RSA_GEN_KEY 			108
+#define PK11_F_RSA_PUB_ENC 			109
+#define PK11_F_RSA_PRIV_ENC 			110
+#define PK11_F_RSA_PUB_DEC 			111
+#define PK11_F_RSA_PRIV_DEC 			112
+#define PK11_F_RSA_SIGN 			113
+#define PK11_F_RSA_VERIFY 			114
+#define PK11_F_RAND_ADD 			115
+#define PK11_F_RAND_BYTES 			116
+#define PK11_F_GET_SESSION 			117
+#define PK11_F_FREE_SESSION 			118
+#define PK11_F_LOAD_PUBKEY 			119
+#define PK11_F_LOAD_PRIVKEY 			120
+#define PK11_F_RSA_PUB_ENC_LOW 			121
+#define PK11_F_RSA_PRIV_ENC_LOW 		122
+#define PK11_F_RSA_PUB_DEC_LOW 			123
+#define PK11_F_RSA_PRIV_DEC_LOW 		124
+#define PK11_F_DSA_SIGN				125
+#define PK11_F_DSA_VERIFY			126
+#define PK11_F_DSA_INIT				127
+#define PK11_F_DSA_FINISH			128
+#define PK11_F_GET_PUB_DSA_KEY 			129
+#define PK11_F_GET_PRIV_DSA_KEY 		130
+#define PK11_F_DH_INIT 				131
+#define PK11_F_DH_FINISH 			132
+#define PK11_F_MOD_EXP_DH 			133
+#define PK11_F_GET_DH_KEY 			134
+#define PK11_F_FREE_ALL_SESSIONS		135
+#define PK11_F_SETUP_SESSION			136
+#define PK11_F_DESTROY_OBJECT			137
+#define PK11_F_CIPHER_INIT			138
+#define PK11_F_CIPHER_DO_CIPHER			139
+#define PK11_F_GET_CIPHER_KEY			140
+#define PK11_F_DIGEST_INIT			141
+#define PK11_F_DIGEST_UPDATE			142
+#define PK11_F_DIGEST_FINAL			143
+#define PK11_F_CHOOSE_SLOT			144
+#define PK11_F_CIPHER_FINAL			145
+#define PK11_F_LIBRARY_INIT 			146
+#define PK11_F_LOAD 				147
+#define PK11_F_DH_GEN_KEY			148
+#define PK11_F_DH_COMP_KEY 			149
+#define PK11_F_DIGEST_COPY 			150
+
+/* Reason codes. */
+#define PK11_R_ALREADY_LOADED 			100
+#define PK11_R_DSO_FAILURE 			101
+#define PK11_R_NOT_LOADED 			102
+#define PK11_R_PASSED_NULL_PARAMETER 		103
+#define PK11_R_COMMAND_NOT_IMPLEMENTED 		104
+#define PK11_R_INITIALIZE 			105
+#define PK11_R_FINALIZE 			106
+#define PK11_R_GETINFO 				107
+#define PK11_R_GETSLOTLIST 			108
+#define PK11_R_NO_MODULUS_OR_NO_EXPONENT 	109
+#define PK11_R_ATTRIBUT_SENSITIVE_OR_INVALID 	110
+#define PK11_R_GETATTRIBUTVALUE 		111
+#define PK11_R_NO_MODULUS 			112
+#define PK11_R_NO_EXPONENT 			113
+#define PK11_R_FINDOBJECTSINIT 			114
+#define PK11_R_FINDOBJECTS 			115
+#define PK11_R_FINDOBJECTSFINAL 		116
+#define PK11_R_CREATEOBJECT 			118
+#define PK11_R_DESTROYOBJECT 			119
+#define PK11_R_OPENSESSION 			120
+#define PK11_R_CLOSESESSION 			121
+#define PK11_R_ENCRYPTINIT 			122
+#define PK11_R_ENCRYPT 				123
+#define PK11_R_SIGNINIT 			124
+#define PK11_R_SIGN 				125
+#define PK11_R_DECRYPTINIT 			126
+#define PK11_R_DECRYPT 				127
+#define PK11_R_VERIFYINIT 			128
+#define PK11_R_VERIFY 				129
+#define PK11_R_VERIFYRECOVERINIT 		130
+#define PK11_R_VERIFYRECOVER 			131
+#define PK11_R_GEN_KEY 				132
+#define PK11_R_SEEDRANDOM 			133
+#define PK11_R_GENERATERANDOM 			134
+#define PK11_R_INVALID_MESSAGE_LENGTH 		135
+#define PK11_R_UNKNOWN_ALGORITHM_TYPE 		136
+#define PK11_R_UNKNOWN_ASN1_OBJECT_ID 		137
+#define PK11_R_UNKNOWN_PADDING_TYPE 		138
+#define PK11_R_PADDING_CHECK_FAILED 		139
+#define PK11_R_DIGEST_TOO_BIG 			140
+#define PK11_R_MALLOC_FAILURE 			141
+#define PK11_R_CTRL_COMMAND_NOT_IMPLEMENTED 	142
+#define PK11_R_DATA_GREATER_THAN_MOD_LEN 	143
+#define PK11_R_DATA_TOO_LARGE_FOR_MODULUS 	144
+#define PK11_R_MISSING_KEY_COMPONENT		145
+#define PK11_R_INVALID_SIGNATURE_LENGTH		146
+#define PK11_R_INVALID_DSA_SIGNATURE_R		147
+#define PK11_R_INVALID_DSA_SIGNATURE_S		148
+#define PK11_R_INCONSISTENT_KEY			149
+#define PK11_R_ENCRYPTUPDATE			150
+#define PK11_R_DECRYPTUPDATE			151
+#define PK11_R_DIGESTINIT			152
+#define PK11_R_DIGESTUPDATE			153
+#define PK11_R_DIGESTFINAL			154
+#define PK11_R_ENCRYPTFINAL			155
+#define PK11_R_DECRYPTFINAL			156
+#define PK11_R_NO_PRNG_SUPPORT			157
+#define PK11_R_GETTOKENINFO			158
+#define PK11_R_DERIVEKEY			159
+#define PK11_R_GET_OPERATION_STATE		160
+#define PK11_R_SET_OPERATION_STATE		161
+#define PK11_R_INVALID_PIN			162
+#define PK11_R_TOO_MANY_OBJECTS			163
+#define PK11_R_OBJECT_NOT_FOUND			164
+
+/* This structure encapsulates all reusable information for a PKCS#11
+ * session. A list of this object is created on behalf of the
+ * calling application using an on-demand method. When a new request
+ * comes in, an object will be taken from the list (if there is one)
+ * or a new one is created to handle the request. Note that not all
+ * fields are used for every application. For example, an RSA-only
+ * application only uses the RSA related fields */
+typedef struct PK11_SESSION_st
+        {
+        struct PK11_SESSION_st *next;
+        CK_SESSION_HANDLE       session;        /* PK11 session handle */
+        CK_SESSION_HANDLE       session_cipher; /* PK11 sess handle for ciph */
+        pid_t                   pid;            /* Current process ID */
+        CK_OBJECT_HANDLE        rsa_pub_key;    /* RSA key handle in the sess */
+	CK_OBJECT_HANDLE        rsa_priv_key;   /* RSA private key handle */
+        CK_OBJECT_HANDLE        dsa_pub_key;    /* DSA pub key handle */
+        CK_OBJECT_HANDLE        dsa_priv_key;   /* DSA priv key handle */
+        CK_OBJECT_HANDLE        dh_key;         /* RSA pub key handle for DH */
+        CK_OBJECT_HANDLE        cipher_key;     /* Cipher key handle */
+        RSA                     *rsa;   /* Address of the RSA struct */
+        void                    *dsa;   /* Address of the DSA structure */
+        void                    *dh;    /* Address of the DH */
+        unsigned char           key[24];/* Save the private key here */
+        int                     key_len;/* Saved private key length */
+        int                     encrypt;/* 1/0 for encrypt/decrypt */
+        } PK11_SESSION;
+
+extern PK11_SESSION *pk11_get_session();
+extern void pk11_return_session(PK11_SESSION *sp);
+
+extern int pk11_destroy_rsa_key_objects(PK11_SESSION *session);
+extern int pk11_destroy_dsa_key_objects(PK11_SESSION *session);
+extern int pk11_destroy_dh_key_objects(PK11_SESSION *session);
+
+extern RSA_METHOD *PK11_RSA(void);
+extern DSA_METHOD *PK11_DSA(void);
+extern DH_METHOD *PK11_DH(void);
+
+extern EVP_PKEY *pk11_load_privkey(ENGINE*, const char* pubkey_file,
+        UI_METHOD *ui_method, void *callback_data);
+extern EVP_PKEY *pk11_load_pubkey(ENGINE*, const char* pubkey_file,
+        UI_METHOD *ui_method, void *callback_data);
+
+extern CK_FUNCTION_LIST_PTR pFuncList;
+
+#endif /* HW_PK11_ERR_H */
diff -r -u -N openssl-0.9.8g/crypto/engine/hw_pk11_pub.c openssl/crypto/engine/hw_pk11_pub.c
--- openssl-0.9.8g/crypto/engine/hw_pk11_pub.c	1970-01-01 01:00:00.000000000 +0100
+++ openssl/crypto/engine/hw_pk11_pub.c	2008-03-17 15:15:49.000000000 +0100
@@ -0,0 +1,2616 @@
+/*
+ * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
+ * Use is subject to license terms.
+ */
+#pragma ident	"@(#)hw_pk11_pub.c	1.4	07/05/10 SMI"
+
+/* crypto/engine/hw_pk11_pub.c */
+/* This product includes software developed by the OpenSSL Project for 
+ * use in the OpenSSL Toolkit (http://www.openssl.org/).
+ *
+ * This project also referenced hw_pkcs11-0.9.7b.patch written by 
+ * Afchine Madjlessi.
+ */
+/* ====================================================================
+ * Copyright (c) 2000-2001 The OpenSSL Project.  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. All advertising materials mentioning features or use of this
+ *    software must display the following acknowledgment:
+ *    "This product includes software developed by the OpenSSL Project
+ *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
+ *
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ *    endorse or promote products derived from this software without
+ *    prior written permission. For written permission, please contact
+ *    licensing@OpenSSL.org.
+ *
+ * 5. Products derived from this software may not be called "OpenSSL"
+ *    nor may "OpenSSL" appear in their names without prior written
+ *    permission of the OpenSSL Project.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ *    acknowledgment:
+ *    "This product includes software developed by the OpenSSL Project
+ *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED 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 OpenSSL PROJECT OR
+ * ITS 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.
+ * ====================================================================
+ *
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com).  This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+ *
+ */
+
+#include <stdio.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <openssl/e_os2.h>
+#include <openssl/engine.h>
+#include <openssl/dso.h>
+#include <openssl/err.h>
+#include <openssl/bn.h>
+#include <openssl/pem.h>
+#include <openssl/rsa.h>
+#include <openssl/rand.h>
+#include <openssl/objects.h>
+#include <openssl/x509.h>
+#include <cryptlib.h>
+
+#ifndef OPENSSL_NO_HW
+#ifndef OPENSSL_NO_HW_PK11
+
+#include "cryptoki.h"
+#include "pkcs11.h"
+#include "hw_pk11_err.c"
+
+#ifndef OPENSSL_NO_RSA
+/* RSA stuff */
+static int pk11_RSA_public_encrypt(int flen, const unsigned char *from, 
+	unsigned char *to, RSA *rsa, int padding);
+static int pk11_RSA_private_encrypt(int flen, const unsigned char *from, 
+	unsigned char *to, RSA *rsa, int padding);
+static int pk11_RSA_public_decrypt(int flen, const unsigned char *from, 
+	unsigned char *to, RSA *rsa, int padding);
+static int pk11_RSA_private_decrypt(int flen, const unsigned char *from, 
+	unsigned char *to, RSA *rsa, int padding);
+static int pk11_RSA_init(RSA *rsa);
+static int pk11_RSA_finish(RSA *rsa);
+static int pk11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
+	unsigned char *sigret, unsigned int *siglen, const RSA *rsa);
+static int pk11_RSA_verify(int dtype, const unsigned char *m, 
+	unsigned int m_len, unsigned char *sigbuf, unsigned int siglen, 
+	const RSA *rsa);
+EVP_PKEY *pk11_load_privkey(ENGINE*, const char* pubkey_file,
+	UI_METHOD *ui_method, void *callback_data);
+EVP_PKEY *pk11_load_pubkey(ENGINE*, const char* pubkey_file,
+	UI_METHOD *ui_method, void *callback_data);
+
+static int pk11_RSA_public_encrypt_low(int flen, const unsigned char *from, 
+	unsigned char *to, RSA *rsa);
+static int pk11_RSA_private_encrypt_low(int flen, const unsigned char *from, 
+	unsigned char *to, RSA *rsa);
+static int pk11_RSA_public_decrypt_low(int flen, const unsigned char *from, 
+	unsigned char *to, RSA *rsa);
+static int pk11_RSA_private_decrypt_low(int flen, const unsigned char *from, 
+	unsigned char *to, RSA *rsa);
+
+static CK_OBJECT_HANDLE pk11_get_public_rsa_key(RSA* rsa, PK11_SESSION *sp);
+static CK_OBJECT_HANDLE pk11_get_private_rsa_key(RSA* rsa, 
+	PK11_SESSION *sp);
+#endif
+
+/* DSA stuff */
+#ifndef OPENSSL_NO_DSA
+static int pk11_DSA_init(DSA *dsa);
+static int pk11_DSA_finish(DSA *dsa);
+static DSA_SIG *pk11_dsa_do_sign(const unsigned char *dgst, int dlen, 
+	DSA *dsa);
+static int pk11_dsa_do_verify(const unsigned char *dgst, int dgst_len,
+	DSA_SIG *sig, DSA *dsa);
+
+static CK_OBJECT_HANDLE pk11_get_public_dsa_key(DSA* dsa,
+	PK11_SESSION *sp);
+static CK_OBJECT_HANDLE pk11_get_private_dsa_key(DSA* dsa, 
+	PK11_SESSION *sp);
+#endif
+
+/* DH stuff */
+#ifndef OPENSSL_NO_DH
+static int pk11_DH_init(DH *dh);
+static int pk11_DH_finish(DH *dh);
+static int pk11_DH_generate_key(DH *dh);
+static int pk11_DH_compute_key(unsigned char *key,
+	const BIGNUM *pub_key,DH *dh);
+
+static CK_OBJECT_HANDLE pk11_get_dh_key(DH* dh, PK11_SESSION *sp);
+#endif
+
+static int init_template_value(BIGNUM *bn, CK_VOID_PTR *pValue,
+        CK_ULONG *ulValueLen);
+static void check_new_rsa_key(PK11_SESSION *sp, void *rsa);
+static void check_new_dsa_key(PK11_SESSION *sp, void *dsa);
+static void check_new_dh_key(PK11_SESSION *sp, void *dh);
+static void attr_to_BN(CK_ATTRIBUTE_PTR attr, CK_BYTE attr_data[], BIGNUM **bn);
+
+
+#ifndef OPENSSL_NO_RSA
+/* Our internal RSA_METHOD that we provide pointers to */
+static RSA_METHOD pk11_rsa =
+	{
+	"PKCS#11 RSA method",
+	pk11_RSA_public_encrypt,		/* rsa_pub_encrypt */
+	pk11_RSA_public_decrypt,		/* rsa_pub_decrypt */
+	pk11_RSA_private_encrypt,		/* rsa_priv_encrypt */
+	pk11_RSA_private_decrypt,		/* rsa_priv_decrypt */
+	NULL,					/* rsa_mod_exp */
+	NULL,					/* bn_mod_exp */
+	pk11_RSA_init,				/* init */
+	pk11_RSA_finish,			/* finish */
+	RSA_FLAG_SIGN_VER,			/* flags */
+	NULL,					/* app_data */
+	pk11_RSA_sign,				/* rsa_sign */
+	pk11_RSA_verify/*,*/			/* rsa_verify */
+	};
+
+RSA_METHOD *PK11_RSA(void)
+	{
+	return(&pk11_rsa);
+	}
+#endif
+
+#ifndef OPENSSL_NO_DSA
+/* Our internal DSA_METHOD that we provide pointers to */
+static DSA_METHOD pk11_dsa =
+	{
+	"PKCS#11 DSA method",
+	pk11_dsa_do_sign, 	/* dsa_do_sign */
+	NULL, 			/* dsa_sign_setup */
+	pk11_dsa_do_verify, 	/* dsa_do_verify */
+	NULL,			/* dsa_mod_exp */
+	NULL, 			/* bn_mod_exp */
+	pk11_DSA_init, 		/* init */
+	pk11_DSA_finish, 	/* finish */
+	0, 			/* flags */
+	NULL 			/* app_data */
+	};
+
+DSA_METHOD *PK11_DSA(void)
+	{
+	return(&pk11_dsa);
+	}
+
+#endif
+
+
+#ifndef OPENSSL_NO_DH
+/* Our internal DH_METHOD that we provide pointers to */
+static DH_METHOD pk11_dh =
+	{
+	"PKCS#11 DH method",
+	pk11_DH_generate_key,	/* generate_key */
+	pk11_DH_compute_key,	/* compute_key */
+	NULL,			/* bn_mod_exp */
+	pk11_DH_init,		/* init */
+	pk11_DH_finish,		/* finish */
+	0,			/* flags */
+	NULL			/* app_data */
+	};
+
+DH_METHOD *PK11_DH(void)
+	{
+	return(&pk11_dh);
+	}
+#endif
+
+/* Size of an SSL signature: MD5+SHA1
+ */
+#define SSL_SIG_LENGTH          36
+
+/* Lengths of DSA data and signature
+ */
+#define DSA_DATA_LEN            20
+#define DSA_SIGNATURE_LEN       40
+
+static CK_BBOOL true = TRUE;
+static CK_BBOOL false = FALSE;
+
+#ifndef OPENSSL_NO_RSA
+
+/* Similiar to Openssl to take advantage of the paddings. The goal is to
+ * support all paddings in this engine although PK11 library does not 
+ * support all the paddings used in OpenSSL. 
+ * The input errors should have been checked in the padding functions
+ */
+static int pk11_RSA_public_encrypt(int flen, const unsigned char *from,
+		unsigned char *to, RSA *rsa, int padding)
+	{
+	int i,num=0,r= -1;
+	unsigned char *buf=NULL;
+
+	num=BN_num_bytes(rsa->n);
+	if ((buf=(unsigned char *)OPENSSL_malloc(num)) == NULL)
+		{
+		RSAerr(PK11_F_RSA_PUB_ENC,PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+
+	switch (padding)
+		{
+	case RSA_PKCS1_PADDING:
+		i=RSA_padding_add_PKCS1_type_2(buf,num,from,flen);
+		break;
+#ifndef OPENSSL_NO_SHA
+	case RSA_PKCS1_OAEP_PADDING:
+		i=RSA_padding_add_PKCS1_OAEP(buf,num,from,flen,NULL,0);
+		break;
+#endif
+	case RSA_SSLV23_PADDING:
+		i=RSA_padding_add_SSLv23(buf,num,from,flen);
+		break;
+	case RSA_NO_PADDING:
+		i=RSA_padding_add_none(buf,num,from,flen);
+		break;
+	default:
+		RSAerr(PK11_F_RSA_PUB_ENC,PK11_R_UNKNOWN_PADDING_TYPE);
+		goto err;
+		}
+	if (i <= 0) goto err;
+
+	/* PK11 functions are called here */
+	r = pk11_RSA_public_encrypt_low(num, buf, to, rsa);
+err:
+	if (buf != NULL) 
+		{
+		OPENSSL_cleanse(buf,num);
+		OPENSSL_free(buf);
+		}
+	return(r);
+	}
+
+
+/* Similar to Openssl to take advantage of the paddings. The input errors
+ * should be catched in the padding functions
+ */
+static int pk11_RSA_private_encrypt(int flen, const unsigned char *from,
+	     unsigned char *to, RSA *rsa, int padding)
+	{
+	int i,num=0,r= -1;
+	unsigned char *buf=NULL;
+
+	num=BN_num_bytes(rsa->n);
+	if ((buf=(unsigned char *)OPENSSL_malloc(num)) == NULL)
+		{
+		RSAerr(PK11_F_RSA_PRIV_ENC,PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+
+	switch (padding)
+		{
+	case RSA_PKCS1_PADDING:
+		i=RSA_padding_add_PKCS1_type_1(buf,num,from,flen);
+		break;
+	case RSA_NO_PADDING:
+		i=RSA_padding_add_none(buf,num,from,flen);
+		break;
+	case RSA_SSLV23_PADDING:
+	default:
+		RSAerr(PK11_F_RSA_PRIV_ENC,PK11_R_UNKNOWN_PADDING_TYPE);
+		goto err;
+		}
+	if (i <= 0) goto err;
+
+	/* PK11 functions are called here */
+	r=pk11_RSA_private_encrypt_low(num, buf, to, rsa);
+err:
+	if (buf != NULL)
+		{
+		OPENSSL_cleanse(buf,num);
+		OPENSSL_free(buf);
+		}
+	return(r);
+	}
+
+/* Similar to Openssl. Input errors are also checked here
+ */
+static int pk11_RSA_private_decrypt(int flen, const unsigned char *from,
+	     unsigned char *to, RSA *rsa, int padding)
+	{
+	BIGNUM f;
+	int j,num=0,r= -1;
+	unsigned char *p;
+	unsigned char *buf=NULL;
+
+	BN_init(&f);
+
+	num=BN_num_bytes(rsa->n);
+
+	if ((buf=(unsigned char *)OPENSSL_malloc(num)) == NULL)
+		{
+		RSAerr(PK11_F_RSA_PRIV_DEC,PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+
+	/* This check was for equality but PGP does evil things
+	 * and chops off the top '0' bytes */
+	if (flen > num)
+		{
+		RSAerr(PK11_F_RSA_PRIV_DEC,
+			PK11_R_DATA_GREATER_THAN_MOD_LEN);
+		goto err;
+		}
+
+	/* make data into a big number */
+	if (BN_bin2bn(from,(int)flen,&f) == NULL) goto err;
+
+	if (BN_ucmp(&f, rsa->n) >= 0)
+		{
+		RSAerr(PK11_F_RSA_PRIV_DEC,
+			PK11_R_DATA_TOO_LARGE_FOR_MODULUS);
+		goto err;
+		}
+
+	/* PK11 functions are called here */
+	r = pk11_RSA_private_decrypt_low(flen, from, buf, rsa);
+
+	/* PK11 CKM_RSA_X_509 mechanism pads 0's at the beginning.
+	 * Needs to skip these 0's paddings here */
+	for (j = 0; j < r; j++)
+		if (buf[j] != 0)
+			break;
+
+	p = buf + j;
+	j = r - j;  /* j is only used with no-padding mode */
+
+	switch (padding)
+		{
+	case RSA_PKCS1_PADDING:
+		r=RSA_padding_check_PKCS1_type_2(to,num,p,j,num);
+		break;
+#ifndef OPENSSL_NO_SHA
+	case RSA_PKCS1_OAEP_PADDING:
+		r=RSA_padding_check_PKCS1_OAEP(to,num,p,j,num,NULL,0);
+		break;
+#endif
+ 	case RSA_SSLV23_PADDING:
+		r=RSA_padding_check_SSLv23(to,num,p,j,num);
+		break;
+	case RSA_NO_PADDING:
+		r=RSA_padding_check_none(to,num,p,j,num);
+		break;
+	default:
+		RSAerr(PK11_F_RSA_PRIV_DEC,PK11_R_UNKNOWN_PADDING_TYPE);
+		goto err;
+		}
+	if (r < 0)
+		RSAerr(PK11_F_RSA_PRIV_DEC,PK11_R_PADDING_CHECK_FAILED);
+
+err:
+	BN_clear_free(&f);
+	if (buf != NULL)
+		{
+		OPENSSL_cleanse(buf,num);
+		OPENSSL_free(buf);
+		}
+	return(r);
+	}
+
+/* Similar to Openssl. Input errors are also checked here
+ */
+static int pk11_RSA_public_decrypt(int flen, const unsigned char *from,
+	     unsigned char *to, RSA *rsa, int padding)
+	{
+	BIGNUM f;
+	int i,num=0,r= -1;
+	unsigned char *p;
+	unsigned char *buf=NULL;
+
+	BN_init(&f);
+	num=BN_num_bytes(rsa->n);
+	buf=(unsigned char *)OPENSSL_malloc(num);
+	if (buf == NULL)
+		{
+		RSAerr(PK11_F_RSA_PUB_DEC,PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+
+	/* This check was for equality but PGP does evil things
+	 * and chops off the top '0' bytes */
+	if (flen > num)
+		{
+		RSAerr(PK11_F_RSA_PUB_DEC,PK11_R_DATA_GREATER_THAN_MOD_LEN);
+		goto err;
+		}
+
+	if (BN_bin2bn(from,flen,&f) == NULL) goto err;
+
+	if (BN_ucmp(&f, rsa->n) >= 0)
+		{
+		RSAerr(PK11_F_RSA_PUB_DEC,
+			PK11_R_DATA_TOO_LARGE_FOR_MODULUS);
+		goto err;
+		}
+
+	/* PK11 functions are called here */
+	r = pk11_RSA_public_decrypt_low(flen, from, buf, rsa);
+
+	/* PK11 CKM_RSA_X_509 mechanism pads 0's at the beginning.
+	 * Needs to skip these 0's here */
+	for (i = 0; i < r; i++)
+		if (buf[i] != 0)
+			break;
+
+	p = buf + i;
+	i = r - i;  /* i is only used with no-padding mode */
+
+	switch (padding)
+		{
+	case RSA_PKCS1_PADDING:
+		r=RSA_padding_check_PKCS1_type_1(to,num,p,i,num);
+		break;
+	case RSA_NO_PADDING:
+		r=RSA_padding_check_none(to,num,p,i,num);
+		break;
+	default:
+		RSAerr(PK11_F_RSA_PUB_DEC,PK11_R_UNKNOWN_PADDING_TYPE);
+		goto err;
+		}
+	if (r < 0)
+		RSAerr(PK11_F_RSA_PUB_DEC,PK11_R_PADDING_CHECK_FAILED);
+
+err:
+	BN_clear_free(&f);
+	if (buf != NULL)
+		{
+		OPENSSL_cleanse(buf,num);
+		OPENSSL_free(buf);
+		}
+	return(r);
+	}
+
+/* This function implements RSA public encryption using C_EncryptInit and
+ * C_Encrypt pk11 interfaces. Note that the CKM_RSA_X_509 is used here.
+ * The calling function allocated sufficient memory in "to" to store results.
+ */
+static int pk11_RSA_public_encrypt_low(int flen,
+	const unsigned char *from, unsigned char *to, RSA *rsa)
+	{
+	CK_ULONG bytes_encrypted=flen;
+	int retval = -1;
+	CK_RV rv;
+	CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
+	CK_MECHANISM *p_mech = &mech_rsa;
+	CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
+	PK11_SESSION *sp;
+	char tmp_buf[20];
+	
+	if ((sp = pk11_get_session()) == NULL)
+		return -1;
+
+	check_new_rsa_key(sp, (void *) rsa);
+	
+	h_pub_key = sp->rsa_pub_key;
+	if (h_pub_key == CK_INVALID_HANDLE)
+		h_pub_key = sp->rsa_pub_key = 
+			pk11_get_public_rsa_key(rsa, sp);
+
+	if (h_pub_key != CK_INVALID_HANDLE)
+		{
+		rv = pFuncList->C_EncryptInit(sp->session, p_mech, 
+			h_pub_key);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_RSA_PUB_ENC_LOW, 
+				PK11_R_ENCRYPTINIT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			pk11_return_session(sp);
+			return -1;
+			}
+	
+		rv = pFuncList->C_Encrypt(sp->session, 
+			(unsigned char *)from, flen, to, &bytes_encrypted);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_RSA_PUB_ENC_LOW, PK11_R_ENCRYPT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			pk11_return_session(sp);
+			return -1;
+			}
+		retval = bytes_encrypted;
+		}
+	
+	pk11_return_session(sp);
+	return retval;
+	}
+
+
+/* This function implements RSA private encryption using C_SignInit and 
+ * C_Sign pk11 APIs. Note that CKM_RSA_X_509 is used here.
+ * The calling function allocated sufficient memory in "to" to store results.
+ */
+static int pk11_RSA_private_encrypt_low(int flen,
+	const unsigned char *from, unsigned char *to, RSA *rsa)
+	{
+	CK_ULONG ul_sig_len=flen;
+	int retval = -1;
+	CK_RV rv;
+	CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
+	CK_MECHANISM *p_mech = &mech_rsa;
+	CK_OBJECT_HANDLE h_priv_key= CK_INVALID_HANDLE;
+	PK11_SESSION *sp;
+	char tmp_buf[20];
+	
+	if ((sp = pk11_get_session()) == NULL)
+		return -1;
+	
+	check_new_rsa_key(sp, (void *) rsa);
+	
+	h_priv_key = sp->rsa_priv_key;
+	if (h_priv_key == CK_INVALID_HANDLE)
+		h_priv_key = sp->rsa_priv_key = 
+			pk11_get_private_rsa_key(rsa, sp);
+	
+	if (h_priv_key != CK_INVALID_HANDLE)
+		{
+		rv = pFuncList->C_SignInit(sp->session, p_mech, 
+			h_priv_key);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_RSA_PRIV_ENC_LOW, PK11_R_SIGNINIT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			pk11_return_session(sp);
+			return -1;
+			}
+	
+		rv = pFuncList->C_Sign(sp->session, 
+			(unsigned char *)from, flen, to, &ul_sig_len);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_RSA_PRIV_ENC_LOW, PK11_R_SIGN);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			pk11_return_session(sp);
+			return -1;
+			}
+
+		retval = ul_sig_len;
+		}
+	
+	pk11_return_session(sp);
+	return retval;
+	}
+
+
+/* This function implements RSA private decryption using C_DecryptInit and
+ * C_Decrypt pk11 APIs. Note that CKM_RSA_X_509 mechanism is used here.
+ * The calling function allocated sufficient memory in "to" to store results.
+ */
+static int pk11_RSA_private_decrypt_low(int flen,
+	const unsigned char *from, unsigned char *to, RSA *rsa)
+	{
+	CK_ULONG bytes_decrypted = flen;
+	int retval = -1;
+	CK_RV rv;
+	CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
+	CK_MECHANISM *p_mech = &mech_rsa;
+	CK_OBJECT_HANDLE h_priv_key;
+	PK11_SESSION *sp;
+	char tmp_buf[20];
+	
+	if ((sp = pk11_get_session()) == NULL)
+		return -1;
+	
+	check_new_rsa_key(sp, (void *) rsa);
+	
+	h_priv_key = sp->rsa_priv_key;
+	if (h_priv_key == CK_INVALID_HANDLE)
+		h_priv_key = sp->rsa_priv_key = 
+			pk11_get_private_rsa_key(rsa, sp);
+
+	if (h_priv_key != CK_INVALID_HANDLE)
+		{
+		rv = pFuncList->C_DecryptInit(sp->session, p_mech, 
+			h_priv_key);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_RSA_PRIV_DEC_LOW, 
+				PK11_R_DECRYPTINIT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			pk11_return_session(sp);
+			return -1;
+			}
+	
+		rv = pFuncList->C_Decrypt(sp->session, 
+			(unsigned char *)from, flen, to, &bytes_decrypted);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_RSA_PRIV_DEC_LOW, PK11_R_DECRYPT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			pk11_return_session(sp);
+			return -1;
+			}
+		retval = bytes_decrypted;
+		}
+
+	pk11_return_session(sp);
+	return retval;
+	}
+
+
+/* This function implements RSA public decryption using C_VerifyRecoverInit 
+ * and C_VerifyRecover pk11 APIs. Note that CKM_RSA_X_509 is used here.
+ * The calling function allocated sufficient memory in "to" to store results.
+ */
+static int pk11_RSA_public_decrypt_low(int flen,
+	const unsigned char *from, unsigned char *to, RSA *rsa)
+	{
+	CK_ULONG bytes_decrypted = flen;
+	int retval = -1;
+	CK_RV rv;
+	CK_MECHANISM mech_rsa = {CKM_RSA_X_509, NULL, 0};
+	CK_MECHANISM *p_mech = &mech_rsa;
+	CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
+	PK11_SESSION *sp;
+	char tmp_buf[20];
+	
+	if ((sp = pk11_get_session()) == NULL)
+		return -1;
+	
+	check_new_rsa_key(sp, (void *) rsa);
+	
+	h_pub_key = sp->rsa_pub_key;
+	if (h_pub_key == CK_INVALID_HANDLE)
+		h_pub_key = sp->rsa_pub_key = 
+			pk11_get_public_rsa_key(rsa, sp);
+
+	if (h_pub_key != CK_INVALID_HANDLE)
+		{	
+		rv = pFuncList->C_VerifyRecoverInit(sp->session, 
+			p_mech, h_pub_key);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_RSA_PUB_DEC_LOW, 
+				PK11_R_VERIFYRECOVERINIT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			pk11_return_session(sp);
+			return -1;
+			}
+	
+		rv = pFuncList->C_VerifyRecover(sp->session, 
+			(unsigned char *)from, flen, to, &bytes_decrypted);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_RSA_PUB_DEC_LOW, 
+				PK11_R_VERIFYRECOVER);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			pk11_return_session(sp);
+			return -1;
+			}
+		retval = bytes_decrypted;
+		}
+
+	pk11_return_session(sp);
+	return retval;
+	}
+
+
+static int pk11_RSA_init(RSA *rsa)
+	{
+	/* This flag in the RSA_METHOD enables the new rsa_sign, 
+	 * rsa_verify functions. See rsa.h for details. */
+	rsa->flags |= RSA_FLAG_SIGN_VER;
+
+	return 1;
+	}
+
+
+static int pk11_RSA_finish(RSA *rsa)
+	{
+	if (rsa->_method_mod_n != NULL)
+		BN_MONT_CTX_free(rsa->_method_mod_n);
+	if (rsa->_method_mod_p != NULL)
+		BN_MONT_CTX_free(rsa->_method_mod_p);
+	if (rsa->_method_mod_q != NULL)
+		BN_MONT_CTX_free(rsa->_method_mod_q);
+	
+	return pk11_destroy_rsa_key_objects(NULL);
+	}
+
+
+/* Standard engine interface function. Majority codes here are from 
+ * rsa/rsa_sign.c. We replaced the decrypt function call by C_Sign of PKCS#11.
+ * See more details in rsa/rsa_sign.c */
+static int pk11_RSA_sign(int type, const unsigned char *m, unsigned int m_len,
+	unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
+	{
+	X509_SIG sig;
+	ASN1_TYPE parameter;
+	int i,j;
+	unsigned char *p,*s = NULL;
+	X509_ALGOR algor;
+	ASN1_OCTET_STRING digest;
+	CK_RV rv;
+	CK_MECHANISM mech_rsa = {CKM_RSA_PKCS, NULL, 0};
+	CK_MECHANISM *p_mech = &mech_rsa;
+	CK_OBJECT_HANDLE h_priv_key;
+	PK11_SESSION *sp = NULL;
+	int ret = 0;
+	char tmp_buf[20];
+	unsigned long ulsiglen;
+
+	/* Encode the digest */
+	/* Special case: SSL signature, just check the length */
+	if (type == NID_md5_sha1)
+		{
+		if (m_len != SSL_SIG_LENGTH)
+			{
+			PK11err(PK11_F_RSA_SIGN, 
+				PK11_R_INVALID_MESSAGE_LENGTH);
+			goto err;
+			}
+		i = SSL_SIG_LENGTH;
+		s = (unsigned char *)m;
+		}
+	else
+		{
+		sig.algor= &algor;
+		sig.algor->algorithm=OBJ_nid2obj(type);
+		if (sig.algor->algorithm == NULL)
+			{
+			PK11err(PK11_F_RSA_SIGN, 
+				PK11_R_UNKNOWN_ALGORITHM_TYPE);
+			goto err;
+			}
+		if (sig.algor->algorithm->length == 0)
+			{
+			PK11err(PK11_F_RSA_SIGN, 
+				PK11_R_UNKNOWN_ASN1_OBJECT_ID);
+			goto err;
+			}
+		parameter.type=V_ASN1_NULL;
+		parameter.value.ptr=NULL;
+		sig.algor->parameter= &parameter;
+	
+		sig.digest= &digest;
+		sig.digest->data=(unsigned char *)m;
+		sig.digest->length=m_len;
+	
+		i=i2d_X509_SIG(&sig,NULL);
+		}
+	
+	j=RSA_size(rsa);
+	if ((i-RSA_PKCS1_PADDING) > j)
+		{
+		PK11err(PK11_F_RSA_SIGN, PK11_R_DIGEST_TOO_BIG);
+		goto err;
+		}
+	
+	if (type != NID_md5_sha1)
+		{
+		s=(unsigned char *)OPENSSL_malloc((unsigned int)j+1);
+		if (s == NULL)
+			{
+			PK11err(PK11_F_RSA_SIGN, PK11_R_MALLOC_FAILURE);
+			goto err;
+			}
+		p=s;
+		i2d_X509_SIG(&sig,&p);
+		}
+	
+	if ((sp = pk11_get_session()) == NULL)
+		goto err;
+
+	check_new_rsa_key(sp, (void *) rsa);
+	
+	h_priv_key = sp->rsa_priv_key;
+	if (h_priv_key == CK_INVALID_HANDLE)
+		h_priv_key = sp->rsa_priv_key = 
+			pk11_get_private_rsa_key((RSA *)rsa, sp);
+
+	if (h_priv_key != CK_INVALID_HANDLE)
+		{
+		rv = pFuncList->C_SignInit(sp->session, p_mech, h_priv_key);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_RSA_SIGN, PK11_R_SIGNINIT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+
+		ulsiglen = j;
+		rv = pFuncList->C_Sign(sp->session, s, i, sigret, 
+			(CK_ULONG_PTR) &ulsiglen);
+		*siglen = ulsiglen;
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_RSA_SIGN, PK11_R_SIGN);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+		ret = 1;
+		}
+
+err:
+	if (type != NID_md5_sha1)
+		{
+		memset(s,0,(unsigned int)j+1);
+		OPENSSL_free(s);
+		}
+	
+	pk11_return_session(sp);
+	return ret;
+	}
+
+static int pk11_RSA_verify(int type, const unsigned char *m,
+	unsigned int m_len, unsigned char *sigbuf, unsigned int siglen,
+	const RSA *rsa)
+	{
+	X509_SIG sig;
+	ASN1_TYPE parameter;
+	int i,j;
+	unsigned char *p,*s = NULL;
+	X509_ALGOR algor;
+	ASN1_OCTET_STRING digest;
+	CK_RV rv;
+	CK_MECHANISM mech_rsa = {CKM_RSA_PKCS, NULL, 0};
+	CK_MECHANISM *p_mech = &mech_rsa;
+	CK_OBJECT_HANDLE h_pub_key;
+	PK11_SESSION *sp = NULL;
+	int ret = 0;
+	char tmp_buf[20];
+
+	/* Encode the digest	*/
+	/* Special case: SSL signature, just check the length */
+	if (type == NID_md5_sha1)
+		{
+		if (m_len != SSL_SIG_LENGTH)
+			{
+			PK11err(PK11_F_RSA_VERIFY, 
+				PK11_R_INVALID_MESSAGE_LENGTH);
+			goto err;
+			}
+		i = SSL_SIG_LENGTH;
+		s = (unsigned char *)m;
+		}
+	else
+		{
+		sig.algor= &algor;
+		sig.algor->algorithm=OBJ_nid2obj(type);
+		if (sig.algor->algorithm == NULL)
+			{
+			PK11err(PK11_F_RSA_VERIFY, 
+				PK11_R_UNKNOWN_ALGORITHM_TYPE);
+			goto err;
+			}
+		if (sig.algor->algorithm->length == 0)
+			{
+			PK11err(PK11_F_RSA_VERIFY, 
+				PK11_R_UNKNOWN_ASN1_OBJECT_ID);
+			goto err;
+			}
+		parameter.type=V_ASN1_NULL;
+		parameter.value.ptr=NULL;
+		sig.algor->parameter= &parameter;
+		sig.digest= &digest;
+		sig.digest->data=(unsigned char *)m;
+		sig.digest->length=m_len;
+		i=i2d_X509_SIG(&sig,NULL);
+		}
+	
+	j=RSA_size(rsa);
+	if ((i-RSA_PKCS1_PADDING) > j)
+		{
+		PK11err(PK11_F_RSA_VERIFY, PK11_R_DIGEST_TOO_BIG);
+		goto err;
+		}
+	
+	if (type != NID_md5_sha1)
+		{
+		s=(unsigned char *)OPENSSL_malloc((unsigned int)j+1);
+		if (s == NULL)
+			{
+			PK11err(PK11_F_RSA_VERIFY, PK11_R_MALLOC_FAILURE);
+			goto err;
+			}
+		p=s;
+		i2d_X509_SIG(&sig,&p);
+		}
+	
+	if ((sp = pk11_get_session()) == NULL)
+		goto err;
+	
+	check_new_rsa_key(sp, (void *) rsa);
+	
+	h_pub_key = sp->rsa_pub_key;
+	if (h_pub_key == CK_INVALID_HANDLE)
+		h_pub_key = sp->rsa_pub_key = 
+			pk11_get_public_rsa_key((RSA *)rsa, sp);
+
+	if (h_pub_key != CK_INVALID_HANDLE)
+		{
+		rv = pFuncList->C_VerifyInit(sp->session, p_mech, 
+			h_pub_key);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_RSA_VERIFY, PK11_R_VERIFYINIT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+		rv = pFuncList->C_Verify(sp->session, s, i, sigbuf, 
+			(CK_ULONG)siglen);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_RSA_VERIFY, PK11_R_VERIFY);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+		ret = 1;
+		}
+
+err:
+	if (type != NID_md5_sha1)
+		{
+		memset(s,0,(unsigned int)siglen);
+		OPENSSL_free(s);
+		}
+
+	pk11_return_session(sp);
+	return ret;
+	}
+
+static int hndidx_rsa = -1;
+
+struct key_info {
+	CK_OBJECT_HANDLE handle;
+	CK_SESSION_HANDLE session;
+};
+
+/* Destroy the object when the last reference to it has gone.
+ */
+static void hndidx_free(void *obj, void *item, CRYPTO_EX_DATA *ad,
+			int ind, long argl, void *argp)
+{
+	struct key_info *key_info = item;
+	CK_RV rv;
+	char tmp_buf[20];
+
+	if (key_info != NULL)
+		{
+                rv = pFuncList->C_DestroyObject(key_info->session,
+						key_info->handle);
+                if (rv != CKR_OK)
+                        {
+                        PK11err(PK11_F_DESTROY_OBJECT, PK11_R_DESTROYOBJECT);
+                        snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+                        ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+                        }
+		free(item);
+		}
+}
+
+EVP_PKEY *pk11_load_privkey(ENGINE* e, const char* privkey_file,
+	UI_METHOD *ui_method, void *callback_data)
+	{
+	EVP_PKEY *pkey=NULL;
+	FILE *privkey;
+	CK_OBJECT_HANDLE  h_priv_key = CK_INVALID_HANDLE;
+	RSA *rsa;
+	PK11_SESSION *sp;
+	/* everything else below needed for key by reference extension */
+	char tmp_buf[20];
+	CK_RV rv;
+	CK_ULONG objcnt = 0;
+	CK_BBOOL is_token = TRUE;
+	CK_BYTE attr_data[2][1024];
+	CK_OBJECT_CLASS key_class = CKO_PRIVATE_KEY;
+	CK_OBJECT_HANDLE ks_key = CK_INVALID_HANDLE;	/* key in keystore */
+	struct key_info *key_info = NULL; 
+	extern char *pk11_pin;
+
+	/* we look for private keys only */
+	CK_ATTRIBUTE search_templ[] =
+		{
+		{CKA_TOKEN, &is_token, sizeof(is_token)},
+		{CKA_CLASS, &key_class, sizeof(key_class)},
+		{CKA_LABEL, NULL, 0}
+		};
+
+	/* these attributes are needed to initialize OpenSSL RSA structure */
+	CK_ATTRIBUTE get_templ[] =
+		{
+		{CKA_MODULUS, (void *)attr_data[0], 1024},	    /* n */
+		{CKA_PUBLIC_EXPONENT, (void *)attr_data[1], 1024},  /* e */
+		};
+
+	if ((sp = pk11_get_session()) == NULL)
+		return NULL;
+
+	/*
+	 * Use simple scheme "pkcs11:<KEY_LABEL>" for now.
+	 */
+	if (strstr(privkey_file, "pkcs11:") == privkey_file)
+		{
+		search_templ[2].pValue = strstr(privkey_file, ":") + 1;
+		search_templ[2].ulValueLen = strlen(search_templ[2].pValue);
+
+		if (pk11_pin == NULL)
+#ifndef OPENCRYPTOKI
+			pk11_pin = getpassphrase("Enter PIN: ");
+#else
+			pk11_pin = getpass("Enter PIN: ");
+#endif
+		if ((rv = pFuncList->C_Login(sp->session, CKU_USER, (CK_UTF8CHAR*)pk11_pin,
+		    strlen(pk11_pin))) != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN)
+			{
+			fprintf(stderr, "C_Login -> %lx\n", rv);
+			PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_INVALID_PIN);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+
+		CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+		if ((rv = pFuncList->C_FindObjectsInit(sp->session,
+		    search_templ, 3)) != CKR_OK)
+			{
+			CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+			PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_FINDOBJECTSINIT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+
+		rv = pFuncList->C_FindObjects(sp->session, &ks_key, 1, &objcnt);
+		if (rv != CKR_OK)
+			{
+			CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+			PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_FINDOBJECTS);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+
+		if (objcnt > 1)
+			{
+			CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+			PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_TOO_MANY_OBJECTS);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lu", objcnt);
+			ERR_add_error_data(2,
+				"PK11 too many objects:", tmp_buf);
+			goto err;
+			}
+
+		if (objcnt != 1)
+			{
+			CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+			PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_OBJECT_NOT_FOUND);
+			ERR_add_error_data(1, "PK11 object not found");
+			goto err;
+			}
+
+		(void) pFuncList->C_FindObjectsFinal(sp->session);
+		CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+
+		if (hndidx_rsa == -1)
+			hndidx_rsa = RSA_get_ex_new_index(0,
+				        "pkcs11 RSA HSM key handle",
+					NULL, NULL, hndidx_free);
+
+		key_info = malloc(sizeof(struct key_info));
+		if (key_info == NULL)
+			goto err;
+
+		pkey = EVP_PKEY_new();
+		if (pkey == NULL)
+			goto err;
+
+		rsa = RSA_new();
+		if (rsa == NULL) {
+			EVP_PKEY_free(pkey);
+			pkey = NULL;
+			goto err;
+		}
+		EVP_PKEY_set1_RSA(pkey, rsa);
+
+		if ((rv = pFuncList->C_GetAttributeValue(sp->session, ks_key,
+		    get_templ, 2)) != CKR_OK)
+			{
+			PK11err(PK11_F_LOAD_PRIVKEY, PK11_R_GETATTRIBUTVALUE);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			EVP_PKEY_free(pkey);
+			pkey = NULL;
+			goto err;
+			}
+
+		/*
+		 * Now we have to initialize an OpenSSL RSA structure,
+		 * everything else is 0 or NULL.
+		 */
+		rsa->meth = &pk11_rsa;
+		rsa->engine = e;
+		rsa->references = 2;
+		rsa->flags = RSA_FLAG_SIGN_VER | RSA_FLAG_EXT_PKEY;
+		key_info->handle = ks_key;
+		key_info->session = sp->session;
+		RSA_set_ex_data(rsa, hndidx_rsa, key_info);
+		key_info = NULL;
+		sp->rsa = rsa;
+		sp->rsa_priv_key = ks_key;
+
+		attr_to_BN(&get_templ[0], attr_data[0], &rsa->n);
+#ifdef OPENCRYPTOKI
+		/* openCryptoki bug workaround */
+		if (get_templ[1].ulValueLen == 0) {
+			get_templ[1].ulValueLen = 1;
+			attr_data[1][0] = 3;
+		}
+#endif
+		attr_to_BN(&get_templ[1], attr_data[1], &rsa->e);
+		}
+	else if ((privkey=fopen(privkey_file,"r")) != NULL)
+		{
+		pkey = PEM_read_PrivateKey(privkey, NULL, NULL, NULL);
+		fclose(privkey);
+		if (pkey)
+			{
+			rsa = EVP_PKEY_get1_RSA(pkey);
+
+			if (rsa)
+				{
+				check_new_rsa_key(sp, (void *) rsa);
+	
+				h_priv_key = pk11_get_private_rsa_key(rsa,
+				sp);
+			if (h_priv_key == CK_INVALID_HANDLE)
+				{
+				EVP_PKEY_free(pkey);
+				pkey = NULL;
+				}
+			}
+		else
+			{
+			EVP_PKEY_free(pkey);
+			pkey = NULL;
+			}
+		}
+	}
+
+err:
+	if (key_info != NULL)
+		free(key_info);
+	pk11_return_session(sp);
+	return(pkey);
+	}
+
+EVP_PKEY *pk11_load_pubkey(ENGINE* e, const char* pubkey_file,
+	UI_METHOD *ui_method, void *callback_data)
+	{
+	EVP_PKEY *pkey=NULL;
+	FILE *pubkey;
+	CK_OBJECT_HANDLE  h_pub_key = CK_INVALID_HANDLE;
+	RSA *rsa;
+	PK11_SESSION *sp;
+	/* everything else below needed for key by reference extension */
+	char tmp_buf[20];
+	CK_RV rv;
+	CK_ULONG objcnt = 0;
+	CK_BBOOL is_token = TRUE;
+	CK_BYTE attr_data[2][1024];
+	CK_OBJECT_CLASS key_class = CKO_PUBLIC_KEY;
+	CK_OBJECT_HANDLE ks_key = CK_INVALID_HANDLE;	/* key in keystore */
+	extern char *pk11_pin;
+
+	/* we look for private keys only */
+	CK_ATTRIBUTE search_templ[] =
+		{
+		{CKA_TOKEN, &is_token, sizeof(is_token)},
+		{CKA_CLASS, &key_class, sizeof(key_class)},
+		{CKA_LABEL, NULL, 0}
+		};
+
+	/* these attributes are needed to initialize OpenSSL RSA structure */
+	CK_ATTRIBUTE get_templ[] =
+		{
+		{CKA_MODULUS, (void *)attr_data[0], 1024},	    /* n */
+		{CKA_PUBLIC_EXPONENT, (void *)attr_data[1], 1024},  /* e */
+		};
+
+	if ((sp = pk11_get_session()) == NULL)
+		return NULL;
+
+	/*
+	 * Use simple scheme "pkcs11:<KEY_LABEL>" for now.
+	 */
+	if (strstr(pubkey_file, "pkcs11:") == pubkey_file)
+		{
+		search_templ[2].pValue = strstr(pubkey_file, ":") + 1;
+		search_templ[2].ulValueLen = strlen(search_templ[2].pValue);
+
+#define ALLWAYS_LOGIN
+#ifdef ALLWAYS_LOGIN
+		if (pk11_pin == NULL)
+#ifndef OPENCRYPTOKI
+			pk11_pin = getpassphrase("Enter PIN: ");
+#else
+			pk11_pin = getpass("Enter PIN: ");
+#endif
+		if ((rv = pFuncList->C_Login(sp->session, CKU_USER, (CK_UTF8CHAR*)pk11_pin,
+		    strlen(pk11_pin))) != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN)
+			{
+			fprintf(stderr, "C_Login -> %lx\n", rv);
+			PK11err(PK11_F_LOAD_PUBKEY, PK11_R_INVALID_PIN);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+#endif
+
+		CRYPTO_w_lock(CRYPTO_LOCK_PK11_ENGINE);
+		if (pFuncList->C_FindObjectsInit(sp->session, search_templ, 3) != CKR_OK)
+			{
+			CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+			PK11err(PK11_F_LOAD_PUBKEY, PK11_R_FINDOBJECTSINIT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+		rv = pFuncList->C_FindObjects(sp->session, &ks_key, 1, &objcnt);
+		if (rv != CKR_OK)
+			{
+			CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+			PK11err(PK11_F_LOAD_PUBKEY, PK11_R_FINDOBJECTS);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+
+		if (objcnt > 1)
+			{
+			CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+			PK11err(PK11_F_LOAD_PUBKEY, PK11_R_TOO_MANY_OBJECTS);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lu", objcnt);
+			ERR_add_error_data(2,
+				"PK11 too many objects:", tmp_buf);
+			goto err;
+			}
+
+		if (objcnt != 1)
+			{
+			CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+			PK11err(PK11_F_LOAD_PUBKEY, PK11_R_OBJECT_NOT_FOUND);
+			ERR_add_error_data(1, "PK11 object not found");
+			goto err;
+			}
+
+		(void) pFuncList->C_FindObjectsFinal(sp->session);
+		CRYPTO_w_unlock(CRYPTO_LOCK_PK11_ENGINE);
+
+		sp->rsa_pub_key = ks_key;
+		pkey = malloc(sizeof(EVP_PKEY));
+		bzero(pkey, sizeof(EVP_PKEY));
+		pkey->type = EVP_PKEY_RSA;
+		pkey->references = 1;
+
+		rsa = pkey->pkey.rsa = sp->rsa = malloc(sizeof(RSA));
+		bzero(rsa, sizeof(RSA));
+
+		if (pFuncList->C_GetAttributeValue(sp->session, ks_key,
+		    get_templ, 3) != CKR_OK)
+			{
+			PK11err(PK11_F_LOAD_PUBKEY, PK11_R_GETATTRIBUTVALUE);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+
+		/*
+		 * Now we have to initialize an OpenSSL RSA structure,
+		 * everything else is 0 or NULL.
+		 */
+		rsa->meth = &pk11_rsa;
+		rsa->engine = e;
+		rsa->references = 2;
+		rsa->flags = RSA_FLAG_SIGN_VER;
+
+		attr_to_BN(&get_templ[0], attr_data[0], &rsa->n);
+		attr_to_BN(&get_templ[1], attr_data[1], &rsa->e);
+		}
+	else if ((pubkey=fopen(pubkey_file,"r")) != NULL)
+		{
+		pkey = PEM_read_PUBKEY(pubkey, NULL, NULL, NULL);
+		fclose(pubkey);
+		if (pkey)
+			{
+			rsa = EVP_PKEY_get1_RSA(pkey);
+			if (rsa)
+				{
+				check_new_rsa_key(sp, (void *) rsa);
+	
+				h_pub_key = pk11_get_public_rsa_key(rsa, sp);
+				if (h_pub_key == CK_INVALID_HANDLE)
+					{
+					EVP_PKEY_free(pkey);
+					pkey = NULL;
+					}
+				}
+			else
+				{
+				EVP_PKEY_free(pkey);
+				pkey = NULL;
+				}
+			}
+		}
+
+err:
+	pk11_return_session(sp);
+	return(pkey);
+	}
+
+/* Create a public key object in a session from a given rsa structure.
+ */
+static CK_OBJECT_HANDLE pk11_get_public_rsa_key(RSA* rsa, PK11_SESSION *sp)
+	{
+	CK_RV rv;
+	CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+	CK_ULONG found;
+	CK_OBJECT_CLASS o_key = CKO_PUBLIC_KEY;
+	CK_KEY_TYPE k_type = CKK_RSA;
+	CK_ULONG ul_key_attr_count = 7;
+	char tmp_buf[20];
+
+	CK_ATTRIBUTE  a_key_template[] =
+		{
+		{CKA_CLASS, (void *) NULL, sizeof(CK_OBJECT_CLASS)},
+		{CKA_KEY_TYPE, (void *) NULL, sizeof(CK_KEY_TYPE)},
+		{CKA_TOKEN, &false, sizeof(true)},
+		{CKA_ENCRYPT, &true, sizeof(true)},
+		{CKA_VERIFY_RECOVER, &true, sizeof(true)},
+		{CKA_MODULUS, (void *)NULL, 0},
+		{CKA_PUBLIC_EXPONENT, (void *)NULL, 0}
+		};
+
+	int i;
+	CK_SESSION_HANDLE session = sp->session;
+
+	a_key_template[0].pValue = &o_key;
+	a_key_template[1].pValue = &k_type;
+
+	a_key_template[5].ulValueLen = BN_num_bytes(rsa->n);
+	a_key_template[5].pValue = (CK_VOID_PTR)OPENSSL_malloc(
+		(size_t)a_key_template[5].ulValueLen);
+	if (a_key_template[5].pValue == NULL)
+		{
+		PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+
+	BN_bn2bin(rsa->n, a_key_template[5].pValue);
+
+	a_key_template[6].ulValueLen = BN_num_bytes(rsa->e);
+	a_key_template[6].pValue = (CK_VOID_PTR)OPENSSL_malloc(
+		(size_t)a_key_template[6].ulValueLen);
+	if (a_key_template[6].pValue == NULL)
+		{
+		PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+
+	BN_bn2bin(rsa->e, a_key_template[6].pValue);
+
+	rv = pFuncList->C_FindObjectsInit(session, a_key_template, 
+		ul_key_attr_count);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_FINDOBJECTSINIT);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_FINDOBJECTS);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	rv = pFuncList->C_FindObjectsFinal(session);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_PUB_RSA_KEY, PK11_R_FINDOBJECTSFINAL);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	if (found == 0)
+		{
+		rv = pFuncList->C_CreateObject(session, 
+			a_key_template, ul_key_attr_count, &h_key);
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_GET_PUB_RSA_KEY, 
+				PK11_R_CREATEOBJECT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+		}
+
+	sp->rsa = rsa;
+
+ err:
+	for (i = 5; i <= 6; i++)
+		{
+		if (a_key_template[i].pValue != NULL)
+			{
+			OPENSSL_free(a_key_template[i].pValue);
+			a_key_template[i].pValue = NULL;
+			}
+		}
+
+	return h_key;
+
+	}
+
+/* Create a private key object in the session from a given rsa structure
+ */
+static CK_OBJECT_HANDLE pk11_get_private_rsa_key(RSA* rsa, PK11_SESSION *sp)
+	{
+	CK_RV rv;
+	CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+	int i;
+	CK_ULONG found;
+	CK_OBJECT_CLASS o_key = CKO_PRIVATE_KEY;
+	CK_KEY_TYPE k_type = CKK_RSA;
+	CK_ULONG ul_key_attr_count = 14;
+	char tmp_buf[20];
+
+	/* Both CKA_TOKEN and CKA_SENSITIVE have to be FALSE for session keys
+	 */
+	CK_ATTRIBUTE  a_key_template[] =
+		{
+		{CKA_CLASS, (void *) NULL, sizeof(CK_OBJECT_CLASS)},
+		{CKA_KEY_TYPE, (void *) NULL, sizeof(CK_KEY_TYPE)},
+		{CKA_TOKEN, &false, sizeof(true)},
+		{CKA_SENSITIVE, &false, sizeof(true)},
+		{CKA_DECRYPT, &true, sizeof(true)},
+		{CKA_SIGN, &true, sizeof(true)},
+		{CKA_MODULUS, (void *)NULL, 0},
+		{CKA_PUBLIC_EXPONENT, (void *)NULL, 0},
+		{CKA_PRIVATE_EXPONENT, (void *)NULL, 0},
+		{CKA_PRIME_1, (void *)NULL, 0},
+		{CKA_PRIME_2, (void *)NULL, 0},
+		{CKA_EXPONENT_1, (void *)NULL, 0},
+		{CKA_EXPONENT_2, (void *)NULL, 0},
+		{CKA_COEFFICIENT, (void *)NULL, 0}
+		};
+	CK_SESSION_HANDLE session = sp->session;
+
+	if ((rsa->flags & RSA_FLAG_EXT_PKEY) != 0) {
+		sp->rsa = rsa;
+		return (*(CK_OBJECT_HANDLE_PTR)RSA_get_ex_data(rsa, hndidx_rsa));
+	}
+	
+	a_key_template[0].pValue = &o_key;
+	a_key_template[1].pValue = &k_type;
+
+	/* Put the private key components into the template */
+	if (init_template_value(rsa->n, &a_key_template[6].pValue,
+		&a_key_template[6].ulValueLen) == 0 ||
+	    init_template_value(rsa->e, &a_key_template[7].pValue,
+		&a_key_template[7].ulValueLen) == 0 ||
+	    init_template_value(rsa->d, &a_key_template[8].pValue,
+		&a_key_template[8].ulValueLen) == 0 ||
+	    init_template_value(rsa->p, &a_key_template[9].pValue,
+		&a_key_template[9].ulValueLen) == 0 ||
+	    init_template_value(rsa->q, &a_key_template[10].pValue,
+		&a_key_template[10].ulValueLen) == 0 ||
+	    init_template_value(rsa->dmp1, &a_key_template[11].pValue,
+		&a_key_template[11].ulValueLen) == 0 ||
+	    init_template_value(rsa->dmq1, &a_key_template[12].pValue,
+		&a_key_template[12].ulValueLen) == 0 ||
+	    init_template_value(rsa->iqmp, &a_key_template[13].pValue,
+		&a_key_template[13].ulValueLen) == 0)
+		{
+		PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+
+	rv = pFuncList->C_FindObjectsInit(session, a_key_template, 
+		ul_key_attr_count);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_FINDOBJECTSINIT);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_FINDOBJECTS);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	rv = pFuncList->C_FindObjectsFinal(session);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_PRIV_RSA_KEY, PK11_R_FINDOBJECTSFINAL);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	if (found == 0)
+		{
+		rv = pFuncList->C_CreateObject(session, 
+			a_key_template, ul_key_attr_count, &h_key);
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_GET_PRIV_RSA_KEY, 
+				PK11_R_CREATEOBJECT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+		}
+
+	sp->rsa = rsa;
+
+ err:
+	/* 6 to 13 entries in the key template are key components
+	 * They need to be freed apon exit or error.
+	 */
+	for (i = 6; i <= 13; i++)
+		{
+		if (a_key_template[i].pValue != NULL)
+			{
+			memset(a_key_template[i].pValue, 0, 
+				a_key_template[i].ulValueLen);
+			OPENSSL_free(a_key_template[i].pValue);
+			a_key_template[i].pValue = NULL;
+			}
+		}
+
+	return h_key;
+	}
+
+#endif
+
+
+#ifndef OPENSSL_NO_DSA
+/* The DSA function implementation
+ */
+static int pk11_DSA_init(DSA *dsa)
+	{
+	return 1;
+	}
+
+
+static int pk11_DSA_finish(DSA *dsa)
+	{
+	return pk11_destroy_dsa_key_objects(NULL);
+	}
+
+
+static DSA_SIG *
+pk11_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa)
+	{
+	BIGNUM *r = NULL, *s = NULL;
+	int i;
+	DSA_SIG *dsa_sig = NULL;
+
+	CK_RV rv;
+	CK_MECHANISM Mechanism_dsa = {CKM_DSA, NULL, 0};
+	CK_MECHANISM *p_mech = &Mechanism_dsa;
+	CK_OBJECT_HANDLE h_priv_key;
+
+	/* The signature is the concatenation of r and s, 
+	 * each is 20 bytes long
+	 */
+	unsigned char sigret[DSA_SIGNATURE_LEN];
+	unsigned long siglen = DSA_SIGNATURE_LEN;
+	unsigned int siglen2 = DSA_SIGNATURE_LEN / 2;
+
+	PK11_SESSION *sp = NULL;
+	char tmp_buf[20];
+
+	if ((dsa->p == NULL) || (dsa->q == NULL) || (dsa->g == NULL)) 
+		{
+		PK11err(PK11_F_DSA_SIGN, PK11_R_MISSING_KEY_COMPONENT);
+		goto ret;
+		}
+
+	i=BN_num_bytes(dsa->q); /* should be 20 */
+	if (dlen > i)
+		{
+		PK11err(PK11_F_DSA_SIGN, PK11_R_INVALID_SIGNATURE_LENGTH);
+		goto ret;
+		}
+
+	if ((sp = pk11_get_session()) == NULL)
+		goto ret;
+
+	check_new_dsa_key(sp, (void *) dsa);
+
+	h_priv_key = sp->dsa_priv_key;
+	if (h_priv_key == CK_INVALID_HANDLE)
+		h_priv_key = sp->dsa_priv_key =
+			pk11_get_private_dsa_key((DSA *)dsa, sp);
+
+	if (h_priv_key != CK_INVALID_HANDLE)
+		{
+		rv = pFuncList->C_SignInit(sp->session, p_mech, h_priv_key);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_DSA_SIGN, PK11_R_SIGNINIT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto ret;
+			}
+
+		memset(sigret, 0, siglen);
+		rv = pFuncList->C_Sign(sp->session, 
+			(unsigned char*) dgst, dlen, sigret, 
+			(CK_ULONG_PTR) &siglen);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_DSA_SIGN, PK11_R_SIGN);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto ret;
+			}
+		}
+
+
+	if ((s = BN_new()) == NULL)
+		{
+		PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
+		goto ret;
+		}
+
+	if ((r = BN_new()) == NULL)
+		{
+		PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
+		goto ret;
+		}
+
+	if ((dsa_sig = DSA_SIG_new()) == NULL)
+		{
+		PK11err(PK11_F_DSA_SIGN, PK11_R_MALLOC_FAILURE);
+		goto ret;
+		}
+
+	BN_bin2bn(sigret, siglen2, r);
+	BN_bin2bn(&sigret[siglen2], siglen2, s);
+
+	dsa_sig->r = r;
+	dsa_sig->s = s;
+
+ret:
+	if (dsa_sig == NULL) 
+		{
+		if (r != NULL)
+			BN_free(r);
+		if (s != NULL)
+			BN_free(s);
+		}
+
+	pk11_return_session(sp);
+	return (dsa_sig);
+	}
+
+static int
+pk11_dsa_do_verify(const unsigned char *dgst, int dlen, DSA_SIG *sig,
+	DSA *dsa)
+	{
+	int i;
+	CK_RV rv;
+	int retval = 0;
+	CK_MECHANISM Mechanism_dsa = {CKM_DSA, NULL, 0};
+	CK_MECHANISM *p_mech = &Mechanism_dsa;
+	CK_OBJECT_HANDLE h_pub_key;
+
+	unsigned char sigbuf[DSA_SIGNATURE_LEN];
+	unsigned long siglen = DSA_SIGNATURE_LEN;
+	unsigned long siglen2 = DSA_SIGNATURE_LEN/2;
+
+	PK11_SESSION *sp = NULL;
+	char tmp_buf[20];
+
+	if (BN_is_zero(sig->r) || sig->r->neg || BN_ucmp(sig->r, dsa->q) >= 0)
+		{
+		PK11err(PK11_F_DSA_VERIFY, 
+			PK11_R_INVALID_DSA_SIGNATURE_R);
+		goto ret;
+		}
+
+	if (BN_is_zero(sig->s) || sig->s->neg || BN_ucmp(sig->s, dsa->q) >= 0) 
+		{
+		PK11err(PK11_F_DSA_VERIFY, 
+			PK11_R_INVALID_DSA_SIGNATURE_S);
+		goto ret;
+		}
+
+	i = BN_num_bytes(dsa->q); /* should be 20 */
+
+	if (dlen > i)
+		{
+		PK11err(PK11_F_DSA_VERIFY, 
+			PK11_R_INVALID_SIGNATURE_LENGTH);
+		goto ret;
+		}
+
+	if ((sp = pk11_get_session()) == NULL)
+		goto ret;
+	
+	check_new_dsa_key(sp, (void *) dsa);
+
+	h_pub_key = sp->dsa_pub_key;
+	if (h_pub_key == CK_INVALID_HANDLE)
+		h_pub_key = sp->dsa_pub_key = 
+			pk11_get_public_dsa_key((DSA *)dsa, sp);
+
+	if (h_pub_key != CK_INVALID_HANDLE)
+		{
+		rv = pFuncList->C_VerifyInit(sp->session, p_mech, 
+			h_pub_key);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_DSA_VERIFY, PK11_R_VERIFYINIT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto ret;
+			}
+
+		memset(sigbuf, 0, siglen);
+		BN_bn2bin(sig->r, sigbuf);
+		BN_bn2bin(sig->s, &sigbuf[siglen2]);
+		
+		rv = pFuncList->C_Verify(sp->session, 
+			(unsigned char *) dgst, dlen, sigbuf, (CK_ULONG)siglen);
+
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_DSA_VERIFY, PK11_R_VERIFY);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto ret;
+			}
+		}
+
+	retval = 1;
+ret:
+
+	pk11_return_session(sp);
+	return retval;
+	}
+
+
+/* Create a public key object in a session from a given dsa structure.
+ */
+static CK_OBJECT_HANDLE pk11_get_public_dsa_key(DSA* dsa, PK11_SESSION *sp)
+	{
+	CK_RV rv;
+	CK_OBJECT_CLASS o_key = CKO_PUBLIC_KEY;
+	CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+	CK_ULONG found;
+	CK_KEY_TYPE k_type = CKK_DSA;
+	CK_ULONG ul_key_attr_count = 8;
+	int i;
+	char tmp_buf[20];
+
+	CK_ATTRIBUTE  a_key_template[] =
+		{
+		{CKA_CLASS, (void *) NULL, sizeof(CK_OBJECT_CLASS)},
+		{CKA_KEY_TYPE, (void *) NULL, sizeof(CK_KEY_TYPE)},
+		{CKA_TOKEN, &false, sizeof(true)},
+		{CKA_VERIFY, &true, sizeof(true)},
+		{CKA_PRIME, (void *)NULL, 0},		/* p */
+		{CKA_SUBPRIME, (void *)NULL, 0},	/* q */
+		{CKA_BASE, (void *)NULL, 0},		/* g */
+		{CKA_VALUE, (void *)NULL, 0}		/* pub_key - y */
+		};
+	CK_SESSION_HANDLE session = sp->session;
+
+	a_key_template[0].pValue = &o_key;
+	a_key_template[1].pValue = &k_type;
+
+	if (init_template_value(dsa->p, &a_key_template[4].pValue,
+		&a_key_template[4].ulValueLen) == 0 ||
+	    init_template_value(dsa->q, &a_key_template[5].pValue,
+		&a_key_template[5].ulValueLen) == 0 ||
+	    init_template_value(dsa->g, &a_key_template[6].pValue,
+		&a_key_template[6].ulValueLen) == 0 ||
+	    init_template_value(dsa->pub_key, &a_key_template[7].pValue,
+		&a_key_template[7].ulValueLen) == 0)
+		{
+		PK11err(PK11_F_GET_PUB_DSA_KEY, PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+
+	rv = pFuncList->C_FindObjectsInit(session, a_key_template, 
+		ul_key_attr_count);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_PUB_DSA_KEY, PK11_R_FINDOBJECTSINIT);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_PUB_DSA_KEY, PK11_R_FINDOBJECTS);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	rv = pFuncList->C_FindObjectsFinal(session);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_PUB_DSA_KEY, PK11_R_FINDOBJECTSFINAL);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	if (found == 0)
+		{
+		rv = pFuncList->C_CreateObject(session, 
+			a_key_template, ul_key_attr_count, &h_key);
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_GET_PUB_DSA_KEY, 
+				PK11_R_CREATEOBJECT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+		}
+
+	sp->dsa = dsa;
+
+ err:
+	for (i = 4; i <= 7; i++)
+		{
+		if (a_key_template[i].pValue != NULL)
+			{
+			OPENSSL_free(a_key_template[i].pValue);
+			a_key_template[i].pValue = NULL;
+			}
+		}
+
+	return h_key;
+
+	}
+
+/* Create a private key object in the session from a given dsa structure
+ */
+static CK_OBJECT_HANDLE pk11_get_private_dsa_key(DSA* dsa, PK11_SESSION *sp)
+	{
+	CK_RV rv;
+	CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+	CK_OBJECT_CLASS o_key = CKO_PRIVATE_KEY;
+	int i;
+	char tmp_buf[20];
+	CK_ULONG found;
+	CK_KEY_TYPE k_type = CKK_DSA;
+	CK_ULONG ul_key_attr_count = 9;
+
+	/* Both CKA_TOKEN and CKA_SENSITIVE have to be FALSE for session keys
+	 */
+	CK_ATTRIBUTE  a_key_template[] =
+		{
+		{CKA_CLASS, (void *) NULL, sizeof(CK_OBJECT_CLASS)},
+		{CKA_KEY_TYPE, (void *) NULL, sizeof(CK_KEY_TYPE)},
+		{CKA_TOKEN, &false, sizeof(true)},
+		{CKA_SENSITIVE, &false, sizeof(true)},
+		{CKA_SIGN, &true, sizeof(true)},
+		{CKA_PRIME, (void *)NULL, 0},		/* p */
+		{CKA_SUBPRIME, (void *)NULL, 0},	/* q */
+		{CKA_BASE, (void *)NULL, 0},		/* g */
+		{CKA_VALUE, (void *)NULL, 0}		/* priv_key - x */
+		};
+	CK_SESSION_HANDLE session = sp->session;
+
+	a_key_template[0].pValue = &o_key;
+	a_key_template[1].pValue = &k_type;
+
+	/* Put the private key components into the template
+	 */
+	if (init_template_value(dsa->p, &a_key_template[5].pValue,
+		&a_key_template[5].ulValueLen) == 0 ||
+	    init_template_value(dsa->q, &a_key_template[6].pValue,
+		&a_key_template[6].ulValueLen) == 0 ||
+	    init_template_value(dsa->g, &a_key_template[7].pValue,
+		&a_key_template[7].ulValueLen) == 0 ||
+	    init_template_value(dsa->priv_key, &a_key_template[8].pValue,
+		&a_key_template[8].ulValueLen) == 0)
+		{
+		PK11err(PK11_F_GET_PRIV_DSA_KEY, PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+
+	rv = pFuncList->C_FindObjectsInit(session, a_key_template, 
+		ul_key_attr_count);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_PRIV_DSA_KEY, PK11_R_FINDOBJECTSINIT);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_PRIV_DSA_KEY, PK11_R_FINDOBJECTS);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	rv = pFuncList->C_FindObjectsFinal(session);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_PRIV_DSA_KEY, PK11_R_FINDOBJECTSFINAL);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	if (found == 0)
+		{
+		rv = pFuncList->C_CreateObject(session, 
+			a_key_template, ul_key_attr_count, &h_key);
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_GET_PRIV_DSA_KEY, 
+				PK11_R_CREATEOBJECT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+		}
+
+	sp->dsa = dsa;
+
+err:
+	/* 5 to 8 entries in the key template are key components
+	 * They need to be freed apon exit or error.
+	 */
+	for (i = 5; i <= 8; i++)
+		{
+		if (a_key_template[i].pValue != NULL)
+			{
+			memset(a_key_template[i].pValue, 0,
+				a_key_template[i].ulValueLen);
+			OPENSSL_free(a_key_template[i].pValue);
+			a_key_template[i].pValue = NULL;
+			}
+		}
+
+	return h_key;
+
+	}
+#endif
+
+
+#ifndef OPENSSL_NO_DH
+
+/* The DH function implementation
+ */
+static int pk11_DH_init(DH *dh)
+	{
+	return 1;
+	}
+
+
+static int pk11_DH_finish(DH *dh)
+	{
+	return pk11_destroy_dh_key_objects(NULL);
+	}
+
+static int pk11_DH_generate_key(DH *dh)
+	{
+	CK_ULONG i;
+	CK_RV rv, rv1;
+	int ret = 0;
+	PK11_SESSION *sp = NULL;
+	char tmp_buf[20];
+	CK_BYTE_PTR reuse_mem;
+
+	CK_MECHANISM mechanism = {CKM_DH_PKCS_KEY_PAIR_GEN, NULL_PTR, 0};
+	CK_OBJECT_HANDLE h_pub_key = CK_INVALID_HANDLE;
+	CK_OBJECT_HANDLE h_priv_key = CK_INVALID_HANDLE;
+
+	CK_ULONG ul_pub_key_attr_count = 3; 
+	CK_ATTRIBUTE pub_key_template[] =
+		{
+		{CKA_PRIVATE, &false, sizeof(false)},
+		{CKA_PRIME, (void *)NULL, 0},
+		{CKA_BASE, (void *)NULL, 0}
+		};
+
+	CK_ULONG ul_priv_key_attr_count = 3; 
+	CK_ATTRIBUTE priv_key_template[] =
+		{
+		{CKA_PRIVATE, &false, sizeof(false)},
+		{CKA_SENSITIVE, &false, sizeof(false)},
+		{CKA_DERIVE, &true, sizeof(true)}
+		};
+
+	CK_ULONG pub_key_attr_result_count = 1;
+	CK_ATTRIBUTE pub_key_result[] =
+		{
+		{CKA_VALUE, (void *)NULL, 0}
+		};
+
+	CK_ULONG priv_key_attr_result_count = 1;
+	CK_ATTRIBUTE priv_key_result[] =
+		{
+		{CKA_VALUE, (void *)NULL, 0}
+		};
+
+	pub_key_template[1].ulValueLen = BN_num_bytes(dh->p);
+	if (pub_key_template[1].ulValueLen > 0)
+		{
+		pub_key_template[1].pValue = 
+			OPENSSL_malloc(pub_key_template[1].ulValueLen);
+		if (pub_key_template[1].pValue == NULL)
+			{
+			PK11err(PK11_F_DH_GEN_KEY, PK11_R_MALLOC_FAILURE);
+			goto err;
+			}
+
+		i = BN_bn2bin(dh->p, pub_key_template[1].pValue);
+		}
+	else
+		goto err;
+
+	pub_key_template[2].ulValueLen = BN_num_bytes(dh->g);
+	if (pub_key_template[2].ulValueLen > 0)
+		{
+		pub_key_template[2].pValue = 
+			OPENSSL_malloc(pub_key_template[2].ulValueLen);
+		if (pub_key_template[2].pValue == NULL)
+			{
+			PK11err(PK11_F_DH_GEN_KEY, PK11_R_MALLOC_FAILURE);
+			goto err;
+			}
+
+		i = BN_bn2bin(dh->g, pub_key_template[2].pValue);
+		}
+	else
+		goto err;
+
+	if ((sp = pk11_get_session()) == NULL)
+		goto err;
+	
+	rv = pFuncList->C_GenerateKeyPair(sp->session,
+			   &mechanism,
+			   pub_key_template,
+			   ul_pub_key_attr_count,
+			   priv_key_template,
+			   ul_priv_key_attr_count,
+			   &h_pub_key,
+			   &h_priv_key);
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_DH_GEN_KEY, PK11_R_GEN_KEY);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	/* Reuse the larger memory allocated. We know the larger memory
+	 * is sufficient for reuse */
+	if (pub_key_template[1].ulValueLen > pub_key_template[2].ulValueLen)
+		reuse_mem = pub_key_template[1].pValue;
+	else
+		reuse_mem = pub_key_template[2].pValue;
+
+	rv = pFuncList->C_GetAttributeValue(sp->session, h_pub_key, 
+		pub_key_result, pub_key_attr_result_count);
+	rv1 = pFuncList->C_GetAttributeValue(sp->session, h_priv_key, 
+		priv_key_result, priv_key_attr_result_count);
+
+	if (rv != CKR_OK || rv1 != CKR_OK)
+		{
+		rv = (rv != CKR_OK) ? rv : rv1;
+		PK11err(PK11_F_DH_GEN_KEY, PK11_R_GETATTRIBUTVALUE);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	if (((CK_LONG) pub_key_result[0].ulValueLen) <= 0 ||
+		((CK_LONG) priv_key_result[0].ulValueLen) <= 0)
+		{
+		PK11err(PK11_F_DH_GEN_KEY, PK11_R_GETATTRIBUTVALUE);
+		goto err;
+		}
+	
+	/* Reuse the memory allocated */
+	pub_key_result[0].pValue = reuse_mem;
+
+	rv = pFuncList->C_GetAttributeValue(sp->session, h_pub_key, 
+		pub_key_result, pub_key_attr_result_count);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_DH_GEN_KEY, PK11_R_GETATTRIBUTVALUE);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	if (pub_key_result[0].type == CKA_VALUE)
+		{
+		if (dh->pub_key == NULL)
+			dh->pub_key = BN_new();
+		dh->pub_key = BN_bin2bn(pub_key_result[0].pValue, 
+			pub_key_result[0].ulValueLen, dh->pub_key);
+		}
+
+	/* Reuse the memory allocated */
+	priv_key_result[0].pValue = reuse_mem;
+
+	rv = pFuncList->C_GetAttributeValue(sp->session, h_priv_key, 
+		priv_key_result, priv_key_attr_result_count);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_DH_GEN_KEY, PK11_R_GETATTRIBUTVALUE);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	if (priv_key_result[0].type == CKA_VALUE)
+		{
+		if (dh->priv_key == NULL)
+			dh->priv_key = BN_new();
+		dh->priv_key = BN_bin2bn(priv_key_result[0].pValue, 
+			priv_key_result[0].ulValueLen, dh->priv_key);
+		}
+
+	ret = 1;
+
+err:
+	 
+	if (h_pub_key != CK_INVALID_HANDLE)
+		{
+		rv = pFuncList->C_DestroyObject(sp->session, h_pub_key);
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_DH_GEN_KEY, PK11_R_DESTROYOBJECT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			}
+		}
+
+	if (h_priv_key != CK_INVALID_HANDLE)
+		{
+		rv = pFuncList->C_DestroyObject(sp->session, h_priv_key);
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_DH_GEN_KEY, PK11_R_DESTROYOBJECT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			}
+		}
+
+	for (i = 1; i <= 2; i++)
+		{
+		if (pub_key_template[i].pValue != NULL)
+			{
+			OPENSSL_free(pub_key_template[i].pValue);
+			pub_key_template[i].pValue = NULL;
+			}
+		}
+
+	pk11_return_session(sp);
+	return ret;
+	}
+
+static int pk11_DH_compute_key(unsigned char *key,const BIGNUM *pub_key,DH *dh)
+	{
+	int i;
+	CK_MECHANISM mechanism = {CKM_DH_PKCS_DERIVE, NULL_PTR, 0};
+	CK_OBJECT_CLASS key_class = CKO_SECRET_KEY;
+	CK_KEY_TYPE key_type = CKK_GENERIC_SECRET;
+	CK_OBJECT_HANDLE h_derived_key = CK_INVALID_HANDLE;
+	CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+
+	CK_ULONG ul_priv_key_attr_count = 2;
+	CK_ATTRIBUTE priv_key_template[] =
+		{
+		{CKA_CLASS, (void*) NULL, sizeof(key_class)},
+		{CKA_KEY_TYPE, (void*) NULL,  sizeof(key_type)},
+		};
+
+	CK_ULONG priv_key_attr_result_count = 1;
+	CK_ATTRIBUTE priv_key_result[] =
+		{
+		{CKA_VALUE, (void *)NULL, 0}
+		};
+
+	CK_RV rv;
+	int ret = 0;
+	PK11_SESSION *sp = NULL;
+	char tmp_buf[20];
+
+	priv_key_template[0].pValue = &key_class;
+	priv_key_template[1].pValue = &key_type;
+
+	if ((sp = pk11_get_session()) == NULL)
+		goto err;
+
+	mechanism.ulParameterLen = BN_num_bytes(pub_key);
+	mechanism.pParameter = OPENSSL_malloc(mechanism.ulParameterLen);
+	if (mechanism.pParameter == NULL)
+		{
+		PK11err(PK11_F_DH_COMP_KEY, PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+	BN_bn2bin(pub_key, mechanism.pParameter);
+
+	check_new_dh_key(sp, dh);
+
+	h_key = sp->dh_key;
+	if (h_key == CK_INVALID_HANDLE)
+		h_key = sp->dh_key = pk11_get_dh_key((DH*) dh, sp);
+
+	if (h_key == CK_INVALID_HANDLE)
+		{
+		PK11err(PK11_F_DH_COMP_KEY, PK11_R_CREATEOBJECT);
+		goto err;
+		}
+
+	rv = pFuncList->C_DeriveKey(sp->session,
+			   &mechanism,
+			   h_key,
+			   priv_key_template,
+			   ul_priv_key_attr_count,
+			   &h_derived_key);
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_DH_COMP_KEY, PK11_R_DERIVEKEY);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	rv = pFuncList->C_GetAttributeValue(sp->session, h_derived_key, 
+		priv_key_result, priv_key_attr_result_count);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_DH_COMP_KEY, PK11_R_GETATTRIBUTVALUE);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	if (((CK_LONG) priv_key_result[0].ulValueLen) <= 0)
+		{
+		PK11err(PK11_F_DH_COMP_KEY, PK11_R_GETATTRIBUTVALUE);
+		goto err;
+		}
+	priv_key_result[0].pValue = 
+		OPENSSL_malloc(priv_key_result[0].ulValueLen);
+	if (!priv_key_result[0].pValue)
+		{
+		PK11err(PK11_F_DH_COMP_KEY, PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+
+	rv = pFuncList->C_GetAttributeValue(sp->session, h_derived_key, 
+		priv_key_result, priv_key_attr_result_count);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_DH_COMP_KEY, PK11_R_GETATTRIBUTVALUE);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	/* OpenSSL allocates the output buffer 'key' which is the same
+	 * length of the public key. It is long enough for the derived key */
+	if (priv_key_result[0].type == CKA_VALUE)
+		{
+		/* CKM_DH_PKCS_DERIVE mechanism is not supposed to strip
+		 * leading zeros from a computed shared secret. However,
+		 * OpenSSL always did it so we must do the same here. The
+		 * vagueness of the spec regarding leading zero bytes was
+		 * finally cleared with TLS 1.1 (RFC 4346) saying that leading
+		 * zeros are stripped before the computed data is used as the
+		 * pre-master secret.
+		 */
+		for (i = 0; i < priv_key_result[0].ulValueLen; ++i)
+			{
+			if (((char *) priv_key_result[0].pValue)[i] != 0)
+				break;
+			}
+
+		memcpy(key, ((char *) priv_key_result[0].pValue) + i, 
+			priv_key_result[0].ulValueLen - i);
+		ret = priv_key_result[0].ulValueLen - i;
+		}
+
+err:
+
+	if (h_derived_key != CK_INVALID_HANDLE)
+		{
+		rv = pFuncList->C_DestroyObject(sp->session, h_derived_key);
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_DH_COMP_KEY, PK11_R_DESTROYOBJECT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			}
+		}
+	if (priv_key_result[0].pValue)
+		{ 
+		OPENSSL_free(priv_key_result[0].pValue);
+		priv_key_result[0].pValue = NULL;
+		}
+
+	if (mechanism.pParameter)
+		{
+		OPENSSL_free(mechanism.pParameter);
+		mechanism.pParameter = NULL;
+		}
+
+	pk11_return_session(sp);
+	return ret;
+	}
+
+
+static CK_OBJECT_HANDLE pk11_get_dh_key(DH* dh, PK11_SESSION *sp)
+	{
+	CK_RV rv;
+	CK_OBJECT_HANDLE h_key = CK_INVALID_HANDLE;
+	CK_OBJECT_CLASS class = CKO_PRIVATE_KEY;
+	CK_KEY_TYPE key_type = CKK_DH;
+	CK_ULONG found;
+	int i;
+	char tmp_buf[20];
+
+	CK_ULONG ul_key_attr_count = 7;
+	CK_ATTRIBUTE key_template[] =
+		{
+		{CKA_CLASS, (void*) NULL, sizeof(class)},
+		{CKA_KEY_TYPE, (void*) NULL, sizeof(key_type)},
+		{CKA_DERIVE, &true, sizeof(true)},
+		{CKA_PRIVATE, &false, sizeof(false)},
+		{CKA_PRIME, (void *) NULL, 0},
+		{CKA_BASE, (void *) NULL, 0},
+		{CKA_VALUE, (void *) NULL, 0},
+		};
+
+	CK_SESSION_HANDLE session = sp->session;
+
+	key_template[0].pValue = &class;
+	key_template[1].pValue = &key_type;
+
+	key_template[4].ulValueLen = BN_num_bytes(dh->p);
+	key_template[4].pValue = (CK_VOID_PTR)OPENSSL_malloc(
+		(size_t)key_template[4].ulValueLen);
+	if (key_template[4].pValue == NULL)
+		{
+		PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+
+	BN_bn2bin(dh->p, key_template[4].pValue);
+
+	key_template[5].ulValueLen = BN_num_bytes(dh->g);
+	key_template[5].pValue = (CK_VOID_PTR)OPENSSL_malloc(
+		(size_t)key_template[5].ulValueLen);
+	if (key_template[5].pValue == NULL)
+		{
+		PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+
+	BN_bn2bin(dh->g, key_template[5].pValue);
+
+	key_template[6].ulValueLen = BN_num_bytes(dh->priv_key);
+	key_template[6].pValue = (CK_VOID_PTR)OPENSSL_malloc(
+		(size_t)key_template[6].ulValueLen);
+	if (key_template[6].pValue == NULL)
+		{
+		PK11err(PK11_F_GET_DH_KEY, PK11_R_MALLOC_FAILURE);
+		goto err;
+		}
+
+	BN_bn2bin(dh->priv_key, key_template[6].pValue);
+
+	rv = pFuncList->C_FindObjectsInit(session, key_template, 
+		ul_key_attr_count);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_DH_KEY, PK11_R_FINDOBJECTSINIT);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	rv = pFuncList->C_FindObjects(session, &h_key, 1, &found);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_DH_KEY, PK11_R_FINDOBJECTS);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	rv = pFuncList->C_FindObjectsFinal(session);
+
+	if (rv != CKR_OK)
+		{
+		PK11err(PK11_F_GET_DH_KEY, PK11_R_FINDOBJECTSFINAL);
+		snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+		ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+		goto err;
+		}
+
+	if (found == 0)
+		{
+		rv = pFuncList->C_CreateObject(session, 
+			key_template, ul_key_attr_count, &h_key);
+		if (rv != CKR_OK)
+			{
+			PK11err(PK11_F_GET_DH_KEY, PK11_R_CREATEOBJECT);
+			snprintf(tmp_buf, sizeof (tmp_buf), "%lx", rv);
+			ERR_add_error_data(2, "PK11 CK_RV=0X", tmp_buf);
+			goto err;
+			}
+		}
+
+	sp->dh = dh;
+
+ err:
+	for (i = 4; i <= 6; i++)
+		{
+		if (key_template[i].pValue != NULL)
+			{
+			OPENSSL_free(key_template[i].pValue);
+			key_template[i].pValue = NULL;
+			}
+		}
+
+	return h_key;
+	}
+
+#endif
+
+/* Local function to simplify key template population
+ * Return 0 -- error, 1 -- no error
+ */
+static int init_template_value(BIGNUM *bn, CK_VOID_PTR *p_value, 
+	CK_ULONG *ul_value_len)
+	{
+	CK_ULONG len = BN_num_bytes(bn);
+	if (len == 0)
+		return 1;
+
+	*ul_value_len = len;
+	*p_value = (CK_VOID_PTR)OPENSSL_malloc((size_t) *ul_value_len);
+	if (*p_value == NULL)
+		return 0;
+
+	BN_bn2bin(bn, *p_value);
+
+	return 1;
+	}
+
+static void attr_to_BN(CK_ATTRIBUTE_PTR attr, CK_BYTE attr_data[], BIGNUM **bn)
+	{
+		if (attr->ulValueLen > 0)
+			{
+			*bn = BN_bin2bn(attr_data, attr->ulValueLen, NULL);
+			}
+	}
+
+static void check_new_rsa_key(PK11_SESSION *sp, void *rsa)
+	{
+	if (sp->rsa != rsa)
+		pk11_destroy_rsa_key_objects(sp);
+	}
+
+static void check_new_dsa_key(PK11_SESSION *sp, void *dsa)
+	{
+	if (sp->dsa != dsa)
+		pk11_destroy_dsa_key_objects(sp);
+	}
+
+static void check_new_dh_key(PK11_SESSION *sp, void *dh)
+	{
+	if (sp->dh != dh)
+		pk11_destroy_dh_key_objects(sp);
+	}
+
+
+#endif
+#endif
diff -r -u -N openssl-0.9.8g/crypto/engine/Makefile openssl/crypto/engine/Makefile
--- openssl-0.9.8g/crypto/engine/Makefile	2005-07-16 13:13:05.000000000 +0200
+++ openssl/crypto/engine/Makefile	2007-10-25 01:27:09.000000000 +0200
@@ -21,12 +21,14 @@
 	eng_table.c eng_pkey.c eng_fat.c eng_all.c \
 	tb_rsa.c tb_dsa.c tb_ecdsa.c tb_dh.c tb_ecdh.c tb_rand.c tb_store.c \
 	tb_cipher.c tb_digest.c \
-	eng_openssl.c eng_cnf.c eng_dyn.c eng_cryptodev.c eng_padlock.c
+	eng_openssl.c eng_cnf.c eng_dyn.c eng_cryptodev.c eng_padlock.c \
+	hw_pk11.c hw_pk11_pub.c
 LIBOBJ= eng_err.o eng_lib.o eng_list.o eng_init.o eng_ctrl.o \
 	eng_table.o eng_pkey.o eng_fat.o eng_all.o \
 	tb_rsa.o tb_dsa.o tb_ecdsa.o tb_dh.o tb_ecdh.o tb_rand.o tb_store.o \
 	tb_cipher.o tb_digest.o \
-	eng_openssl.o eng_cnf.o eng_dyn.o eng_cryptodev.o eng_padlock.o
+	eng_openssl.o eng_cnf.o eng_dyn.o eng_cryptodev.o eng_padlock.o \
+	hw_pk11.o hw_pk11_pub.o
 
 SRC= $(LIBSRC)
 
@@ -212,6 +214,54 @@
 eng_table.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 eng_table.o: ../../include/openssl/symhacks.h ../cryptlib.h eng_int.h
 eng_table.o: eng_table.c
+hw_pk11.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
+hw_pk11.o: ../../include/openssl/engine.h ../../include/openssl/ossl_typ.h
+hw_pk11.o: ../../include/openssl/bn.h ../../include/openssl/rsa.h
+hw_pk11.o: ../../include/openssl/asn1.h ../../include/openssl/bio.h
+hw_pk11.o: ../../include/openssl/crypto.h ../../include/openssl/stack.h
+hw_pk11.o: ../../include/openssl/safestack.h ../../include/openssl/opensslv.h
+hw_pk11.o: ../../include/openssl/symhacks.h ../../include/openssl/dsa.h
+hw_pk11.o: ../../include/openssl/dh.h ../../include/openssl/rand.h
+hw_pk11.o: ../../include/openssl/ui.h ../../include/openssl/err.h
+hw_pk11.o: ../../include/openssl/lhash.h ../../include/openssl/dso.h
+hw_pk11.o: ../../include/openssl/pem.h ../../include/openssl/evp.h
+hw_pk11.o: ../../include/openssl/md2.h ../../include/openssl/md4.h
+hw_pk11.o: ../../include/openssl/md5.h ../../include/openssl/sha.h
+hw_pk11.o: ../../include/openssl/ripemd.h ../../include/openssl/des.h
+hw_pk11.o: ../../include/openssl/des_old.h ../../include/openssl/ui_compat.h
+hw_pk11.o: ../../include/openssl/rc4.h ../../include/openssl/rc2.h
+hw_pk11.o: ../../crypto/rc5/rc5.h ../../include/openssl/blowfish.h
+hw_pk11.o: ../../include/openssl/cast.h ../../include/openssl/idea.h
+hw_pk11.o: ../../crypto/mdc2/mdc2.h ../../include/openssl/aes.h
+hw_pk11.o: ../../include/openssl/objects.h ../../include/openssl/obj_mac.h
+hw_pk11.o: ../../include/openssl/x509.h ../../include/openssl/buffer.h
+hw_pk11.o: ../../include/openssl/x509_vfy.h ../../include/openssl/pkcs7.h
+hw_pk11.o: ../../include/openssl/pem2.h ../cryptlib.h
+hw_pk11.o: ../../e_os.h hw_pk11_err.c hw_pk11_err.h hw_pk11.c
+hw_pk11_pub.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
+hw_pk11_pub.o: ../../include/openssl/engine.h ../../include/openssl/ossl_typ.h
+hw_pk11_pub.o: ../../include/openssl/bn.h ../../include/openssl/rsa.h
+hw_pk11_pub.o: ../../include/openssl/asn1.h ../../include/openssl/bio.h
+hw_pk11_pub.o: ../../include/openssl/crypto.h ../../include/openssl/stack.h
+hw_pk11_pub.o: ../../include/openssl/safestack.h ../../include/openssl/opensslv.h
+hw_pk11_pub.o: ../../include/openssl/symhacks.h ../../include/openssl/dsa.h
+hw_pk11_pub.o: ../../include/openssl/dh.h ../../include/openssl/rand.h
+hw_pk11_pub.o: ../../include/openssl/ui.h ../../include/openssl/err.h
+hw_pk11_pub.o: ../../include/openssl/lhash.h ../../include/openssl/dso.h
+hw_pk11_pub.o: ../../include/openssl/pem.h ../../include/openssl/evp.h
+hw_pk11_pub.o: ../../include/openssl/md2.h ../../include/openssl/md4.h
+hw_pk11_pub.o: ../../include/openssl/md5.h ../../include/openssl/sha.h
+hw_pk11_pub.o: ../../include/openssl/ripemd.h ../../include/openssl/des.h
+hw_pk11_pub.o: ../../include/openssl/des_old.h ../../include/openssl/ui_compat.h
+hw_pk11_pub.o: ../../include/openssl/rc4.h ../../include/openssl/rc2.h
+hw_pk11_pub.o: ../../crypto/rc5/rc5.h ../../include/openssl/blowfish.h
+hw_pk11_pub.o: ../../include/openssl/cast.h ../../include/openssl/idea.h
+hw_pk11_pub.o: ../../crypto/mdc2/mdc2.h ../../include/openssl/aes.h
+hw_pk11_pub.o: ../../include/openssl/objects.h ../../include/openssl/obj_mac.h
+hw_pk11_pub.o: ../../include/openssl/x509.h ../../include/openssl/buffer.h
+hw_pk11_pub.o: ../../include/openssl/x509_vfy.h ../../include/openssl/pkcs7.h
+hw_pk11_pub.o: ../../include/openssl/pem2.h ../cryptlib.h
+hw_pk11_pub.o: ../../e_os.h hw_pk11_err.c hw_pk11_err.h hw_pk11_pub.c
 tb_cipher.o: ../../e_os.h ../../include/openssl/bio.h
 tb_cipher.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 tb_cipher.o: ../../include/openssl/e_os2.h ../../include/openssl/engine.h
diff -r -u -N openssl-0.9.8g/crypto/engine/pkcs11f.h openssl/crypto/engine/pkcs11f.h
--- openssl-0.9.8g/crypto/engine/pkcs11f.h	1970-01-01 01:00:00.000000000 +0100
+++ openssl/crypto/engine/pkcs11f.h	2007-10-25 01:27:09.000000000 +0200
@@ -0,0 +1,912 @@
+/* pkcs11f.h include file for PKCS #11. */
+/* $Revision: 1.2 $ */
+
+/* License to copy and use this software is granted provided that it is
+ * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
+ * (Cryptoki)" in all material mentioning or referencing this software.
+
+ * License is also granted to make and use derivative works provided that
+ * such works are identified as "derived from the RSA Security Inc. PKCS #11
+ * Cryptographic Token Interface (Cryptoki)" in all material mentioning or 
+ * referencing the derived work.
+
+ * RSA Security Inc. makes no representations concerning either the 
+ * merchantability of this software or the suitability of this software for
+ * any particular purpose. It is provided "as is" without express or implied
+ * warranty of any kind.
+ */
+
+/* This header file contains pretty much everything about all the */
+/* Cryptoki function prototypes.  Because this information is */
+/* used for more than just declaring function prototypes, the */
+/* order of the functions appearing herein is important, and */
+/* should not be altered. */
+
+/* General-purpose */
+
+/* C_Initialize initializes the Cryptoki library. */
+CK_PKCS11_FUNCTION_INFO(C_Initialize)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_VOID_PTR   pInitArgs  /* if this is not NULL_PTR, it gets
+                            * cast to CK_C_INITIALIZE_ARGS_PTR
+                            * and dereferenced */
+);
+#endif
+
+
+/* C_Finalize indicates that an application is done with the
+ * Cryptoki library. */
+CK_PKCS11_FUNCTION_INFO(C_Finalize)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_VOID_PTR   pReserved  /* reserved.  Should be NULL_PTR */
+);
+#endif
+
+
+/* C_GetInfo returns general information about Cryptoki. */
+CK_PKCS11_FUNCTION_INFO(C_GetInfo)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_INFO_PTR   pInfo  /* location that receives information */
+);
+#endif
+
+
+/* C_GetFunctionList returns the function list. */
+CK_PKCS11_FUNCTION_INFO(C_GetFunctionList)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_FUNCTION_LIST_PTR_PTR ppFunctionList  /* receives pointer to
+                                            * function list */
+);
+#endif
+
+
+
+/* Slot and token management */
+
+/* C_GetSlotList obtains a list of slots in the system. */
+CK_PKCS11_FUNCTION_INFO(C_GetSlotList)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_BBOOL       tokenPresent,  /* only slots with tokens? */
+  CK_SLOT_ID_PTR pSlotList,     /* receives array of slot IDs */
+  CK_ULONG_PTR   pulCount       /* receives number of slots */
+);
+#endif
+
+
+/* C_GetSlotInfo obtains information about a particular slot in
+ * the system. */
+CK_PKCS11_FUNCTION_INFO(C_GetSlotInfo)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SLOT_ID       slotID,  /* the ID of the slot */
+  CK_SLOT_INFO_PTR pInfo    /* receives the slot information */
+);
+#endif
+
+
+/* C_GetTokenInfo obtains information about a particular token
+ * in the system. */
+CK_PKCS11_FUNCTION_INFO(C_GetTokenInfo)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SLOT_ID        slotID,  /* ID of the token's slot */
+  CK_TOKEN_INFO_PTR pInfo    /* receives the token information */
+);
+#endif
+
+
+/* C_GetMechanismList obtains a list of mechanism types
+ * supported by a token. */
+CK_PKCS11_FUNCTION_INFO(C_GetMechanismList)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SLOT_ID            slotID,          /* ID of token's slot */
+  CK_MECHANISM_TYPE_PTR pMechanismList,  /* gets mech. array */
+  CK_ULONG_PTR          pulCount         /* gets # of mechs. */
+);
+#endif
+
+
+/* C_GetMechanismInfo obtains information about a particular
+ * mechanism possibly supported by a token. */
+CK_PKCS11_FUNCTION_INFO(C_GetMechanismInfo)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SLOT_ID            slotID,  /* ID of the token's slot */
+  CK_MECHANISM_TYPE     type,    /* type of mechanism */
+  CK_MECHANISM_INFO_PTR pInfo    /* receives mechanism info */
+);
+#endif
+
+
+/* C_InitToken initializes a token. */
+CK_PKCS11_FUNCTION_INFO(C_InitToken)
+#ifdef CK_NEED_ARG_LIST
+/* pLabel changed from CK_CHAR_PTR to CK_UTF8CHAR_PTR for v2.10 */
+(
+  CK_SLOT_ID      slotID,    /* ID of the token's slot */
+  CK_UTF8CHAR_PTR pPin,      /* the SO's initial PIN */
+  CK_ULONG        ulPinLen,  /* length in bytes of the PIN */
+  CK_UTF8CHAR_PTR pLabel     /* 32-byte token label (blank padded) */
+);
+#endif
+
+
+/* C_InitPIN initializes the normal user's PIN. */
+CK_PKCS11_FUNCTION_INFO(C_InitPIN)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,  /* the session's handle */
+  CK_UTF8CHAR_PTR   pPin,      /* the normal user's PIN */
+  CK_ULONG          ulPinLen   /* length in bytes of the PIN */
+);
+#endif
+
+
+/* C_SetPIN modifies the PIN of the user who is logged in. */
+CK_PKCS11_FUNCTION_INFO(C_SetPIN)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,  /* the session's handle */
+  CK_UTF8CHAR_PTR   pOldPin,   /* the old PIN */
+  CK_ULONG          ulOldLen,  /* length of the old PIN */
+  CK_UTF8CHAR_PTR   pNewPin,   /* the new PIN */
+  CK_ULONG          ulNewLen   /* length of the new PIN */
+);
+#endif
+
+
+
+/* Session management */
+
+/* C_OpenSession opens a session between an application and a
+ * token. */
+CK_PKCS11_FUNCTION_INFO(C_OpenSession)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SLOT_ID            slotID,        /* the slot's ID */
+  CK_FLAGS              flags,         /* from CK_SESSION_INFO */
+  CK_VOID_PTR           pApplication,  /* passed to callback */
+  CK_NOTIFY             Notify,        /* callback function */
+  CK_SESSION_HANDLE_PTR phSession      /* gets session handle */
+);
+#endif
+
+
+/* C_CloseSession closes a session between an application and a
+ * token. */
+CK_PKCS11_FUNCTION_INFO(C_CloseSession)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession  /* the session's handle */
+);
+#endif
+
+
+/* C_CloseAllSessions closes all sessions with a token. */
+CK_PKCS11_FUNCTION_INFO(C_CloseAllSessions)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SLOT_ID     slotID  /* the token's slot */
+);
+#endif
+
+
+/* C_GetSessionInfo obtains information about the session. */
+CK_PKCS11_FUNCTION_INFO(C_GetSessionInfo)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE   hSession,  /* the session's handle */
+  CK_SESSION_INFO_PTR pInfo      /* receives session info */
+);
+#endif
+
+
+/* C_GetOperationState obtains the state of the cryptographic operation
+ * in a session. */
+CK_PKCS11_FUNCTION_INFO(C_GetOperationState)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,             /* session's handle */
+  CK_BYTE_PTR       pOperationState,      /* gets state */
+  CK_ULONG_PTR      pulOperationStateLen  /* gets state length */
+);
+#endif
+
+
+/* C_SetOperationState restores the state of the cryptographic
+ * operation in a session. */
+CK_PKCS11_FUNCTION_INFO(C_SetOperationState)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,            /* session's handle */
+  CK_BYTE_PTR      pOperationState,      /* holds state */
+  CK_ULONG         ulOperationStateLen,  /* holds state length */
+  CK_OBJECT_HANDLE hEncryptionKey,       /* en/decryption key */
+  CK_OBJECT_HANDLE hAuthenticationKey    /* sign/verify key */
+);
+#endif
+
+
+/* C_Login logs a user into a token. */
+CK_PKCS11_FUNCTION_INFO(C_Login)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,  /* the session's handle */
+  CK_USER_TYPE      userType,  /* the user type */
+  CK_UTF8CHAR_PTR   pPin,      /* the user's PIN */
+  CK_ULONG          ulPinLen   /* the length of the PIN */
+);
+#endif
+
+
+/* C_Logout logs a user out from a token. */
+CK_PKCS11_FUNCTION_INFO(C_Logout)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession  /* the session's handle */
+);
+#endif
+
+
+
+/* Object management */
+
+/* C_CreateObject creates a new object. */
+CK_PKCS11_FUNCTION_INFO(C_CreateObject)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,    /* the session's handle */
+  CK_ATTRIBUTE_PTR  pTemplate,   /* the object's template */
+  CK_ULONG          ulCount,     /* attributes in template */
+  CK_OBJECT_HANDLE_PTR phObject  /* gets new object's handle. */
+);
+#endif
+
+
+/* C_CopyObject copies an object, creating a new object for the
+ * copy. */
+CK_PKCS11_FUNCTION_INFO(C_CopyObject)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE    hSession,    /* the session's handle */
+  CK_OBJECT_HANDLE     hObject,     /* the object's handle */
+  CK_ATTRIBUTE_PTR     pTemplate,   /* template for new object */
+  CK_ULONG             ulCount,     /* attributes in template */
+  CK_OBJECT_HANDLE_PTR phNewObject  /* receives handle of copy */
+);
+#endif
+
+
+/* C_DestroyObject destroys an object. */
+CK_PKCS11_FUNCTION_INFO(C_DestroyObject)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,  /* the session's handle */
+  CK_OBJECT_HANDLE  hObject    /* the object's handle */
+);
+#endif
+
+
+/* C_GetObjectSize gets the size of an object in bytes. */
+CK_PKCS11_FUNCTION_INFO(C_GetObjectSize)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,  /* the session's handle */
+  CK_OBJECT_HANDLE  hObject,   /* the object's handle */
+  CK_ULONG_PTR      pulSize    /* receives size of object */
+);
+#endif
+
+
+/* C_GetAttributeValue obtains the value of one or more object
+ * attributes. */
+CK_PKCS11_FUNCTION_INFO(C_GetAttributeValue)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,   /* the session's handle */
+  CK_OBJECT_HANDLE  hObject,    /* the object's handle */
+  CK_ATTRIBUTE_PTR  pTemplate,  /* specifies attrs; gets vals */
+  CK_ULONG          ulCount     /* attributes in template */
+);
+#endif
+
+
+/* C_SetAttributeValue modifies the value of one or more object
+ * attributes */
+CK_PKCS11_FUNCTION_INFO(C_SetAttributeValue)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,   /* the session's handle */
+  CK_OBJECT_HANDLE  hObject,    /* the object's handle */
+  CK_ATTRIBUTE_PTR  pTemplate,  /* specifies attrs and values */
+  CK_ULONG          ulCount     /* attributes in template */
+);
+#endif
+
+
+/* C_FindObjectsInit initializes a search for token and session
+ * objects that match a template. */
+CK_PKCS11_FUNCTION_INFO(C_FindObjectsInit)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,   /* the session's handle */
+  CK_ATTRIBUTE_PTR  pTemplate,  /* attribute values to match */
+  CK_ULONG          ulCount     /* attrs in search template */
+);
+#endif
+
+
+/* C_FindObjects continues a search for token and session
+ * objects that match a template, obtaining additional object
+ * handles. */
+CK_PKCS11_FUNCTION_INFO(C_FindObjects)
+#ifdef CK_NEED_ARG_LIST
+(
+ CK_SESSION_HANDLE    hSession,          /* session's handle */
+ CK_OBJECT_HANDLE_PTR phObject,          /* gets obj. handles */
+ CK_ULONG             ulMaxObjectCount,  /* max handles to get */
+ CK_ULONG_PTR         pulObjectCount     /* actual # returned */
+);
+#endif
+
+
+/* C_FindObjectsFinal finishes a search for token and session
+ * objects. */
+CK_PKCS11_FUNCTION_INFO(C_FindObjectsFinal)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession  /* the session's handle */
+);
+#endif
+
+
+
+/* Encryption and decryption */
+
+/* C_EncryptInit initializes an encryption operation. */
+CK_PKCS11_FUNCTION_INFO(C_EncryptInit)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,    /* the session's handle */
+  CK_MECHANISM_PTR  pMechanism,  /* the encryption mechanism */
+  CK_OBJECT_HANDLE  hKey         /* handle of encryption key */
+);
+#endif
+
+
+/* C_Encrypt encrypts single-part data. */
+CK_PKCS11_FUNCTION_INFO(C_Encrypt)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,            /* session's handle */
+  CK_BYTE_PTR       pData,               /* the plaintext data */
+  CK_ULONG          ulDataLen,           /* bytes of plaintext */
+  CK_BYTE_PTR       pEncryptedData,      /* gets ciphertext */
+  CK_ULONG_PTR      pulEncryptedDataLen  /* gets c-text size */
+);
+#endif
+
+
+/* C_EncryptUpdate continues a multiple-part encryption
+ * operation. */
+CK_PKCS11_FUNCTION_INFO(C_EncryptUpdate)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,           /* session's handle */
+  CK_BYTE_PTR       pPart,              /* the plaintext data */
+  CK_ULONG          ulPartLen,          /* plaintext data len */
+  CK_BYTE_PTR       pEncryptedPart,     /* gets ciphertext */
+  CK_ULONG_PTR      pulEncryptedPartLen /* gets c-text size */
+);
+#endif
+
+
+/* C_EncryptFinal finishes a multiple-part encryption
+ * operation. */
+CK_PKCS11_FUNCTION_INFO(C_EncryptFinal)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,                /* session handle */
+  CK_BYTE_PTR       pLastEncryptedPart,      /* last c-text */
+  CK_ULONG_PTR      pulLastEncryptedPartLen  /* gets last size */
+);
+#endif
+
+
+/* C_DecryptInit initializes a decryption operation. */
+CK_PKCS11_FUNCTION_INFO(C_DecryptInit)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,    /* the session's handle */
+  CK_MECHANISM_PTR  pMechanism,  /* the decryption mechanism */
+  CK_OBJECT_HANDLE  hKey         /* handle of decryption key */
+);
+#endif
+
+
+/* C_Decrypt decrypts encrypted data in a single part. */
+CK_PKCS11_FUNCTION_INFO(C_Decrypt)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,           /* session's handle */
+  CK_BYTE_PTR       pEncryptedData,     /* ciphertext */
+  CK_ULONG          ulEncryptedDataLen, /* ciphertext length */
+  CK_BYTE_PTR       pData,              /* gets plaintext */
+  CK_ULONG_PTR      pulDataLen          /* gets p-text size */
+);
+#endif
+
+
+/* C_DecryptUpdate continues a multiple-part decryption
+ * operation. */
+CK_PKCS11_FUNCTION_INFO(C_DecryptUpdate)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,            /* session's handle */
+  CK_BYTE_PTR       pEncryptedPart,      /* encrypted data */
+  CK_ULONG          ulEncryptedPartLen,  /* input length */
+  CK_BYTE_PTR       pPart,               /* gets plaintext */
+  CK_ULONG_PTR      pulPartLen           /* p-text size */
+);
+#endif
+
+
+/* C_DecryptFinal finishes a multiple-part decryption
+ * operation. */
+CK_PKCS11_FUNCTION_INFO(C_DecryptFinal)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,       /* the session's handle */
+  CK_BYTE_PTR       pLastPart,      /* gets plaintext */
+  CK_ULONG_PTR      pulLastPartLen  /* p-text size */
+);
+#endif
+
+
+
+/* Message digesting */
+
+/* C_DigestInit initializes a message-digesting operation. */
+CK_PKCS11_FUNCTION_INFO(C_DigestInit)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,   /* the session's handle */
+  CK_MECHANISM_PTR  pMechanism  /* the digesting mechanism */
+);
+#endif
+
+
+/* C_Digest digests data in a single part. */
+CK_PKCS11_FUNCTION_INFO(C_Digest)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,     /* the session's handle */
+  CK_BYTE_PTR       pData,        /* data to be digested */
+  CK_ULONG          ulDataLen,    /* bytes of data to digest */
+  CK_BYTE_PTR       pDigest,      /* gets the message digest */
+  CK_ULONG_PTR      pulDigestLen  /* gets digest length */
+);
+#endif
+
+
+/* C_DigestUpdate continues a multiple-part message-digesting
+ * operation. */
+CK_PKCS11_FUNCTION_INFO(C_DigestUpdate)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,  /* the session's handle */
+  CK_BYTE_PTR       pPart,     /* data to be digested */
+  CK_ULONG          ulPartLen  /* bytes of data to be digested */
+);
+#endif
+
+
+/* C_DigestKey continues a multi-part message-digesting
+ * operation, by digesting the value of a secret key as part of
+ * the data already digested. */
+CK_PKCS11_FUNCTION_INFO(C_DigestKey)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,  /* the session's handle */
+  CK_OBJECT_HANDLE  hKey       /* secret key to digest */
+);
+#endif
+
+
+/* C_DigestFinal finishes a multiple-part message-digesting
+ * operation. */
+CK_PKCS11_FUNCTION_INFO(C_DigestFinal)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,     /* the session's handle */
+  CK_BYTE_PTR       pDigest,      /* gets the message digest */
+  CK_ULONG_PTR      pulDigestLen  /* gets byte count of digest */
+);
+#endif
+
+
+
+/* Signing and MACing */
+
+/* C_SignInit initializes a signature (private key encryption)
+ * operation, where the signature is (will be) an appendix to
+ * the data, and plaintext cannot be recovered from the
+ *signature. */
+CK_PKCS11_FUNCTION_INFO(C_SignInit)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,    /* the session's handle */
+  CK_MECHANISM_PTR  pMechanism,  /* the signature mechanism */
+  CK_OBJECT_HANDLE  hKey         /* handle of signature key */
+);
+#endif
+
+
+/* C_Sign signs (encrypts with private key) data in a single
+ * part, where the signature is (will be) an appendix to the
+ * data, and plaintext cannot be recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_Sign)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,        /* the session's handle */
+  CK_BYTE_PTR       pData,           /* the data to sign */
+  CK_ULONG          ulDataLen,       /* count of bytes to sign */
+  CK_BYTE_PTR       pSignature,      /* gets the signature */
+  CK_ULONG_PTR      pulSignatureLen  /* gets signature length */
+);
+#endif
+
+
+/* C_SignUpdate continues a multiple-part signature operation,
+ * where the signature is (will be) an appendix to the data, 
+ * and plaintext cannot be recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_SignUpdate)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,  /* the session's handle */
+  CK_BYTE_PTR       pPart,     /* the data to sign */
+  CK_ULONG          ulPartLen  /* count of bytes to sign */
+);
+#endif
+
+
+/* C_SignFinal finishes a multiple-part signature operation, 
+ * returning the signature. */
+CK_PKCS11_FUNCTION_INFO(C_SignFinal)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,        /* the session's handle */
+  CK_BYTE_PTR       pSignature,      /* gets the signature */
+  CK_ULONG_PTR      pulSignatureLen  /* gets signature length */
+);
+#endif
+
+
+/* C_SignRecoverInit initializes a signature operation, where
+ * the data can be recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_SignRecoverInit)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,   /* the session's handle */
+  CK_MECHANISM_PTR  pMechanism, /* the signature mechanism */
+  CK_OBJECT_HANDLE  hKey        /* handle of the signature key */
+);
+#endif
+
+
+/* C_SignRecover signs data in a single operation, where the
+ * data can be recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_SignRecover)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,        /* the session's handle */
+  CK_BYTE_PTR       pData,           /* the data to sign */
+  CK_ULONG          ulDataLen,       /* count of bytes to sign */
+  CK_BYTE_PTR       pSignature,      /* gets the signature */
+  CK_ULONG_PTR      pulSignatureLen  /* gets signature length */
+);
+#endif
+
+
+
+/* Verifying signatures and MACs */
+
+/* C_VerifyInit initializes a verification operation, where the
+ * signature is an appendix to the data, and plaintext cannot
+ *  cannot be recovered from the signature (e.g. DSA). */
+CK_PKCS11_FUNCTION_INFO(C_VerifyInit)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,    /* the session's handle */
+  CK_MECHANISM_PTR  pMechanism,  /* the verification mechanism */
+  CK_OBJECT_HANDLE  hKey         /* verification key */ 
+);
+#endif
+
+
+/* C_Verify verifies a signature in a single-part operation, 
+ * where the signature is an appendix to the data, and plaintext
+ * cannot be recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_Verify)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,       /* the session's handle */
+  CK_BYTE_PTR       pData,          /* signed data */
+  CK_ULONG          ulDataLen,      /* length of signed data */
+  CK_BYTE_PTR       pSignature,     /* signature */
+  CK_ULONG          ulSignatureLen  /* signature length*/
+);
+#endif
+
+
+/* C_VerifyUpdate continues a multiple-part verification
+ * operation, where the signature is an appendix to the data, 
+ * and plaintext cannot be recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_VerifyUpdate)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,  /* the session's handle */
+  CK_BYTE_PTR       pPart,     /* signed data */
+  CK_ULONG          ulPartLen  /* length of signed data */
+);
+#endif
+
+
+/* C_VerifyFinal finishes a multiple-part verification
+ * operation, checking the signature. */
+CK_PKCS11_FUNCTION_INFO(C_VerifyFinal)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,       /* the session's handle */
+  CK_BYTE_PTR       pSignature,     /* signature to verify */
+  CK_ULONG          ulSignatureLen  /* signature length */
+);
+#endif
+
+
+/* C_VerifyRecoverInit initializes a signature verification
+ * operation, where the data is recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_VerifyRecoverInit)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,    /* the session's handle */
+  CK_MECHANISM_PTR  pMechanism,  /* the verification mechanism */
+  CK_OBJECT_HANDLE  hKey         /* verification key */
+);
+#endif
+
+
+/* C_VerifyRecover verifies a signature in a single-part
+ * operation, where the data is recovered from the signature. */
+CK_PKCS11_FUNCTION_INFO(C_VerifyRecover)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,        /* the session's handle */
+  CK_BYTE_PTR       pSignature,      /* signature to verify */
+  CK_ULONG          ulSignatureLen,  /* signature length */
+  CK_BYTE_PTR       pData,           /* gets signed data */
+  CK_ULONG_PTR      pulDataLen       /* gets signed data len */
+);
+#endif
+
+
+
+/* Dual-function cryptographic operations */
+
+/* C_DigestEncryptUpdate continues a multiple-part digesting
+ * and encryption operation. */
+CK_PKCS11_FUNCTION_INFO(C_DigestEncryptUpdate)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,            /* session's handle */
+  CK_BYTE_PTR       pPart,               /* the plaintext data */
+  CK_ULONG          ulPartLen,           /* plaintext length */
+  CK_BYTE_PTR       pEncryptedPart,      /* gets ciphertext */
+  CK_ULONG_PTR      pulEncryptedPartLen  /* gets c-text length */
+);
+#endif
+
+
+/* C_DecryptDigestUpdate continues a multiple-part decryption and
+ * digesting operation. */
+CK_PKCS11_FUNCTION_INFO(C_DecryptDigestUpdate)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,            /* session's handle */
+  CK_BYTE_PTR       pEncryptedPart,      /* ciphertext */
+  CK_ULONG          ulEncryptedPartLen,  /* ciphertext length */
+  CK_BYTE_PTR       pPart,               /* gets plaintext */
+  CK_ULONG_PTR      pulPartLen           /* gets plaintext len */
+);
+#endif
+
+
+/* C_SignEncryptUpdate continues a multiple-part signing and
+ * encryption operation. */
+CK_PKCS11_FUNCTION_INFO(C_SignEncryptUpdate)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,            /* session's handle */
+  CK_BYTE_PTR       pPart,               /* the plaintext data */
+  CK_ULONG          ulPartLen,           /* plaintext length */
+  CK_BYTE_PTR       pEncryptedPart,      /* gets ciphertext */
+  CK_ULONG_PTR      pulEncryptedPartLen  /* gets c-text length */
+);
+#endif
+
+
+/* C_DecryptVerifyUpdate continues a multiple-part decryption and
+ * verify operation. */
+CK_PKCS11_FUNCTION_INFO(C_DecryptVerifyUpdate)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,            /* session's handle */
+  CK_BYTE_PTR       pEncryptedPart,      /* ciphertext */
+  CK_ULONG          ulEncryptedPartLen,  /* ciphertext length */
+  CK_BYTE_PTR       pPart,               /* gets plaintext */
+  CK_ULONG_PTR      pulPartLen           /* gets p-text length */
+);
+#endif
+
+
+
+/* Key management */
+
+/* C_GenerateKey generates a secret key, creating a new key
+ * object. */
+CK_PKCS11_FUNCTION_INFO(C_GenerateKey)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE    hSession,    /* the session's handle */
+  CK_MECHANISM_PTR     pMechanism,  /* key generation mech. */
+  CK_ATTRIBUTE_PTR     pTemplate,   /* template for new key */
+  CK_ULONG             ulCount,     /* # of attrs in template */
+  CK_OBJECT_HANDLE_PTR phKey        /* gets handle of new key */
+);
+#endif
+
+
+/* C_GenerateKeyPair generates a public-key/private-key pair, 
+ * creating new key objects. */
+CK_PKCS11_FUNCTION_INFO(C_GenerateKeyPair)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE    hSession,                    /* session
+                                                     * handle */
+  CK_MECHANISM_PTR     pMechanism,                  /* key-gen
+                                                     * mech. */
+  CK_ATTRIBUTE_PTR     pPublicKeyTemplate,          /* template
+                                                     * for pub.
+                                                     * key */
+  CK_ULONG             ulPublicKeyAttributeCount,   /* # pub.
+                                                     * attrs. */
+  CK_ATTRIBUTE_PTR     pPrivateKeyTemplate,         /* template
+                                                     * for priv.
+                                                     * key */
+  CK_ULONG             ulPrivateKeyAttributeCount,  /* # priv.
+                                                     * attrs. */
+  CK_OBJECT_HANDLE_PTR phPublicKey,                 /* gets pub.
+                                                     * key
+                                                     * handle */
+  CK_OBJECT_HANDLE_PTR phPrivateKey                 /* gets
+                                                     * priv. key
+                                                     * handle */
+);
+#endif
+
+
+/* C_WrapKey wraps (i.e., encrypts) a key. */
+CK_PKCS11_FUNCTION_INFO(C_WrapKey)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,        /* the session's handle */
+  CK_MECHANISM_PTR  pMechanism,      /* the wrapping mechanism */
+  CK_OBJECT_HANDLE  hWrappingKey,    /* wrapping key */
+  CK_OBJECT_HANDLE  hKey,            /* key to be wrapped */
+  CK_BYTE_PTR       pWrappedKey,     /* gets wrapped key */
+  CK_ULONG_PTR      pulWrappedKeyLen /* gets wrapped key size */
+);
+#endif
+
+
+/* C_UnwrapKey unwraps (decrypts) a wrapped key, creating a new
+ * key object. */
+CK_PKCS11_FUNCTION_INFO(C_UnwrapKey)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE    hSession,          /* session's handle */
+  CK_MECHANISM_PTR     pMechanism,        /* unwrapping mech. */
+  CK_OBJECT_HANDLE     hUnwrappingKey,    /* unwrapping key */
+  CK_BYTE_PTR          pWrappedKey,       /* the wrapped key */
+  CK_ULONG             ulWrappedKeyLen,   /* wrapped key len */
+  CK_ATTRIBUTE_PTR     pTemplate,         /* new key template */
+  CK_ULONG             ulAttributeCount,  /* template length */
+  CK_OBJECT_HANDLE_PTR phKey              /* gets new handle */
+);
+#endif
+
+
+/* C_DeriveKey derives a key from a base key, creating a new key
+ * object. */
+CK_PKCS11_FUNCTION_INFO(C_DeriveKey)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE    hSession,          /* session's handle */
+  CK_MECHANISM_PTR     pMechanism,        /* key deriv. mech. */
+  CK_OBJECT_HANDLE     hBaseKey,          /* base key */
+  CK_ATTRIBUTE_PTR     pTemplate,         /* new key template */
+  CK_ULONG             ulAttributeCount,  /* template length */
+  CK_OBJECT_HANDLE_PTR phKey              /* gets new handle */
+);
+#endif
+
+
+
+/* Random number generation */
+
+/* C_SeedRandom mixes additional seed material into the token's
+ * random number generator. */
+CK_PKCS11_FUNCTION_INFO(C_SeedRandom)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,  /* the session's handle */
+  CK_BYTE_PTR       pSeed,     /* the seed material */
+  CK_ULONG          ulSeedLen  /* length of seed material */
+);
+#endif
+
+
+/* C_GenerateRandom generates random data. */
+CK_PKCS11_FUNCTION_INFO(C_GenerateRandom)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession,    /* the session's handle */
+  CK_BYTE_PTR       RandomData,  /* receives the random data */
+  CK_ULONG          ulRandomLen  /* # of bytes to generate */
+);
+#endif
+
+
+
+/* Parallel function management */
+
+/* C_GetFunctionStatus is a legacy function; it obtains an
+ * updated status of a function running in parallel with an
+ * application. */
+CK_PKCS11_FUNCTION_INFO(C_GetFunctionStatus)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession  /* the session's handle */
+);
+#endif
+
+
+/* C_CancelFunction is a legacy function; it cancels a function
+ * running in parallel. */
+CK_PKCS11_FUNCTION_INFO(C_CancelFunction)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_SESSION_HANDLE hSession  /* the session's handle */
+);
+#endif
+
+
+
+/* Functions added in for Cryptoki Version 2.01 or later */
+
+/* C_WaitForSlotEvent waits for a slot event (token insertion,
+ * removal, etc.) to occur. */
+CK_PKCS11_FUNCTION_INFO(C_WaitForSlotEvent)
+#ifdef CK_NEED_ARG_LIST
+(
+  CK_FLAGS flags,        /* blocking/nonblocking flag */
+  CK_SLOT_ID_PTR pSlot,  /* location that receives the slot ID */
+  CK_VOID_PTR pRserved   /* reserved.  Should be NULL_PTR */
+);
+#endif
diff -r -u -N openssl-0.9.8g/crypto/engine/pkcs11.h openssl/crypto/engine/pkcs11.h
--- openssl-0.9.8g/crypto/engine/pkcs11.h	1970-01-01 01:00:00.000000000 +0100
+++ openssl/crypto/engine/pkcs11.h	2007-10-25 01:27:09.000000000 +0200
@@ -0,0 +1,299 @@
+/* pkcs11.h include file for PKCS #11. */
+/* $Revision: 1.2 $ */
+
+/* License to copy and use this software is granted provided that it is
+ * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
+ * (Cryptoki)" in all material mentioning or referencing this software.
+
+ * License is also granted to make and use derivative works provided that
+ * such works are identified as "derived from the RSA Security Inc. PKCS #11
+ * Cryptographic Token Interface (Cryptoki)" in all material mentioning or 
+ * referencing the derived work.
+
+ * RSA Security Inc. makes no representations concerning either the 
+ * merchantability of this software or the suitability of this software for
+ * any particular purpose. It is provided "as is" without express or implied
+ * warranty of any kind.
+ */
+
+#ifndef _PKCS11_H_
+#define _PKCS11_H_ 1
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Before including this file (pkcs11.h) (or pkcs11t.h by
+ * itself), 6 platform-specific macros must be defined.  These
+ * macros are described below, and typical definitions for them
+ * are also given.  Be advised that these definitions can depend
+ * on both the platform and the compiler used (and possibly also
+ * on whether a Cryptoki library is linked statically or
+ * dynamically).
+ *
+ * In addition to defining these 6 macros, the packing convention
+ * for Cryptoki structures should be set.  The Cryptoki
+ * convention on packing is that structures should be 1-byte
+ * aligned.
+ *
+ * If you're using Microsoft Developer Studio 5.0 to produce
+ * Win32 stuff, this might be done by using the following
+ * preprocessor directive before including pkcs11.h or pkcs11t.h:
+ *
+ * #pragma pack(push, cryptoki, 1)
+ *
+ * and using the following preprocessor directive after including
+ * pkcs11.h or pkcs11t.h:
+ *
+ * #pragma pack(pop, cryptoki)
+ *
+ * If you're using an earlier version of Microsoft Developer
+ * Studio to produce Win16 stuff, this might be done by using
+ * the following preprocessor directive before including
+ * pkcs11.h or pkcs11t.h:
+ *
+ * #pragma pack(1)
+ *
+ * In a UNIX environment, you're on your own for this.  You might
+ * not need to do (or be able to do!) anything.
+ *
+ *
+ * Now for the macros:
+ *
+ *
+ * 1. CK_PTR: The indirection string for making a pointer to an
+ * object.  It can be used like this:
+ *
+ * typedef CK_BYTE CK_PTR CK_BYTE_PTR;
+ *
+ * If you're using Microsoft Developer Studio 5.0 to produce
+ * Win32 stuff, it might be defined by:
+ *
+ * #define CK_PTR *
+ *
+ * If you're using an earlier version of Microsoft Developer
+ * Studio to produce Win16 stuff, it might be defined by:
+ *
+ * #define CK_PTR far *
+ *
+ * In a typical UNIX environment, it might be defined by:
+ *
+ * #define CK_PTR *
+ *
+ *
+ * 2. CK_DEFINE_FUNCTION(returnType, name): A macro which makes
+ * an exportable Cryptoki library function definition out of a
+ * return type and a function name.  It should be used in the
+ * following fashion to define the exposed Cryptoki functions in
+ * a Cryptoki library:
+ *
+ * CK_DEFINE_FUNCTION(CK_RV, C_Initialize)(
+ *   CK_VOID_PTR pReserved
+ * )
+ * {
+ *   ...
+ * }
+ *
+ * If you're using Microsoft Developer Studio 5.0 to define a
+ * function in a Win32 Cryptoki .dll, it might be defined by:
+ *
+ * #define CK_DEFINE_FUNCTION(returnType, name) \
+ *   returnType __declspec(dllexport) name
+ *
+ * If you're using an earlier version of Microsoft Developer
+ * Studio to define a function in a Win16 Cryptoki .dll, it
+ * might be defined by:
+ *
+ * #define CK_DEFINE_FUNCTION(returnType, name) \
+ *   returnType __export _far _pascal name
+ *
+ * In a UNIX environment, it might be defined by:
+ *
+ * #define CK_DEFINE_FUNCTION(returnType, name) \
+ *   returnType name
+ *
+ *
+ * 3. CK_DECLARE_FUNCTION(returnType, name): A macro which makes
+ * an importable Cryptoki library function declaration out of a
+ * return type and a function name.  It should be used in the
+ * following fashion:
+ *
+ * extern CK_DECLARE_FUNCTION(CK_RV, C_Initialize)(
+ *   CK_VOID_PTR pReserved
+ * );
+ *
+ * If you're using Microsoft Developer Studio 5.0 to declare a
+ * function in a Win32 Cryptoki .dll, it might be defined by:
+ *
+ * #define CK_DECLARE_FUNCTION(returnType, name) \
+ *   returnType __declspec(dllimport) name
+ *
+ * If you're using an earlier version of Microsoft Developer
+ * Studio to declare a function in a Win16 Cryptoki .dll, it
+ * might be defined by:
+ *
+ * #define CK_DECLARE_FUNCTION(returnType, name) \
+ *   returnType __export _far _pascal name
+ *
+ * In a UNIX environment, it might be defined by:
+ *
+ * #define CK_DECLARE_FUNCTION(returnType, name) \
+ *   returnType name
+ *
+ *
+ * 4. CK_DECLARE_FUNCTION_POINTER(returnType, name): A macro
+ * which makes a Cryptoki API function pointer declaration or
+ * function pointer type declaration out of a return type and a
+ * function name.  It should be used in the following fashion:
+ *
+ * // Define funcPtr to be a pointer to a Cryptoki API function
+ * // taking arguments args and returning CK_RV.
+ * CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtr)(args);
+ *
+ * or
+ *
+ * // Define funcPtrType to be the type of a pointer to a
+ * // Cryptoki API function taking arguments args and returning
+ * // CK_RV, and then define funcPtr to be a variable of type
+ * // funcPtrType.
+ * typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtrType)(args);
+ * funcPtrType funcPtr;
+ *
+ * If you're using Microsoft Developer Studio 5.0 to access
+ * functions in a Win32 Cryptoki .dll, in might be defined by:
+ *
+ * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
+ *   returnType __declspec(dllimport) (* name)
+ *
+ * If you're using an earlier version of Microsoft Developer
+ * Studio to access functions in a Win16 Cryptoki .dll, it might
+ * be defined by:
+ *
+ * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
+ *   returnType __export _far _pascal (* name)
+ *
+ * In a UNIX environment, it might be defined by:
+ *
+ * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
+ *   returnType (* name)
+ *
+ *
+ * 5. CK_CALLBACK_FUNCTION(returnType, name): A macro which makes
+ * a function pointer type for an application callback out of
+ * a return type for the callback and a name for the callback.
+ * It should be used in the following fashion:
+ *
+ * CK_CALLBACK_FUNCTION(CK_RV, myCallback)(args);
+ *
+ * to declare a function pointer, myCallback, to a callback
+ * which takes arguments args and returns a CK_RV.  It can also
+ * be used like this:
+ *
+ * typedef CK_CALLBACK_FUNCTION(CK_RV, myCallbackType)(args);
+ * myCallbackType myCallback;
+ *
+ * If you're using Microsoft Developer Studio 5.0 to do Win32
+ * Cryptoki development, it might be defined by:
+ *
+ * #define CK_CALLBACK_FUNCTION(returnType, name) \
+ *   returnType (* name)
+ *
+ * If you're using an earlier version of Microsoft Developer
+ * Studio to do Win16 development, it might be defined by:
+ *
+ * #define CK_CALLBACK_FUNCTION(returnType, name) \
+ *   returnType _far _pascal (* name)
+ *
+ * In a UNIX environment, it might be defined by:
+ *
+ * #define CK_CALLBACK_FUNCTION(returnType, name) \
+ *   returnType (* name)
+ *
+ *
+ * 6. NULL_PTR: This macro is the value of a NULL pointer.
+ *
+ * In any ANSI/ISO C environment (and in many others as well),
+ * this should best be defined by
+ *
+ * #ifndef NULL_PTR
+ * #define NULL_PTR 0
+ * #endif
+ */
+
+
+/* All the various Cryptoki types and #define'd values are in the
+ * file pkcs11t.h. */
+#include "pkcs11t.h"
+
+#define __PASTE(x,y)      x##y
+
+
+/* ==============================================================
+ * Define the "extern" form of all the entry points.
+ * ==============================================================
+ */
+
+#define CK_NEED_ARG_LIST  1
+#define CK_PKCS11_FUNCTION_INFO(name) \
+  extern CK_DECLARE_FUNCTION(CK_RV, name)
+
+/* pkcs11f.h has all the information about the Cryptoki
+ * function prototypes. */
+#include "pkcs11f.h"
+
+#undef CK_NEED_ARG_LIST
+#undef CK_PKCS11_FUNCTION_INFO
+
+
+/* ==============================================================
+ * Define the typedef form of all the entry points.  That is, for
+ * each Cryptoki function C_XXX, define a type CK_C_XXX which is
+ * a pointer to that kind of function.
+ * ==============================================================
+ */
+
+#define CK_NEED_ARG_LIST  1
+#define CK_PKCS11_FUNCTION_INFO(name) \
+  typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, __PASTE(CK_,name))
+
+/* pkcs11f.h has all the information about the Cryptoki
+ * function prototypes. */
+#include "pkcs11f.h"
+
+#undef CK_NEED_ARG_LIST
+#undef CK_PKCS11_FUNCTION_INFO
+
+
+/* ==============================================================
+ * Define structed vector of entry points.  A CK_FUNCTION_LIST
+ * contains a CK_VERSION indicating a library's Cryptoki version
+ * and then a whole slew of function pointers to the routines in
+ * the library.  This type was declared, but not defined, in
+ * pkcs11t.h.
+ * ==============================================================
+ */
+
+#define CK_PKCS11_FUNCTION_INFO(name) \
+  __PASTE(CK_,name) name;
+  
+struct CK_FUNCTION_LIST {
+
+  CK_VERSION    version;  /* Cryptoki version */
+
+/* Pile all the function pointers into the CK_FUNCTION_LIST. */
+/* pkcs11f.h has all the information about the Cryptoki
+ * function prototypes. */
+#include "pkcs11f.h"
+
+};
+
+#undef CK_PKCS11_FUNCTION_INFO
+
+
+#undef __PASTE
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff -r -u -N openssl-0.9.8g/crypto/engine/pkcs11t.h openssl/crypto/engine/pkcs11t.h
--- openssl-0.9.8g/crypto/engine/pkcs11t.h	1970-01-01 01:00:00.000000000 +0100
+++ openssl/crypto/engine/pkcs11t.h	2007-10-25 01:27:09.000000000 +0200
@@ -0,0 +1,1685 @@
+/* pkcs11t.h include file for PKCS #11. */
+/* $Revision: 1.2 $ */
+
+/* License to copy and use this software is granted provided that it is
+ * identified as "RSA Security Inc. PKCS #11 Cryptographic Token Interface
+ * (Cryptoki)" in all material mentioning or referencing this software.
+
+ * License is also granted to make and use derivative works provided that
+ * such works are identified as "derived from the RSA Security Inc. PKCS #11
+ * Cryptographic Token Interface (Cryptoki)" in all material mentioning or
+ * referencing the derived work.
+
+ * RSA Security Inc. makes no representations concerning either the
+ * merchantability of this software or the suitability of this software for
+ * any particular purpose. It is provided "as is" without express or implied
+ * warranty of any kind.
+ */
+
+/* See top of pkcs11.h for information about the macros that
+ * must be defined and the structure-packing conventions that
+ * must be set before including this file. */
+
+#ifndef _PKCS11T_H_
+#define _PKCS11T_H_ 1
+
+#define CK_TRUE 1
+#define CK_FALSE 0
+
+#ifndef CK_DISABLE_TRUE_FALSE
+#ifndef FALSE
+#define FALSE CK_FALSE
+#endif
+
+#ifndef TRUE
+#define TRUE CK_TRUE
+#endif
+#endif
+
+/* an unsigned 8-bit value */
+typedef unsigned char     CK_BYTE;
+
+/* an unsigned 8-bit character */
+typedef CK_BYTE           CK_CHAR;
+
+/* an 8-bit UTF-8 character */
+typedef CK_BYTE           CK_UTF8CHAR;
+
+/* a BYTE-sized Boolean flag */
+typedef CK_BYTE           CK_BBOOL;
+
+/* an unsigned value, at least 32 bits long */
+typedef unsigned long int CK_ULONG;
+
+/* a signed value, the same size as a CK_ULONG */
+/* CK_LONG is new for v2.0 */
+typedef long int          CK_LONG;
+
+/* at least 32 bits; each bit is a Boolean flag */
+typedef CK_ULONG          CK_FLAGS;
+
+
+/* some special values for certain CK_ULONG variables */
+#define CK_UNAVAILABLE_INFORMATION (~0UL)
+#define CK_EFFECTIVELY_INFINITE    0
+
+
+typedef CK_BYTE     CK_PTR   CK_BYTE_PTR;
+typedef CK_CHAR     CK_PTR   CK_CHAR_PTR;
+typedef CK_UTF8CHAR CK_PTR   CK_UTF8CHAR_PTR;
+typedef CK_ULONG    CK_PTR   CK_ULONG_PTR;
+typedef void        CK_PTR   CK_VOID_PTR;
+
+/* Pointer to a CK_VOID_PTR-- i.e., pointer to pointer to void */
+typedef CK_VOID_PTR CK_PTR CK_VOID_PTR_PTR;
+
+
+/* The following value is always invalid if used as a session */
+/* handle or object handle */
+#define CK_INVALID_HANDLE 0
+
+
+typedef struct CK_VERSION {
+  CK_BYTE       major;  /* integer portion of version number */
+  CK_BYTE       minor;  /* 1/100ths portion of version number */
+} CK_VERSION;
+
+typedef CK_VERSION CK_PTR CK_VERSION_PTR;
+
+
+typedef struct CK_INFO {
+  /* manufacturerID and libraryDecription have been changed from
+   * CK_CHAR to CK_UTF8CHAR for v2.10 */
+  CK_VERSION    cryptokiVersion;     /* Cryptoki interface ver */
+  CK_UTF8CHAR   manufacturerID[32];  /* blank padded */
+  CK_FLAGS      flags;               /* must be zero */
+
+  /* libraryDescription and libraryVersion are new for v2.0 */
+  CK_UTF8CHAR   libraryDescription[32];  /* blank padded */
+  CK_VERSION    libraryVersion;          /* version of library */
+} CK_INFO;
+
+typedef CK_INFO CK_PTR    CK_INFO_PTR;
+
+
+/* CK_NOTIFICATION enumerates the types of notifications that
+ * Cryptoki provides to an application */
+/* CK_NOTIFICATION has been changed from an enum to a CK_ULONG
+ * for v2.0 */
+typedef CK_ULONG CK_NOTIFICATION;
+#define CKN_SURRENDER       0
+
+
+typedef CK_ULONG          CK_SLOT_ID;
+
+typedef CK_SLOT_ID CK_PTR CK_SLOT_ID_PTR;
+
+
+/* CK_SLOT_INFO provides information about a slot */
+typedef struct CK_SLOT_INFO {
+  /* slotDescription and manufacturerID have been changed from
+   * CK_CHAR to CK_UTF8CHAR for v2.10 */
+  CK_UTF8CHAR   slotDescription[64];  /* blank padded */
+  CK_UTF8CHAR   manufacturerID[32];   /* blank padded */
+  CK_FLAGS      flags;
+
+  /* hardwareVersion and firmwareVersion are new for v2.0 */
+  CK_VERSION    hardwareVersion;  /* version of hardware */
+  CK_VERSION    firmwareVersion;  /* version of firmware */
+} CK_SLOT_INFO;
+
+/* flags: bit flags that provide capabilities of the slot
+ *      Bit Flag              Mask        Meaning
+ */
+#define CKF_TOKEN_PRESENT     0x00000001  /* a token is there */
+#define CKF_REMOVABLE_DEVICE  0x00000002  /* removable devices*/
+#define CKF_HW_SLOT           0x00000004  /* hardware slot */
+
+typedef CK_SLOT_INFO CK_PTR CK_SLOT_INFO_PTR;
+
+
+/* CK_TOKEN_INFO provides information about a token */
+typedef struct CK_TOKEN_INFO {
+  /* label, manufacturerID, and model have been changed from
+   * CK_CHAR to CK_UTF8CHAR for v2.10 */
+  CK_UTF8CHAR   label[32];           /* blank padded */
+  CK_UTF8CHAR   manufacturerID[32];  /* blank padded */
+  CK_UTF8CHAR   model[16];           /* blank padded */
+  CK_CHAR       serialNumber[16];    /* blank padded */
+  CK_FLAGS      flags;               /* see below */
+
+  /* ulMaxSessionCount, ulSessionCount, ulMaxRwSessionCount,
+   * ulRwSessionCount, ulMaxPinLen, and ulMinPinLen have all been
+   * changed from CK_USHORT to CK_ULONG for v2.0 */
+  CK_ULONG      ulMaxSessionCount;     /* max open sessions */
+  CK_ULONG      ulSessionCount;        /* sess. now open */
+  CK_ULONG      ulMaxRwSessionCount;   /* max R/W sessions */
+  CK_ULONG      ulRwSessionCount;      /* R/W sess. now open */
+  CK_ULONG      ulMaxPinLen;           /* in bytes */
+  CK_ULONG      ulMinPinLen;           /* in bytes */
+  CK_ULONG      ulTotalPublicMemory;   /* in bytes */
+  CK_ULONG      ulFreePublicMemory;    /* in bytes */
+  CK_ULONG      ulTotalPrivateMemory;  /* in bytes */
+  CK_ULONG      ulFreePrivateMemory;   /* in bytes */
+
+  /* hardwareVersion, firmwareVersion, and time are new for
+   * v2.0 */
+  CK_VERSION    hardwareVersion;       /* version of hardware */
+  CK_VERSION    firmwareVersion;       /* version of firmware */
+  CK_CHAR       utcTime[16];           /* time */
+} CK_TOKEN_INFO;
+
+/* The flags parameter is defined as follows:
+ *      Bit Flag                    Mask        Meaning
+ */
+#define CKF_RNG                     0x00000001  /* has random #
+                                                 * generator */
+#define CKF_WRITE_PROTECTED         0x00000002  /* token is
+                                                 * write-
+                                                 * protected */
+#define CKF_LOGIN_REQUIRED          0x00000004  /* user must
+                                                 * login */
+#define CKF_USER_PIN_INITIALIZED    0x00000008  /* normal user's
+                                                 * PIN is set */
+
+/* CKF_RESTORE_KEY_NOT_NEEDED is new for v2.0.  If it is set,
+ * that means that *every* time the state of cryptographic
+ * operations of a session is successfully saved, all keys
+ * needed to continue those operations are stored in the state */
+#define CKF_RESTORE_KEY_NOT_NEEDED  0x00000020
+
+/* CKF_CLOCK_ON_TOKEN is new for v2.0.  If it is set, that means
+ * that the token has some sort of clock.  The time on that
+ * clock is returned in the token info structure */
+#define CKF_CLOCK_ON_TOKEN          0x00000040
+
+/* CKF_PROTECTED_AUTHENTICATION_PATH is new for v2.0.  If it is
+ * set, that means that there is some way for the user to login
+ * without sending a PIN through the Cryptoki library itself */
+#define CKF_PROTECTED_AUTHENTICATION_PATH 0x00000100
+
+/* CKF_DUAL_CRYPTO_OPERATIONS is new for v2.0.  If it is true,
+ * that means that a single session with the token can perform
+ * dual simultaneous cryptographic operations (digest and
+ * encrypt; decrypt and digest; sign and encrypt; and decrypt
+ * and sign) */
+#define CKF_DUAL_CRYPTO_OPERATIONS  0x00000200
+
+/* CKF_TOKEN_INITIALIZED if new for v2.10. If it is true, the
+ * token has been initialized using C_InitializeToken or an
+ * equivalent mechanism outside the scope of PKCS #11.
+ * Calling C_InitializeToken when this flag is set will cause
+ * the token to be reinitialized. */
+#define CKF_TOKEN_INITIALIZED       0x00000400
+
+/* CKF_SECONDARY_AUTHENTICATION if new for v2.10. If it is
+ * true, the token supports secondary authentication for
+ * private key objects. This flag is deprecated in v2.11 and
+   onwards. */
+#define CKF_SECONDARY_AUTHENTICATION  0x00000800
+
+/* CKF_USER_PIN_COUNT_LOW if new for v2.10. If it is true, an
+ * incorrect user login PIN has been entered at least once
+ * since the last successful authentication. */
+#define CKF_USER_PIN_COUNT_LOW       0x00010000
+
+/* CKF_USER_PIN_FINAL_TRY if new for v2.10. If it is true,
+ * supplying an incorrect user PIN will it to become locked. */
+#define CKF_USER_PIN_FINAL_TRY       0x00020000
+
+/* CKF_USER_PIN_LOCKED if new for v2.10. If it is true, the
+ * user PIN has been locked. User login to the token is not
+ * possible. */
+#define CKF_USER_PIN_LOCKED          0x00040000
+
+/* CKF_USER_PIN_TO_BE_CHANGED if new for v2.10. If it is true,
+ * the user PIN value is the default value set by token
+ * initialization or manufacturing, or the PIN has been
+ * expired by the card. */
+#define CKF_USER_PIN_TO_BE_CHANGED   0x00080000
+
+/* CKF_SO_PIN_COUNT_LOW if new for v2.10. If it is true, an
+ * incorrect SO login PIN has been entered at least once since
+ * the last successful authentication. */
+#define CKF_SO_PIN_COUNT_LOW         0x00100000
+
+/* CKF_SO_PIN_FINAL_TRY if new for v2.10. If it is true,
+ * supplying an incorrect SO PIN will it to become locked. */
+#define CKF_SO_PIN_FINAL_TRY         0x00200000
+
+/* CKF_SO_PIN_LOCKED if new for v2.10. If it is true, the SO
+ * PIN has been locked. SO login to the token is not possible.
+ */
+#define CKF_SO_PIN_LOCKED            0x00400000
+
+/* CKF_SO_PIN_TO_BE_CHANGED if new for v2.10. If it is true,
+ * the SO PIN value is the default value set by token
+ * initialization or manufacturing, or the PIN has been
+ * expired by the card. */
+#define CKF_SO_PIN_TO_BE_CHANGED     0x00800000
+
+typedef CK_TOKEN_INFO CK_PTR CK_TOKEN_INFO_PTR;
+
+
+/* CK_SESSION_HANDLE is a Cryptoki-assigned value that
+ * identifies a session */
+typedef CK_ULONG          CK_SESSION_HANDLE;
+
+typedef CK_SESSION_HANDLE CK_PTR CK_SESSION_HANDLE_PTR;
+
+
+/* CK_USER_TYPE enumerates the types of Cryptoki users */
+/* CK_USER_TYPE has been changed from an enum to a CK_ULONG for
+ * v2.0 */
+typedef CK_ULONG          CK_USER_TYPE;
+/* Security Officer */
+#define CKU_SO    0
+/* Normal user */
+#define CKU_USER  1
+/* Context specific (added in v2.20) */
+#define CKU_CONTEXT_SPECIFIC   2
+
+/* CK_STATE enumerates the session states */
+/* CK_STATE has been changed from an enum to a CK_ULONG for
+ * v2.0 */
+typedef CK_ULONG          CK_STATE;
+#define CKS_RO_PUBLIC_SESSION  0
+#define CKS_RO_USER_FUNCTIONS  1
+#define CKS_RW_PUBLIC_SESSION  2
+#define CKS_RW_USER_FUNCTIONS  3
+#define CKS_RW_SO_FUNCTIONS    4
+
+
+/* CK_SESSION_INFO provides information about a session */
+typedef struct CK_SESSION_INFO {
+  CK_SLOT_ID    slotID;
+  CK_STATE      state;
+  CK_FLAGS      flags;          /* see below */
+
+  /* ulDeviceError was changed from CK_USHORT to CK_ULONG for
+   * v2.0 */
+  CK_ULONG      ulDeviceError;  /* device-dependent error code */
+} CK_SESSION_INFO;
+
+/* The flags are defined in the following table:
+ *      Bit Flag                Mask        Meaning
+ */
+#define CKF_RW_SESSION          0x00000002  /* session is r/w */
+#define CKF_SERIAL_SESSION      0x00000004  /* no parallel */
+
+typedef CK_SESSION_INFO CK_PTR CK_SESSION_INFO_PTR;
+
+
+/* CK_OBJECT_HANDLE is a token-specific identifier for an
+ * object  */
+typedef CK_ULONG          CK_OBJECT_HANDLE;
+
+typedef CK_OBJECT_HANDLE CK_PTR CK_OBJECT_HANDLE_PTR;
+
+
+/* CK_OBJECT_CLASS is a value that identifies the classes (or
+ * types) of objects that Cryptoki recognizes.  It is defined
+ * as follows: */
+/* CK_OBJECT_CLASS was changed from CK_USHORT to CK_ULONG for
+ * v2.0 */
+typedef CK_ULONG          CK_OBJECT_CLASS;
+
+/* The following classes of objects are defined: */
+/* CKO_HW_FEATURE is new for v2.10 */
+/* CKO_DOMAIN_PARAMETERS is new for v2.11 */
+/* CKO_MECHANISM is new for v2.20 */
+#define CKO_DATA              0x00000000
+#define CKO_CERTIFICATE       0x00000001
+#define CKO_PUBLIC_KEY        0x00000002
+#define CKO_PRIVATE_KEY       0x00000003
+#define CKO_SECRET_KEY        0x00000004
+#define CKO_HW_FEATURE        0x00000005
+#define CKO_DOMAIN_PARAMETERS 0x00000006
+#define CKO_MECHANISM         0x00000007
+#define CKO_VENDOR_DEFINED    0x80000000
+
+typedef CK_OBJECT_CLASS CK_PTR CK_OBJECT_CLASS_PTR;
+
+/* CK_HW_FEATURE_TYPE is new for v2.10. CK_HW_FEATURE_TYPE is a
+ * value that identifies the hardware feature type of an object
+ * with CK_OBJECT_CLASS equal to CKO_HW_FEATURE. */
+typedef CK_ULONG          CK_HW_FEATURE_TYPE;
+
+/* The following hardware feature types are defined */
+/* CKH_USER_INTERFACE is new for v2.20 */
+#define CKH_MONOTONIC_COUNTER  0x00000001
+#define CKH_CLOCK           0x00000002
+#define CKH_USER_INTERFACE  0x00000003
+#define CKH_VENDOR_DEFINED  0x80000000
+
+/* CK_KEY_TYPE is a value that identifies a key type */
+/* CK_KEY_TYPE was changed from CK_USHORT to CK_ULONG for v2.0 */
+typedef CK_ULONG          CK_KEY_TYPE;
+
+/* the following key types are defined: */
+#define CKK_RSA             0x00000000
+#define CKK_DSA             0x00000001
+#define CKK_DH              0x00000002
+
+/* CKK_ECDSA and CKK_KEA are new for v2.0 */
+/* CKK_ECDSA is deprecated in v2.11, CKK_EC is preferred. */
+#define CKK_ECDSA           0x00000003
+#define CKK_EC              0x00000003
+#define CKK_X9_42_DH        0x00000004
+#define CKK_KEA             0x00000005
+
+#define CKK_GENERIC_SECRET  0x00000010
+#define CKK_RC2             0x00000011
+#define CKK_RC4             0x00000012
+#define CKK_DES             0x00000013
+#define CKK_DES2            0x00000014
+#define CKK_DES3            0x00000015
+
+/* all these key types are new for v2.0 */
+#define CKK_CAST            0x00000016
+#define CKK_CAST3           0x00000017
+/* CKK_CAST5 is deprecated in v2.11, CKK_CAST128 is preferred. */
+#define CKK_CAST5           0x00000018
+#define CKK_CAST128         0x00000018
+#define CKK_RC5             0x00000019
+#define CKK_IDEA            0x0000001A
+#define CKK_SKIPJACK        0x0000001B
+#define CKK_BATON           0x0000001C
+#define CKK_JUNIPER         0x0000001D
+#define CKK_CDMF            0x0000001E
+#define CKK_AES             0x0000001F
+
+/* BlowFish and TwoFish are new for v2.20 */
+#define CKK_BLOWFISH        0x00000020
+#define CKK_TWOFISH         0x00000021
+
+#define CKK_VENDOR_DEFINED  0x80000000
+
+
+/* CK_CERTIFICATE_TYPE is a value that identifies a certificate
+ * type */
+/* CK_CERTIFICATE_TYPE was changed from CK_USHORT to CK_ULONG
+ * for v2.0 */
+typedef CK_ULONG          CK_CERTIFICATE_TYPE;
+
+/* The following certificate types are defined: */
+/* CKC_X_509_ATTR_CERT is new for v2.10 */
+/* CKC_WTLS is new for v2.20 */
+#define CKC_X_509           0x00000000
+#define CKC_X_509_ATTR_CERT 0x00000001
+#define CKC_WTLS            0x00000002
+#define CKC_VENDOR_DEFINED  0x80000000
+
+
+/* CK_ATTRIBUTE_TYPE is a value that identifies an attribute
+ * type */
+/* CK_ATTRIBUTE_TYPE was changed from CK_USHORT to CK_ULONG for
+ * v2.0 */
+typedef CK_ULONG          CK_ATTRIBUTE_TYPE;
+
+/* The CKF_ARRAY_ATTRIBUTE flag identifies an attribute which
+   consists of an array of values. */
+#define CKF_ARRAY_ATTRIBUTE    0x40000000
+
+/* The following attribute types are defined: */
+#define CKA_CLASS              0x00000000
+#define CKA_TOKEN              0x00000001
+#define CKA_PRIVATE            0x00000002
+#define CKA_LABEL              0x00000003
+#define CKA_APPLICATION        0x00000010
+#define CKA_VALUE              0x00000011
+
+/* CKA_OBJECT_ID is new for v2.10 */
+#define CKA_OBJECT_ID          0x00000012
+
+#define CKA_CERTIFICATE_TYPE   0x00000080
+#define CKA_ISSUER             0x00000081
+#define CKA_SERIAL_NUMBER      0x00000082
+
+/* CKA_AC_ISSUER, CKA_OWNER, and CKA_ATTR_TYPES are new
+ * for v2.10 */
+#define CKA_AC_ISSUER          0x00000083
+#define CKA_OWNER              0x00000084
+#define CKA_ATTR_TYPES         0x00000085
+
+/* CKA_TRUSTED is new for v2.11 */
+#define CKA_TRUSTED            0x00000086
+
+/* CKA_CERTIFICATE_CATEGORY ...
+ * CKA_CHECK_VALUE are new for v2.20 */
+#define CKA_CERTIFICATE_CATEGORY        0x00000087
+#define CKA_JAVA_MIDP_SECURITY_DOMAIN   0x00000088
+#define CKA_URL                         0x00000089
+#define CKA_HASH_OF_SUBJECT_PUBLIC_KEY  0x0000008A
+#define CKA_HASH_OF_ISSUER_PUBLIC_KEY   0x0000008B
+#define CKA_CHECK_VALUE                 0x00000090
+
+#define CKA_KEY_TYPE           0x00000100
+#define CKA_SUBJECT            0x00000101
+#define CKA_ID                 0x00000102
+#define CKA_SENSITIVE          0x00000103
+#define CKA_ENCRYPT            0x00000104
+#define CKA_DECRYPT            0x00000105
+#define CKA_WRAP               0x00000106
+#define CKA_UNWRAP             0x00000107
+#define CKA_SIGN               0x00000108
+#define CKA_SIGN_RECOVER       0x00000109
+#define CKA_VERIFY             0x0000010A
+#define CKA_VERIFY_RECOVER     0x0000010B
+#define CKA_DERIVE             0x0000010C
+#define CKA_START_DATE         0x00000110
+#define CKA_END_DATE           0x00000111
+#define CKA_MODULUS            0x00000120
+#define CKA_MODULUS_BITS       0x00000121
+#define CKA_PUBLIC_EXPONENT    0x00000122
+#define CKA_PRIVATE_EXPONENT   0x00000123
+#define CKA_PRIME_1            0x00000124
+#define CKA_PRIME_2            0x00000125
+#define CKA_EXPONENT_1         0x00000126
+#define CKA_EXPONENT_2         0x00000127
+#define CKA_COEFFICIENT        0x00000128
+#define CKA_PRIME              0x00000130
+#define CKA_SUBPRIME           0x00000131
+#define CKA_BASE               0x00000132
+
+/* CKA_PRIME_BITS and CKA_SUB_PRIME_BITS are new for v2.11 */
+#define CKA_PRIME_BITS         0x00000133
+#define CKA_SUBPRIME_BITS      0x00000134
+#define CKA_SUB_PRIME_BITS     CKA_SUBPRIME_BITS
+/* (To retain backwards-compatibility) */
+
+#define CKA_VALUE_BITS         0x00000160
+#define CKA_VALUE_LEN          0x00000161
+
+/* CKA_EXTRACTABLE, CKA_LOCAL, CKA_NEVER_EXTRACTABLE,
+ * CKA_ALWAYS_SENSITIVE, CKA_MODIFIABLE, CKA_ECDSA_PARAMS,
+ * and CKA_EC_POINT are new for v2.0 */
+#define CKA_EXTRACTABLE        0x00000162
+#define CKA_LOCAL              0x00000163
+#define CKA_NEVER_EXTRACTABLE  0x00000164
+#define CKA_ALWAYS_SENSITIVE   0x00000165
+
+/* CKA_KEY_GEN_MECHANISM is new for v2.11 */
+#define CKA_KEY_GEN_MECHANISM  0x00000166
+
+#define CKA_MODIFIABLE         0x00000170
+
+/* CKA_ECDSA_PARAMS is deprecated in v2.11,
+ * CKA_EC_PARAMS is preferred. */
+#define CKA_ECDSA_PARAMS       0x00000180
+#define CKA_EC_PARAMS          0x00000180
+
+#define CKA_EC_POINT           0x00000181
+
+/* CKA_SECONDARY_AUTH, CKA_AUTH_PIN_FLAGS,
+ * are new for v2.10. Deprecated in v2.11 and onwards. */
+#define CKA_SECONDARY_AUTH     0x00000200
+#define CKA_AUTH_PIN_FLAGS     0x00000201
+
+/* CKA_ALWAYS_AUTHENTICATE ...
+ * CKA_UNWRAP_TEMPLATE are new for v2.20 */
+#define CKA_ALWAYS_AUTHENTICATE  0x00000202
+
+#define CKA_WRAP_WITH_TRUSTED    0x00000210
+#define CKA_WRAP_TEMPLATE        (CKF_ARRAY_ATTRIBUTE|0x00000211)
+#define CKA_UNWRAP_TEMPLATE      (CKF_ARRAY_ATTRIBUTE|0x00000212)
+
+/* CKA_HW_FEATURE_TYPE, CKA_RESET_ON_INIT, and CKA_HAS_RESET
+ * are new for v2.10 */
+#define CKA_HW_FEATURE_TYPE    0x00000300
+#define CKA_RESET_ON_INIT      0x00000301
+#define CKA_HAS_RESET          0x00000302
+
+/* The following attributes are new for v2.20 */
+#define CKA_PIXEL_X                     0x00000400
+#define CKA_PIXEL_Y                     0x00000401
+#define CKA_RESOLUTION                  0x00000402
+#define CKA_CHAR_ROWS                   0x00000403
+#define CKA_CHAR_COLUMNS                0x00000404
+#define CKA_COLOR                       0x00000405
+#define CKA_BITS_PER_PIXEL              0x00000406
+#define CKA_CHAR_SETS                   0x00000480
+#define CKA_ENCODING_METHODS            0x00000481
+#define CKA_MIME_TYPES                  0x00000482
+#define CKA_MECHANISM_TYPE              0x00000500
+#define CKA_REQUIRED_CMS_ATTRIBUTES     0x00000501
+#define CKA_DEFAULT_CMS_ATTRIBUTES      0x00000502
+#define CKA_SUPPORTED_CMS_ATTRIBUTES    0x00000503
+#define CKA_ALLOWED_MECHANISMS          (CKF_ARRAY_ATTRIBUTE|0x00000600)
+
+#define CKA_VENDOR_DEFINED     0x80000000
+
+
+/* CK_ATTRIBUTE is a structure that includes the type, length
+ * and value of an attribute */
+typedef struct CK_ATTRIBUTE {
+  CK_ATTRIBUTE_TYPE type;
+  CK_VOID_PTR       pValue;
+
+  /* ulValueLen went from CK_USHORT to CK_ULONG for v2.0 */
+  CK_ULONG          ulValueLen;  /* in bytes */
+} CK_ATTRIBUTE;
+
+typedef CK_ATTRIBUTE CK_PTR CK_ATTRIBUTE_PTR;
+
+
+/* CK_DATE is a structure that defines a date */
+typedef struct CK_DATE{
+  CK_CHAR       year[4];   /* the year ("1900" - "9999") */
+  CK_CHAR       month[2];  /* the month ("01" - "12") */
+  CK_CHAR       day[2];    /* the day   ("01" - "31") */
+} CK_DATE;
+
+
+/* CK_MECHANISM_TYPE is a value that identifies a mechanism
+ * type */
+/* CK_MECHANISM_TYPE was changed from CK_USHORT to CK_ULONG for
+ * v2.0 */
+typedef CK_ULONG          CK_MECHANISM_TYPE;
+
+/* the following mechanism types are defined: */
+#define CKM_RSA_PKCS_KEY_PAIR_GEN      0x00000000
+#define CKM_RSA_PKCS                   0x00000001
+#define CKM_RSA_9796                   0x00000002
+#define CKM_RSA_X_509                  0x00000003
+
+/* CKM_MD2_RSA_PKCS, CKM_MD5_RSA_PKCS, and CKM_SHA1_RSA_PKCS
+ * are new for v2.0.  They are mechanisms which hash and sign */
+#define CKM_MD2_RSA_PKCS               0x00000004
+#define CKM_MD5_RSA_PKCS               0x00000005
+#define CKM_SHA1_RSA_PKCS              0x00000006
+
+/* CKM_RIPEMD128_RSA_PKCS, CKM_RIPEMD160_RSA_PKCS, and
+ * CKM_RSA_PKCS_OAEP are new for v2.10 */
+#define CKM_RIPEMD128_RSA_PKCS         0x00000007
+#define CKM_RIPEMD160_RSA_PKCS         0x00000008
+#define CKM_RSA_PKCS_OAEP              0x00000009
+
+/* CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_RSA_X9_31, CKM_SHA1_RSA_X9_31,
+ * CKM_RSA_PKCS_PSS, and CKM_SHA1_RSA_PKCS_PSS are new for v2.11 */
+#define CKM_RSA_X9_31_KEY_PAIR_GEN     0x0000000A
+#define CKM_RSA_X9_31                  0x0000000B
+#define CKM_SHA1_RSA_X9_31             0x0000000C
+#define CKM_RSA_PKCS_PSS               0x0000000D
+#define CKM_SHA1_RSA_PKCS_PSS          0x0000000E
+
+#define CKM_DSA_KEY_PAIR_GEN           0x00000010
+#define CKM_DSA                        0x00000011
+#define CKM_DSA_SHA1                   0x00000012
+#define CKM_DH_PKCS_KEY_PAIR_GEN       0x00000020
+#define CKM_DH_PKCS_DERIVE             0x00000021
+
+/* CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_DERIVE,
+ * CKM_X9_42_DH_HYBRID_DERIVE, and CKM_X9_42_MQV_DERIVE are new for
+ * v2.11 */
+#define CKM_X9_42_DH_KEY_PAIR_GEN      0x00000030
+#define CKM_X9_42_DH_DERIVE            0x00000031
+#define CKM_X9_42_DH_HYBRID_DERIVE     0x00000032
+#define CKM_X9_42_MQV_DERIVE           0x00000033
+
+/* CKM_SHA256/384/512 are new for v2.20 */
+#define CKM_SHA256_RSA_PKCS            0x00000040
+#define CKM_SHA384_RSA_PKCS            0x00000041
+#define CKM_SHA512_RSA_PKCS            0x00000042
+#define CKM_SHA256_RSA_PKCS_PSS        0x00000043
+#define CKM_SHA384_RSA_PKCS_PSS        0x00000044
+#define CKM_SHA512_RSA_PKCS_PSS        0x00000045
+
+#define CKM_RC2_KEY_GEN                0x00000100
+#define CKM_RC2_ECB                    0x00000101
+#define CKM_RC2_CBC                    0x00000102
+#define CKM_RC2_MAC                    0x00000103
+
+/* CKM_RC2_MAC_GENERAL and CKM_RC2_CBC_PAD are new for v2.0 */
+#define CKM_RC2_MAC_GENERAL            0x00000104
+#define CKM_RC2_CBC_PAD                0x00000105
+
+#define CKM_RC4_KEY_GEN                0x00000110
+#define CKM_RC4                        0x00000111
+#define CKM_DES_KEY_GEN                0x00000120
+#define CKM_DES_ECB                    0x00000121
+#define CKM_DES_CBC                    0x00000122
+#define CKM_DES_MAC                    0x00000123
+
+/* CKM_DES_MAC_GENERAL and CKM_DES_CBC_PAD are new for v2.0 */
+#define CKM_DES_MAC_GENERAL            0x00000124
+#define CKM_DES_CBC_PAD                0x00000125
+
+#define CKM_DES2_KEY_GEN               0x00000130
+#define CKM_DES3_KEY_GEN               0x00000131
+#define CKM_DES3_ECB                   0x00000132
+#define CKM_DES3_CBC                   0x00000133
+#define CKM_DES3_MAC                   0x00000134
+
+/* CKM_DES3_MAC_GENERAL, CKM_DES3_CBC_PAD, CKM_CDMF_KEY_GEN,
+ * CKM_CDMF_ECB, CKM_CDMF_CBC, CKM_CDMF_MAC,
+ * CKM_CDMF_MAC_GENERAL, and CKM_CDMF_CBC_PAD are new for v2.0 */
+#define CKM_DES3_MAC_GENERAL           0x00000135
+#define CKM_DES3_CBC_PAD               0x00000136
+#define CKM_CDMF_KEY_GEN               0x00000140
+#define CKM_CDMF_ECB                   0x00000141
+#define CKM_CDMF_CBC                   0x00000142
+#define CKM_CDMF_MAC                   0x00000143
+#define CKM_CDMF_MAC_GENERAL           0x00000144
+#define CKM_CDMF_CBC_PAD               0x00000145
+
+/* the following four DES mechanisms are new for v2.20 */
+#define CKM_DES_OFB64                  0x00000150
+#define CKM_DES_OFB8                   0x00000151
+#define CKM_DES_CFB64                  0x00000152
+#define CKM_DES_CFB8                   0x00000153
+
+#define CKM_MD2                        0x00000200
+
+/* CKM_MD2_HMAC and CKM_MD2_HMAC_GENERAL are new for v2.0 */
+#define CKM_MD2_HMAC                   0x00000201
+#define CKM_MD2_HMAC_GENERAL           0x00000202
+
+#define CKM_MD5                        0x00000210
+
+/* CKM_MD5_HMAC and CKM_MD5_HMAC_GENERAL are new for v2.0 */
+#define CKM_MD5_HMAC                   0x00000211
+#define CKM_MD5_HMAC_GENERAL           0x00000212
+
+#define CKM_SHA_1                      0x00000220
+
+/* CKM_SHA_1_HMAC and CKM_SHA_1_HMAC_GENERAL are new for v2.0 */
+#define CKM_SHA_1_HMAC                 0x00000221
+#define CKM_SHA_1_HMAC_GENERAL         0x00000222
+
+/* CKM_RIPEMD128, CKM_RIPEMD128_HMAC,
+ * CKM_RIPEMD128_HMAC_GENERAL, CKM_RIPEMD160, CKM_RIPEMD160_HMAC,
+ * and CKM_RIPEMD160_HMAC_GENERAL are new for v2.10 */
+#define CKM_RIPEMD128                  0x00000230
+#define CKM_RIPEMD128_HMAC             0x00000231
+#define CKM_RIPEMD128_HMAC_GENERAL     0x00000232
+#define CKM_RIPEMD160                  0x00000240
+#define CKM_RIPEMD160_HMAC             0x00000241
+#define CKM_RIPEMD160_HMAC_GENERAL     0x00000242
+
+/* CKM_SHA256/384/512 are new for v2.20 */
+#define CKM_SHA256                     0x00000250
+#define CKM_SHA256_HMAC                0x00000251
+#define CKM_SHA256_HMAC_GENERAL        0x00000252
+#define CKM_SHA384                     0x00000260
+#define CKM_SHA384_HMAC                0x00000261
+#define CKM_SHA384_HMAC_GENERAL        0x00000262
+#define CKM_SHA512                     0x00000270
+#define CKM_SHA512_HMAC                0x00000271
+#define CKM_SHA512_HMAC_GENERAL        0x00000272
+
+/* All of the following mechanisms are new for v2.0 */
+/* Note that CAST128 and CAST5 are the same algorithm */
+#define CKM_CAST_KEY_GEN               0x00000300
+#define CKM_CAST_ECB                   0x00000301
+#define CKM_CAST_CBC                   0x00000302
+#define CKM_CAST_MAC                   0x00000303
+#define CKM_CAST_MAC_GENERAL           0x00000304
+#define CKM_CAST_CBC_PAD               0x00000305
+#define CKM_CAST3_KEY_GEN              0x00000310
+#define CKM_CAST3_ECB                  0x00000311
+#define CKM_CAST3_CBC                  0x00000312
+#define CKM_CAST3_MAC                  0x00000313
+#define CKM_CAST3_MAC_GENERAL          0x00000314
+#define CKM_CAST3_CBC_PAD              0x00000315
+#define CKM_CAST5_KEY_GEN              0x00000320
+#define CKM_CAST128_KEY_GEN            0x00000320
+#define CKM_CAST5_ECB                  0x00000321
+#define CKM_CAST128_ECB                0x00000321
+#define CKM_CAST5_CBC                  0x00000322
+#define CKM_CAST128_CBC                0x00000322
+#define CKM_CAST5_MAC                  0x00000323
+#define CKM_CAST128_MAC                0x00000323
+#define CKM_CAST5_MAC_GENERAL          0x00000324
+#define CKM_CAST128_MAC_GENERAL        0x00000324
+#define CKM_CAST5_CBC_PAD              0x00000325
+#define CKM_CAST128_CBC_PAD            0x00000325
+#define CKM_RC5_KEY_GEN                0x00000330
+#define CKM_RC5_ECB                    0x00000331
+#define CKM_RC5_CBC                    0x00000332
+#define CKM_RC5_MAC                    0x00000333
+#define CKM_RC5_MAC_GENERAL            0x00000334
+#define CKM_RC5_CBC_PAD                0x00000335
+#define CKM_IDEA_KEY_GEN               0x00000340
+#define CKM_IDEA_ECB                   0x00000341
+#define CKM_IDEA_CBC                   0x00000342
+#define CKM_IDEA_MAC                   0x00000343
+#define CKM_IDEA_MAC_GENERAL           0x00000344
+#define CKM_IDEA_CBC_PAD               0x00000345
+#define CKM_GENERIC_SECRET_KEY_GEN     0x00000350
+#define CKM_CONCATENATE_BASE_AND_KEY   0x00000360
+#define CKM_CONCATENATE_BASE_AND_DATA  0x00000362
+#define CKM_CONCATENATE_DATA_AND_BASE  0x00000363
+#define CKM_XOR_BASE_AND_DATA          0x00000364
+#define CKM_EXTRACT_KEY_FROM_KEY       0x00000365
+#define CKM_SSL3_PRE_MASTER_KEY_GEN    0x00000370
+#define CKM_SSL3_MASTER_KEY_DERIVE     0x00000371
+#define CKM_SSL3_KEY_AND_MAC_DERIVE    0x00000372
+
+/* CKM_SSL3_MASTER_KEY_DERIVE_DH, CKM_TLS_PRE_MASTER_KEY_GEN,
+ * CKM_TLS_MASTER_KEY_DERIVE, CKM_TLS_KEY_AND_MAC_DERIVE, and
+ * CKM_TLS_MASTER_KEY_DERIVE_DH are new for v2.11 */
+#define CKM_SSL3_MASTER_KEY_DERIVE_DH  0x00000373
+#define CKM_TLS_PRE_MASTER_KEY_GEN     0x00000374
+#define CKM_TLS_MASTER_KEY_DERIVE      0x00000375
+#define CKM_TLS_KEY_AND_MAC_DERIVE     0x00000376
+#define CKM_TLS_MASTER_KEY_DERIVE_DH   0x00000377
+
+/* CKM_TLS_PRF is new for v2.20 */
+#define CKM_TLS_PRF                    0x00000378
+
+#define CKM_SSL3_MD5_MAC               0x00000380
+#define CKM_SSL3_SHA1_MAC              0x00000381
+#define CKM_MD5_KEY_DERIVATION         0x00000390
+#define CKM_MD2_KEY_DERIVATION         0x00000391
+#define CKM_SHA1_KEY_DERIVATION        0x00000392
+
+/* CKM_SHA256/384/512 are new for v2.20 */
+#define CKM_SHA256_KEY_DERIVATION      0x00000393
+#define CKM_SHA384_KEY_DERIVATION      0x00000394
+#define CKM_SHA512_KEY_DERIVATION      0x00000395
+
+#define CKM_PBE_MD2_DES_CBC            0x000003A0
+#define CKM_PBE_MD5_DES_CBC            0x000003A1
+#define CKM_PBE_MD5_CAST_CBC           0x000003A2
+#define CKM_PBE_MD5_CAST3_CBC          0x000003A3
+#define CKM_PBE_MD5_CAST5_CBC          0x000003A4
+#define CKM_PBE_MD5_CAST128_CBC        0x000003A4
+#define CKM_PBE_SHA1_CAST5_CBC         0x000003A5
+#define CKM_PBE_SHA1_CAST128_CBC       0x000003A5
+#define CKM_PBE_SHA1_RC4_128           0x000003A6
+#define CKM_PBE_SHA1_RC4_40            0x000003A7
+#define CKM_PBE_SHA1_DES3_EDE_CBC      0x000003A8
+#define CKM_PBE_SHA1_DES2_EDE_CBC      0x000003A9
+#define CKM_PBE_SHA1_RC2_128_CBC       0x000003AA
+#define CKM_PBE_SHA1_RC2_40_CBC        0x000003AB
+
+/* CKM_PKCS5_PBKD2 is new for v2.10 */
+#define CKM_PKCS5_PBKD2                0x000003B0
+
+#define CKM_PBA_SHA1_WITH_SHA1_HMAC    0x000003C0
+
+/* WTLS mechanisms are new for v2.20 */
+#define CKM_WTLS_PRE_MASTER_KEY_GEN         0x000003D0
+#define CKM_WTLS_MASTER_KEY_DERIVE          0x000003D1
+#define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC   0x000003D2
+#define CKM_WTLS_PRF                        0x000003D3
+#define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE  0x000003D4
+#define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE  0x000003D5
+
+#define CKM_KEY_WRAP_LYNKS             0x00000400
+#define CKM_KEY_WRAP_SET_OAEP          0x00000401
+
+/* CKM_CMS_SIG is new for v2.20 */
+#define CKM_CMS_SIG                    0x00000500
+
+/* Fortezza mechanisms */
+#define CKM_SKIPJACK_KEY_GEN           0x00001000
+#define CKM_SKIPJACK_ECB64             0x00001001
+#define CKM_SKIPJACK_CBC64             0x00001002
+#define CKM_SKIPJACK_OFB64             0x00001003
+#define CKM_SKIPJACK_CFB64             0x00001004
+#define CKM_SKIPJACK_CFB32             0x00001005
+#define CKM_SKIPJACK_CFB16             0x00001006
+#define CKM_SKIPJACK_CFB8              0x00001007
+#define CKM_SKIPJACK_WRAP              0x00001008
+#define CKM_SKIPJACK_PRIVATE_WRAP      0x00001009
+#define CKM_SKIPJACK_RELAYX            0x0000100a
+#define CKM_KEA_KEY_PAIR_GEN           0x00001010
+#define CKM_KEA_KEY_DERIVE             0x00001011
+#define CKM_FORTEZZA_TIMESTAMP         0x00001020
+#define CKM_BATON_KEY_GEN              0x00001030
+#define CKM_BATON_ECB128               0x00001031
+#define CKM_BATON_ECB96                0x00001032
+#define CKM_BATON_CBC128               0x00001033
+#define CKM_BATON_COUNTER              0x00001034
+#define CKM_BATON_SHUFFLE              0x00001035
+#define CKM_BATON_WRAP                 0x00001036
+
+/* CKM_ECDSA_KEY_PAIR_GEN is deprecated in v2.11,
+ * CKM_EC_KEY_PAIR_GEN is preferred */
+#define CKM_ECDSA_KEY_PAIR_GEN         0x00001040
+#define CKM_EC_KEY_PAIR_GEN            0x00001040
+
+#define CKM_ECDSA                      0x00001041
+#define CKM_ECDSA_SHA1                 0x00001042
+
+/* CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE, and CKM_ECMQV_DERIVE
+ * are new for v2.11 */
+#define CKM_ECDH1_DERIVE               0x00001050
+#define CKM_ECDH1_COFACTOR_DERIVE      0x00001051
+#define CKM_ECMQV_DERIVE               0x00001052
+
+#define CKM_JUNIPER_KEY_GEN            0x00001060
+#define CKM_JUNIPER_ECB128             0x00001061
+#define CKM_JUNIPER_CBC128             0x00001062
+#define CKM_JUNIPER_COUNTER            0x00001063
+#define CKM_JUNIPER_SHUFFLE            0x00001064
+#define CKM_JUNIPER_WRAP               0x00001065
+#define CKM_FASTHASH                   0x00001070
+
+/* CKM_AES_KEY_GEN, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_MAC,
+ * CKM_AES_MAC_GENERAL, CKM_AES_CBC_PAD, CKM_DSA_PARAMETER_GEN,
+ * CKM_DH_PKCS_PARAMETER_GEN, and CKM_X9_42_DH_PARAMETER_GEN are
+ * new for v2.11 */
+#define CKM_AES_KEY_GEN                0x00001080
+#define CKM_AES_ECB                    0x00001081
+#define CKM_AES_CBC                    0x00001082
+#define CKM_AES_MAC                    0x00001083
+#define CKM_AES_MAC_GENERAL            0x00001084
+#define CKM_AES_CBC_PAD                0x00001085
+
+/* BlowFish and TwoFish are new for v2.20 */
+#define CKM_BLOWFISH_KEY_GEN           0x00001090
+#define CKM_BLOWFISH_CBC               0x00001091
+#define CKM_TWOFISH_KEY_GEN            0x00001092
+#define CKM_TWOFISH_CBC                0x00001093
+
+
+/* CKM_xxx_ENCRYPT_DATA mechanisms are new for v2.20 */
+#define CKM_DES_ECB_ENCRYPT_DATA       0x00001100
+#define CKM_DES_CBC_ENCRYPT_DATA       0x00001101
+#define CKM_DES3_ECB_ENCRYPT_DATA      0x00001102
+#define CKM_DES3_CBC_ENCRYPT_DATA      0x00001103
+#define CKM_AES_ECB_ENCRYPT_DATA       0x00001104
+#define CKM_AES_CBC_ENCRYPT_DATA       0x00001105
+
+#define CKM_DSA_PARAMETER_GEN          0x00002000
+#define CKM_DH_PKCS_PARAMETER_GEN      0x00002001
+#define CKM_X9_42_DH_PARAMETER_GEN     0x00002002
+
+#define CKM_VENDOR_DEFINED             0x80000000
+
+typedef CK_MECHANISM_TYPE CK_PTR CK_MECHANISM_TYPE_PTR;
+
+
+/* CK_MECHANISM is a structure that specifies a particular
+ * mechanism  */
+typedef struct CK_MECHANISM {
+  CK_MECHANISM_TYPE mechanism;
+  CK_VOID_PTR       pParameter;
+
+  /* ulParameterLen was changed from CK_USHORT to CK_ULONG for
+   * v2.0 */
+  CK_ULONG          ulParameterLen;  /* in bytes */
+} CK_MECHANISM;
+
+typedef CK_MECHANISM CK_PTR CK_MECHANISM_PTR;
+
+
+/* CK_MECHANISM_INFO provides information about a particular
+ * mechanism */
+typedef struct CK_MECHANISM_INFO {
+    CK_ULONG    ulMinKeySize;
+    CK_ULONG    ulMaxKeySize;
+    CK_FLAGS    flags;
+} CK_MECHANISM_INFO;
+
+/* The flags are defined as follows:
+ *      Bit Flag               Mask        Meaning */
+#define CKF_HW                 0x00000001  /* performed by HW */
+
+/* The flags CKF_ENCRYPT, CKF_DECRYPT, CKF_DIGEST, CKF_SIGN,
+ * CKG_SIGN_RECOVER, CKF_VERIFY, CKF_VERIFY_RECOVER,
+ * CKF_GENERATE, CKF_GENERATE_KEY_PAIR, CKF_WRAP, CKF_UNWRAP,
+ * and CKF_DERIVE are new for v2.0.  They specify whether or not
+ * a mechanism can be used for a particular task */
+#define CKF_ENCRYPT            0x00000100
+#define CKF_DECRYPT            0x00000200
+#define CKF_DIGEST             0x00000400
+#define CKF_SIGN               0x00000800
+#define CKF_SIGN_RECOVER       0x00001000
+#define CKF_VERIFY             0x00002000
+#define CKF_VERIFY_RECOVER     0x00004000
+#define CKF_GENERATE           0x00008000
+#define CKF_GENERATE_KEY_PAIR  0x00010000
+#define CKF_WRAP               0x00020000
+#define CKF_UNWRAP             0x00040000
+#define CKF_DERIVE             0x00080000
+
+/* CKF_EC_F_P, CKF_EC_F_2M, CKF_EC_ECPARAMETERS, CKF_EC_NAMEDCURVE,
+ * CKF_EC_UNCOMPRESS, and CKF_EC_COMPRESS are new for v2.11. They
+ * describe a token's EC capabilities not available in mechanism
+ * information. */
+#define CKF_EC_F_P             0x00100000
+#define CKF_EC_F_2M            0x00200000
+#define CKF_EC_ECPARAMETERS    0x00400000
+#define CKF_EC_NAMEDCURVE      0x00800000
+#define CKF_EC_UNCOMPRESS      0x01000000
+#define CKF_EC_COMPRESS        0x02000000
+
+#define CKF_EXTENSION          0x80000000 /* FALSE for this version */
+
+typedef CK_MECHANISM_INFO CK_PTR CK_MECHANISM_INFO_PTR;
+
+
+/* CK_RV is a value that identifies the return value of a
+ * Cryptoki function */
+/* CK_RV was changed from CK_USHORT to CK_ULONG for v2.0 */
+typedef CK_ULONG          CK_RV;
+
+#define CKR_OK                                0x00000000
+#define CKR_CANCEL                            0x00000001
+#define CKR_HOST_MEMORY                       0x00000002
+#define CKR_SLOT_ID_INVALID                   0x00000003
+
+/* CKR_FLAGS_INVALID was removed for v2.0 */
+
+/* CKR_GENERAL_ERROR and CKR_FUNCTION_FAILED are new for v2.0 */
+#define CKR_GENERAL_ERROR                     0x00000005
+#define CKR_FUNCTION_FAILED                   0x00000006
+
+/* CKR_ARGUMENTS_BAD, CKR_NO_EVENT, CKR_NEED_TO_CREATE_THREADS,
+ * and CKR_CANT_LOCK are new for v2.01 */
+#define CKR_ARGUMENTS_BAD                     0x00000007
+#define CKR_NO_EVENT                          0x00000008
+#define CKR_NEED_TO_CREATE_THREADS            0x00000009
+#define CKR_CANT_LOCK                         0x0000000A
+
+#define CKR_ATTRIBUTE_READ_ONLY               0x00000010
+#define CKR_ATTRIBUTE_SENSITIVE               0x00000011
+#define CKR_ATTRIBUTE_TYPE_INVALID            0x00000012
+#define CKR_ATTRIBUTE_VALUE_INVALID           0x00000013
+#define CKR_DATA_INVALID                      0x00000020
+#define CKR_DATA_LEN_RANGE                    0x00000021
+#define CKR_DEVICE_ERROR                      0x00000030
+#define CKR_DEVICE_MEMORY                     0x00000031
+#define CKR_DEVICE_REMOVED                    0x00000032
+#define CKR_ENCRYPTED_DATA_INVALID            0x00000040
+#define CKR_ENCRYPTED_DATA_LEN_RANGE          0x00000041
+#define CKR_FUNCTION_CANCELED                 0x00000050
+#define CKR_FUNCTION_NOT_PARALLEL             0x00000051
+
+/* CKR_FUNCTION_NOT_SUPPORTED is new for v2.0 */
+#define CKR_FUNCTION_NOT_SUPPORTED            0x00000054
+
+#define CKR_KEY_HANDLE_INVALID                0x00000060
+
+/* CKR_KEY_SENSITIVE was removed for v2.0 */
+
+#define CKR_KEY_SIZE_RANGE                    0x00000062
+#define CKR_KEY_TYPE_INCONSISTENT             0x00000063
+
+/* CKR_KEY_NOT_NEEDED, CKR_KEY_CHANGED, CKR_KEY_NEEDED,
+ * CKR_KEY_INDIGESTIBLE, CKR_KEY_FUNCTION_NOT_PERMITTED,
+ * CKR_KEY_NOT_WRAPPABLE, and CKR_KEY_UNEXTRACTABLE are new for
+ * v2.0 */
+#define CKR_KEY_NOT_NEEDED                    0x00000064
+#define CKR_KEY_CHANGED                       0x00000065
+#define CKR_KEY_NEEDED                        0x00000066
+#define CKR_KEY_INDIGESTIBLE                  0x00000067
+#define CKR_KEY_FUNCTION_NOT_PERMITTED        0x00000068
+#define CKR_KEY_NOT_WRAPPABLE                 0x00000069
+#define CKR_KEY_UNEXTRACTABLE                 0x0000006A
+
+#define CKR_MECHANISM_INVALID                 0x00000070
+#define CKR_MECHANISM_PARAM_INVALID           0x00000071
+
+/* CKR_OBJECT_CLASS_INCONSISTENT and CKR_OBJECT_CLASS_INVALID
+ * were removed for v2.0 */
+#define CKR_OBJECT_HANDLE_INVALID             0x00000082
+#define CKR_OPERATION_ACTIVE                  0x00000090
+#define CKR_OPERATION_NOT_INITIALIZED         0x00000091
+#define CKR_PIN_INCORRECT                     0x000000A0
+#define CKR_PIN_INVALID                       0x000000A1
+#define CKR_PIN_LEN_RANGE                     0x000000A2
+
+/* CKR_PIN_EXPIRED and CKR_PIN_LOCKED are new for v2.0 */
+#define CKR_PIN_EXPIRED                       0x000000A3
+#define CKR_PIN_LOCKED                        0x000000A4
+
+#define CKR_SESSION_CLOSED                    0x000000B0
+#define CKR_SESSION_COUNT                     0x000000B1
+#define CKR_SESSION_HANDLE_INVALID            0x000000B3
+#define CKR_SESSION_PARALLEL_NOT_SUPPORTED    0x000000B4
+#define CKR_SESSION_READ_ONLY                 0x000000B5
+#define CKR_SESSION_EXISTS                    0x000000B6
+
+/* CKR_SESSION_READ_ONLY_EXISTS and
+ * CKR_SESSION_READ_WRITE_SO_EXISTS are new for v2.0 */
+#define CKR_SESSION_READ_ONLY_EXISTS          0x000000B7
+#define CKR_SESSION_READ_WRITE_SO_EXISTS      0x000000B8
+
+#define CKR_SIGNATURE_INVALID                 0x000000C0
+#define CKR_SIGNATURE_LEN_RANGE               0x000000C1
+#define CKR_TEMPLATE_INCOMPLETE               0x000000D0
+#define CKR_TEMPLATE_INCONSISTENT             0x000000D1
+#define CKR_TOKEN_NOT_PRESENT                 0x000000E0
+#define CKR_TOKEN_NOT_RECOGNIZED              0x000000E1
+#define CKR_TOKEN_WRITE_PROTECTED             0x000000E2
+#define CKR_UNWRAPPING_KEY_HANDLE_INVALID     0x000000F0
+#define CKR_UNWRAPPING_KEY_SIZE_RANGE         0x000000F1
+#define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT  0x000000F2
+#define CKR_USER_ALREADY_LOGGED_IN            0x00000100
+#define CKR_USER_NOT_LOGGED_IN                0x00000101
+#define CKR_USER_PIN_NOT_INITIALIZED          0x00000102
+#define CKR_USER_TYPE_INVALID                 0x00000103
+
+/* CKR_USER_ANOTHER_ALREADY_LOGGED_IN and CKR_USER_TOO_MANY_TYPES
+ * are new to v2.01 */
+#define CKR_USER_ANOTHER_ALREADY_LOGGED_IN    0x00000104
+#define CKR_USER_TOO_MANY_TYPES               0x00000105
+
+#define CKR_WRAPPED_KEY_INVALID               0x00000110
+#define CKR_WRAPPED_KEY_LEN_RANGE             0x00000112
+#define CKR_WRAPPING_KEY_HANDLE_INVALID       0x00000113
+#define CKR_WRAPPING_KEY_SIZE_RANGE           0x00000114
+#define CKR_WRAPPING_KEY_TYPE_INCONSISTENT    0x00000115
+#define CKR_RANDOM_SEED_NOT_SUPPORTED         0x00000120
+
+/* These are new to v2.0 */
+#define CKR_RANDOM_NO_RNG                     0x00000121
+
+/* These are new to v2.11 */
+#define CKR_DOMAIN_PARAMS_INVALID             0x00000130
+
+/* These are new to v2.0 */
+#define CKR_BUFFER_TOO_SMALL                  0x00000150
+#define CKR_SAVED_STATE_INVALID               0x00000160
+#define CKR_INFORMATION_SENSITIVE             0x00000170
+#define CKR_STATE_UNSAVEABLE                  0x00000180
+
+/* These are new to v2.01 */
+#define CKR_CRYPTOKI_NOT_INITIALIZED          0x00000190
+#define CKR_CRYPTOKI_ALREADY_INITIALIZED      0x00000191
+#define CKR_MUTEX_BAD                         0x000001A0
+#define CKR_MUTEX_NOT_LOCKED                  0x000001A1
+
+/* This is new to v2.20 */
+#define CKR_FUNCTION_REJECTED                 0x00000200
+
+#define CKR_VENDOR_DEFINED                    0x80000000
+
+
+/* CK_NOTIFY is an application callback that processes events */
+typedef CK_CALLBACK_FUNCTION(CK_RV, CK_NOTIFY)(
+  CK_SESSION_HANDLE hSession,     /* the session's handle */
+  CK_NOTIFICATION   event,
+  CK_VOID_PTR       pApplication  /* passed to C_OpenSession */
+);
+
+
+/* CK_FUNCTION_LIST is a structure holding a Cryptoki spec
+ * version and pointers of appropriate types to all the
+ * Cryptoki functions */
+/* CK_FUNCTION_LIST is new for v2.0 */
+typedef struct CK_FUNCTION_LIST CK_FUNCTION_LIST;
+
+typedef CK_FUNCTION_LIST CK_PTR CK_FUNCTION_LIST_PTR;
+
+typedef CK_FUNCTION_LIST_PTR CK_PTR CK_FUNCTION_LIST_PTR_PTR;
+
+
+/* CK_CREATEMUTEX is an application callback for creating a
+ * mutex object */
+typedef CK_CALLBACK_FUNCTION(CK_RV, CK_CREATEMUTEX)(
+  CK_VOID_PTR_PTR ppMutex  /* location to receive ptr to mutex */
+);
+
+
+/* CK_DESTROYMUTEX is an application callback for destroying a
+ * mutex object */
+typedef CK_CALLBACK_FUNCTION(CK_RV, CK_DESTROYMUTEX)(
+  CK_VOID_PTR pMutex  /* pointer to mutex */
+);
+
+
+/* CK_LOCKMUTEX is an application callback for locking a mutex */
+typedef CK_CALLBACK_FUNCTION(CK_RV, CK_LOCKMUTEX)(
+  CK_VOID_PTR pMutex  /* pointer to mutex */
+);
+
+
+/* CK_UNLOCKMUTEX is an application callback for unlocking a
+ * mutex */
+typedef CK_CALLBACK_FUNCTION(CK_RV, CK_UNLOCKMUTEX)(
+  CK_VOID_PTR pMutex  /* pointer to mutex */
+);
+
+
+/* CK_C_INITIALIZE_ARGS provides the optional arguments to
+ * C_Initialize */
+typedef struct CK_C_INITIALIZE_ARGS {
+  CK_CREATEMUTEX CreateMutex;
+  CK_DESTROYMUTEX DestroyMutex;
+  CK_LOCKMUTEX LockMutex;
+  CK_UNLOCKMUTEX UnlockMutex;
+  CK_FLAGS flags;
+  CK_VOID_PTR pReserved;
+} CK_C_INITIALIZE_ARGS;
+
+/* flags: bit flags that provide capabilities of the slot
+ *      Bit Flag                           Mask       Meaning
+ */
+#define CKF_LIBRARY_CANT_CREATE_OS_THREADS 0x00000001
+#define CKF_OS_LOCKING_OK                  0x00000002
+
+typedef CK_C_INITIALIZE_ARGS CK_PTR CK_C_INITIALIZE_ARGS_PTR;
+
+
+/* additional flags for parameters to functions */
+
+/* CKF_DONT_BLOCK is for the function C_WaitForSlotEvent */
+#define CKF_DONT_BLOCK     1
+
+/* CK_RSA_PKCS_OAEP_MGF_TYPE is new for v2.10.
+ * CK_RSA_PKCS_OAEP_MGF_TYPE  is used to indicate the Message
+ * Generation Function (MGF) applied to a message block when
+ * formatting a message block for the PKCS #1 OAEP encryption
+ * scheme. */
+typedef CK_ULONG CK_RSA_PKCS_MGF_TYPE;
+
+typedef CK_RSA_PKCS_MGF_TYPE CK_PTR CK_RSA_PKCS_MGF_TYPE_PTR;
+
+/* The following MGFs are defined */
+/* CKG_MGF1_SHA256, CKG_MGF1_SHA384, and CKG_MGF1_SHA512
+ * are new for v2.20 */
+#define CKG_MGF1_SHA1         0x00000001
+#define CKG_MGF1_SHA256       0x00000002
+#define CKG_MGF1_SHA384       0x00000003
+#define CKG_MGF1_SHA512       0x00000004
+
+/* CK_RSA_PKCS_OAEP_SOURCE_TYPE is new for v2.10.
+ * CK_RSA_PKCS_OAEP_SOURCE_TYPE  is used to indicate the source
+ * of the encoding parameter when formatting a message block
+ * for the PKCS #1 OAEP encryption scheme. */
+typedef CK_ULONG CK_RSA_PKCS_OAEP_SOURCE_TYPE;
+
+typedef CK_RSA_PKCS_OAEP_SOURCE_TYPE CK_PTR CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR;
+
+/* The following encoding parameter sources are defined */
+#define CKZ_DATA_SPECIFIED    0x00000001
+
+/* CK_RSA_PKCS_OAEP_PARAMS is new for v2.10.
+ * CK_RSA_PKCS_OAEP_PARAMS provides the parameters to the
+ * CKM_RSA_PKCS_OAEP mechanism. */
+typedef struct CK_RSA_PKCS_OAEP_PARAMS {
+        CK_MECHANISM_TYPE hashAlg;
+        CK_RSA_PKCS_MGF_TYPE mgf;
+        CK_RSA_PKCS_OAEP_SOURCE_TYPE source;
+        CK_VOID_PTR pSourceData;
+        CK_ULONG ulSourceDataLen;
+} CK_RSA_PKCS_OAEP_PARAMS;
+
+typedef CK_RSA_PKCS_OAEP_PARAMS CK_PTR CK_RSA_PKCS_OAEP_PARAMS_PTR;
+
+/* CK_RSA_PKCS_PSS_PARAMS is new for v2.11.
+ * CK_RSA_PKCS_PSS_PARAMS provides the parameters to the
+ * CKM_RSA_PKCS_PSS mechanism(s). */
+typedef struct CK_RSA_PKCS_PSS_PARAMS {
+        CK_MECHANISM_TYPE    hashAlg;
+        CK_RSA_PKCS_MGF_TYPE mgf;
+        CK_ULONG             sLen;
+} CK_RSA_PKCS_PSS_PARAMS;
+
+typedef CK_RSA_PKCS_PSS_PARAMS CK_PTR CK_RSA_PKCS_PSS_PARAMS_PTR;
+
+/* CK_EC_KDF_TYPE is new for v2.11. */
+typedef CK_ULONG CK_EC_KDF_TYPE;
+
+/* The following EC Key Derivation Functions are defined */
+#define CKD_NULL                 0x00000001
+#define CKD_SHA1_KDF             0x00000002
+
+/* CK_ECDH1_DERIVE_PARAMS is new for v2.11.
+ * CK_ECDH1_DERIVE_PARAMS provides the parameters to the
+ * CKM_ECDH1_DERIVE and CKM_ECDH1_COFACTOR_DERIVE mechanisms,
+ * where each party contributes one key pair.
+ */
+typedef struct CK_ECDH1_DERIVE_PARAMS {
+  CK_EC_KDF_TYPE kdf;
+  CK_ULONG ulSharedDataLen;
+  CK_BYTE_PTR pSharedData;
+  CK_ULONG ulPublicDataLen;
+  CK_BYTE_PTR pPublicData;
+} CK_ECDH1_DERIVE_PARAMS;
+
+typedef CK_ECDH1_DERIVE_PARAMS CK_PTR CK_ECDH1_DERIVE_PARAMS_PTR;
+
+
+/* CK_ECDH2_DERIVE_PARAMS is new for v2.11.
+ * CK_ECDH2_DERIVE_PARAMS provides the parameters to the
+ * CKM_ECMQV_DERIVE mechanism, where each party contributes two key pairs. */
+typedef struct CK_ECDH2_DERIVE_PARAMS {
+  CK_EC_KDF_TYPE kdf;
+  CK_ULONG ulSharedDataLen;
+  CK_BYTE_PTR pSharedData;
+  CK_ULONG ulPublicDataLen;
+  CK_BYTE_PTR pPublicData;
+  CK_ULONG ulPrivateDataLen;
+  CK_OBJECT_HANDLE hPrivateData;
+  CK_ULONG ulPublicDataLen2;
+  CK_BYTE_PTR pPublicData2;
+} CK_ECDH2_DERIVE_PARAMS;
+
+typedef CK_ECDH2_DERIVE_PARAMS CK_PTR CK_ECDH2_DERIVE_PARAMS_PTR;
+
+typedef struct CK_ECMQV_DERIVE_PARAMS {
+  CK_EC_KDF_TYPE kdf;
+  CK_ULONG ulSharedDataLen;
+  CK_BYTE_PTR pSharedData;
+  CK_ULONG ulPublicDataLen;
+  CK_BYTE_PTR pPublicData;
+  CK_ULONG ulPrivateDataLen;
+  CK_OBJECT_HANDLE hPrivateData;
+  CK_ULONG ulPublicDataLen2;
+  CK_BYTE_PTR pPublicData2;
+  CK_OBJECT_HANDLE publicKey;
+} CK_ECMQV_DERIVE_PARAMS;
+
+typedef CK_ECMQV_DERIVE_PARAMS CK_PTR CK_ECMQV_DERIVE_PARAMS_PTR;
+
+/* Typedefs and defines for the CKM_X9_42_DH_KEY_PAIR_GEN and the
+ * CKM_X9_42_DH_PARAMETER_GEN mechanisms (new for PKCS #11 v2.11) */
+typedef CK_ULONG CK_X9_42_DH_KDF_TYPE;
+typedef CK_X9_42_DH_KDF_TYPE CK_PTR CK_X9_42_DH_KDF_TYPE_PTR;
+
+/* The following X9.42 DH key derivation functions are defined
+   (besides CKD_NULL already defined : */
+#define CKD_SHA1_KDF_ASN1        0x00000003
+#define CKD_SHA1_KDF_CONCATENATE 0x00000004
+
+/* CK_X9_42_DH1_DERIVE_PARAMS is new for v2.11.
+ * CK_X9_42_DH1_DERIVE_PARAMS provides the parameters to the
+ * CKM_X9_42_DH_DERIVE key derivation mechanism, where each party
+ * contributes one key pair */
+typedef struct CK_X9_42_DH1_DERIVE_PARAMS {
+  CK_X9_42_DH_KDF_TYPE kdf;
+  CK_ULONG ulOtherInfoLen;
+  CK_BYTE_PTR pOtherInfo;
+  CK_ULONG ulPublicDataLen;
+  CK_BYTE_PTR pPublicData;
+} CK_X9_42_DH1_DERIVE_PARAMS;
+
+typedef struct CK_X9_42_DH1_DERIVE_PARAMS CK_PTR CK_X9_42_DH1_DERIVE_PARAMS_PTR;
+
+/* CK_X9_42_DH2_DERIVE_PARAMS is new for v2.11.
+ * CK_X9_42_DH2_DERIVE_PARAMS provides the parameters to the
+ * CKM_X9_42_DH_HYBRID_DERIVE and CKM_X9_42_MQV_DERIVE key derivation
+ * mechanisms, where each party contributes two key pairs */
+typedef struct CK_X9_42_DH2_DERIVE_PARAMS {
+  CK_X9_42_DH_KDF_TYPE kdf;
+  CK_ULONG ulOtherInfoLen;
+  CK_BYTE_PTR pOtherInfo;
+  CK_ULONG ulPublicDataLen;
+  CK_BYTE_PTR pPublicData;
+  CK_ULONG ulPrivateDataLen;
+  CK_OBJECT_HANDLE hPrivateData;
+  CK_ULONG ulPublicDataLen2;
+  CK_BYTE_PTR pPublicData2;
+} CK_X9_42_DH2_DERIVE_PARAMS;
+
+typedef CK_X9_42_DH2_DERIVE_PARAMS CK_PTR CK_X9_42_DH2_DERIVE_PARAMS_PTR;
+
+typedef struct CK_X9_42_MQV_DERIVE_PARAMS {
+  CK_X9_42_DH_KDF_TYPE kdf;
+  CK_ULONG ulOtherInfoLen;
+  CK_BYTE_PTR pOtherInfo;
+  CK_ULONG ulPublicDataLen;
+  CK_BYTE_PTR pPublicData;
+  CK_ULONG ulPrivateDataLen;
+  CK_OBJECT_HANDLE hPrivateData;
+  CK_ULONG ulPublicDataLen2;
+  CK_BYTE_PTR pPublicData2;
+  CK_OBJECT_HANDLE publicKey;
+} CK_X9_42_MQV_DERIVE_PARAMS;
+
+typedef CK_X9_42_MQV_DERIVE_PARAMS CK_PTR CK_X9_42_MQV_DERIVE_PARAMS_PTR;
+
+/* CK_KEA_DERIVE_PARAMS provides the parameters to the
+ * CKM_KEA_DERIVE mechanism */
+/* CK_KEA_DERIVE_PARAMS is new for v2.0 */
+typedef struct CK_KEA_DERIVE_PARAMS {
+  CK_BBOOL      isSender;
+  CK_ULONG      ulRandomLen;
+  CK_BYTE_PTR   pRandomA;
+  CK_BYTE_PTR   pRandomB;
+  CK_ULONG      ulPublicDataLen;
+  CK_BYTE_PTR   pPublicData;
+} CK_KEA_DERIVE_PARAMS;
+
+typedef CK_KEA_DERIVE_PARAMS CK_PTR CK_KEA_DERIVE_PARAMS_PTR;
+
+
+/* CK_RC2_PARAMS provides the parameters to the CKM_RC2_ECB and
+ * CKM_RC2_MAC mechanisms.  An instance of CK_RC2_PARAMS just
+ * holds the effective keysize */
+typedef CK_ULONG          CK_RC2_PARAMS;
+
+typedef CK_RC2_PARAMS CK_PTR CK_RC2_PARAMS_PTR;
+
+
+/* CK_RC2_CBC_PARAMS provides the parameters to the CKM_RC2_CBC
+ * mechanism */
+typedef struct CK_RC2_CBC_PARAMS {
+  /* ulEffectiveBits was changed from CK_USHORT to CK_ULONG for
+   * v2.0 */
+  CK_ULONG      ulEffectiveBits;  /* effective bits (1-1024) */
+
+  CK_BYTE       iv[8];            /* IV for CBC mode */
+} CK_RC2_CBC_PARAMS;
+
+typedef CK_RC2_CBC_PARAMS CK_PTR CK_RC2_CBC_PARAMS_PTR;
+
+
+/* CK_RC2_MAC_GENERAL_PARAMS provides the parameters for the
+ * CKM_RC2_MAC_GENERAL mechanism */
+/* CK_RC2_MAC_GENERAL_PARAMS is new for v2.0 */
+typedef struct CK_RC2_MAC_GENERAL_PARAMS {
+  CK_ULONG      ulEffectiveBits;  /* effective bits (1-1024) */
+  CK_ULONG      ulMacLength;      /* Length of MAC in bytes */
+} CK_RC2_MAC_GENERAL_PARAMS;
+
+typedef CK_RC2_MAC_GENERAL_PARAMS CK_PTR \
+  CK_RC2_MAC_GENERAL_PARAMS_PTR;
+
+
+/* CK_RC5_PARAMS provides the parameters to the CKM_RC5_ECB and
+ * CKM_RC5_MAC mechanisms */
+/* CK_RC5_PARAMS is new for v2.0 */
+typedef struct CK_RC5_PARAMS {
+  CK_ULONG      ulWordsize;  /* wordsize in bits */
+  CK_ULONG      ulRounds;    /* number of rounds */
+} CK_RC5_PARAMS;
+
+typedef CK_RC5_PARAMS CK_PTR CK_RC5_PARAMS_PTR;
+
+
+/* CK_RC5_CBC_PARAMS provides the parameters to the CKM_RC5_CBC
+ * mechanism */
+/* CK_RC5_CBC_PARAMS is new for v2.0 */
+typedef struct CK_RC5_CBC_PARAMS {
+  CK_ULONG      ulWordsize;  /* wordsize in bits */
+  CK_ULONG      ulRounds;    /* number of rounds */
+  CK_BYTE_PTR   pIv;         /* pointer to IV */
+  CK_ULONG      ulIvLen;     /* length of IV in bytes */
+} CK_RC5_CBC_PARAMS;
+
+typedef CK_RC5_CBC_PARAMS CK_PTR CK_RC5_CBC_PARAMS_PTR;
+
+
+/* CK_RC5_MAC_GENERAL_PARAMS provides the parameters for the
+ * CKM_RC5_MAC_GENERAL mechanism */
+/* CK_RC5_MAC_GENERAL_PARAMS is new for v2.0 */
+typedef struct CK_RC5_MAC_GENERAL_PARAMS {
+  CK_ULONG      ulWordsize;   /* wordsize in bits */
+  CK_ULONG      ulRounds;     /* number of rounds */
+  CK_ULONG      ulMacLength;  /* Length of MAC in bytes */
+} CK_RC5_MAC_GENERAL_PARAMS;
+
+typedef CK_RC5_MAC_GENERAL_PARAMS CK_PTR \
+  CK_RC5_MAC_GENERAL_PARAMS_PTR;
+
+
+/* CK_MAC_GENERAL_PARAMS provides the parameters to most block
+ * ciphers' MAC_GENERAL mechanisms.  Its value is the length of
+ * the MAC */
+/* CK_MAC_GENERAL_PARAMS is new for v2.0 */
+typedef CK_ULONG          CK_MAC_GENERAL_PARAMS;
+
+typedef CK_MAC_GENERAL_PARAMS CK_PTR CK_MAC_GENERAL_PARAMS_PTR;
+
+/* CK_DES/AES_ECB/CBC_ENCRYPT_DATA_PARAMS are new for v2.20 */
+typedef struct CK_DES_CBC_ENCRYPT_DATA_PARAMS {
+  CK_BYTE      iv[8];
+  CK_BYTE_PTR  pData;
+  CK_ULONG     length;
+} CK_DES_CBC_ENCRYPT_DATA_PARAMS;
+
+typedef CK_DES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR;
+
+typedef struct CK_AES_CBC_ENCRYPT_DATA_PARAMS {
+  CK_BYTE      iv[16];
+  CK_BYTE_PTR  pData;
+  CK_ULONG     length;
+} CK_AES_CBC_ENCRYPT_DATA_PARAMS;
+
+typedef CK_AES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR;
+
+/* CK_SKIPJACK_PRIVATE_WRAP_PARAMS provides the parameters to the
+ * CKM_SKIPJACK_PRIVATE_WRAP mechanism */
+/* CK_SKIPJACK_PRIVATE_WRAP_PARAMS is new for v2.0 */
+typedef struct CK_SKIPJACK_PRIVATE_WRAP_PARAMS {
+  CK_ULONG      ulPasswordLen;
+  CK_BYTE_PTR   pPassword;
+  CK_ULONG      ulPublicDataLen;
+  CK_BYTE_PTR   pPublicData;
+  CK_ULONG      ulPAndGLen;
+  CK_ULONG      ulQLen;
+  CK_ULONG      ulRandomLen;
+  CK_BYTE_PTR   pRandomA;
+  CK_BYTE_PTR   pPrimeP;
+  CK_BYTE_PTR   pBaseG;
+  CK_BYTE_PTR   pSubprimeQ;
+} CK_SKIPJACK_PRIVATE_WRAP_PARAMS;
+
+typedef CK_SKIPJACK_PRIVATE_WRAP_PARAMS CK_PTR \
+  CK_SKIPJACK_PRIVATE_WRAP_PTR;
+
+
+/* CK_SKIPJACK_RELAYX_PARAMS provides the parameters to the
+ * CKM_SKIPJACK_RELAYX mechanism */
+/* CK_SKIPJACK_RELAYX_PARAMS is new for v2.0 */
+typedef struct CK_SKIPJACK_RELAYX_PARAMS {
+  CK_ULONG      ulOldWrappedXLen;
+  CK_BYTE_PTR   pOldWrappedX;
+  CK_ULONG      ulOldPasswordLen;
+  CK_BYTE_PTR   pOldPassword;
+  CK_ULONG      ulOldPublicDataLen;
+  CK_BYTE_PTR   pOldPublicData;
+  CK_ULONG      ulOldRandomLen;
+  CK_BYTE_PTR   pOldRandomA;
+  CK_ULONG      ulNewPasswordLen;
+  CK_BYTE_PTR   pNewPassword;
+  CK_ULONG      ulNewPublicDataLen;
+  CK_BYTE_PTR   pNewPublicData;
+  CK_ULONG      ulNewRandomLen;
+  CK_BYTE_PTR   pNewRandomA;
+} CK_SKIPJACK_RELAYX_PARAMS;
+
+typedef CK_SKIPJACK_RELAYX_PARAMS CK_PTR \
+  CK_SKIPJACK_RELAYX_PARAMS_PTR;
+
+
+typedef struct CK_PBE_PARAMS {
+  CK_BYTE_PTR      pInitVector;
+  CK_UTF8CHAR_PTR  pPassword;
+  CK_ULONG         ulPasswordLen;
+  CK_BYTE_PTR      pSalt;
+  CK_ULONG         ulSaltLen;
+  CK_ULONG         ulIteration;
+} CK_PBE_PARAMS;
+
+typedef CK_PBE_PARAMS CK_PTR CK_PBE_PARAMS_PTR;
+
+
+/* CK_KEY_WRAP_SET_OAEP_PARAMS provides the parameters to the
+ * CKM_KEY_WRAP_SET_OAEP mechanism */
+/* CK_KEY_WRAP_SET_OAEP_PARAMS is new for v2.0 */
+typedef struct CK_KEY_WRAP_SET_OAEP_PARAMS {
+  CK_BYTE       bBC;     /* block contents byte */
+  CK_BYTE_PTR   pX;      /* extra data */
+  CK_ULONG      ulXLen;  /* length of extra data in bytes */
+} CK_KEY_WRAP_SET_OAEP_PARAMS;
+
+typedef CK_KEY_WRAP_SET_OAEP_PARAMS CK_PTR \
+  CK_KEY_WRAP_SET_OAEP_PARAMS_PTR;
+
+
+typedef struct CK_SSL3_RANDOM_DATA {
+  CK_BYTE_PTR  pClientRandom;
+  CK_ULONG     ulClientRandomLen;
+  CK_BYTE_PTR  pServerRandom;
+  CK_ULONG     ulServerRandomLen;
+} CK_SSL3_RANDOM_DATA;
+
+
+typedef struct CK_SSL3_MASTER_KEY_DERIVE_PARAMS {
+  CK_SSL3_RANDOM_DATA RandomInfo;
+  CK_VERSION_PTR pVersion;
+} CK_SSL3_MASTER_KEY_DERIVE_PARAMS;
+
+typedef struct CK_SSL3_MASTER_KEY_DERIVE_PARAMS CK_PTR \
+  CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR;
+
+
+typedef struct CK_SSL3_KEY_MAT_OUT {
+  CK_OBJECT_HANDLE hClientMacSecret;
+  CK_OBJECT_HANDLE hServerMacSecret;
+  CK_OBJECT_HANDLE hClientKey;
+  CK_OBJECT_HANDLE hServerKey;
+  CK_BYTE_PTR      pIVClient;
+  CK_BYTE_PTR      pIVServer;
+} CK_SSL3_KEY_MAT_OUT;
+
+typedef CK_SSL3_KEY_MAT_OUT CK_PTR CK_SSL3_KEY_MAT_OUT_PTR;
+
+
+typedef struct CK_SSL3_KEY_MAT_PARAMS {
+  CK_ULONG                ulMacSizeInBits;
+  CK_ULONG                ulKeySizeInBits;
+  CK_ULONG                ulIVSizeInBits;
+  CK_BBOOL                bIsExport;
+  CK_SSL3_RANDOM_DATA     RandomInfo;
+  CK_SSL3_KEY_MAT_OUT_PTR pReturnedKeyMaterial;
+} CK_SSL3_KEY_MAT_PARAMS;
+
+typedef CK_SSL3_KEY_MAT_PARAMS CK_PTR CK_SSL3_KEY_MAT_PARAMS_PTR;
+
+/* CK_TLS_PRF_PARAMS is new for version 2.20 */
+typedef struct CK_TLS_PRF_PARAMS {
+  CK_BYTE_PTR  pSeed;
+  CK_ULONG     ulSeedLen;
+  CK_BYTE_PTR  pLabel;
+  CK_ULONG     ulLabelLen;
+  CK_BYTE_PTR  pOutput;
+  CK_ULONG_PTR pulOutputLen;
+} CK_TLS_PRF_PARAMS;
+
+typedef CK_TLS_PRF_PARAMS CK_PTR CK_TLS_PRF_PARAMS_PTR;
+
+/* WTLS is new for version 2.20 */
+typedef struct CK_WTLS_RANDOM_DATA {
+  CK_BYTE_PTR pClientRandom;
+  CK_ULONG    ulClientRandomLen;
+  CK_BYTE_PTR pServerRandom;
+  CK_ULONG    ulServerRandomLen;
+} CK_WTLS_RANDOM_DATA;
+
+typedef CK_WTLS_RANDOM_DATA CK_PTR CK_WTLS_RANDOM_DATA_PTR;
+
+typedef struct CK_WTLS_MASTER_KEY_DERIVE_PARAMS {
+  CK_MECHANISM_TYPE   DigestMechanism;
+  CK_WTLS_RANDOM_DATA RandomInfo;
+  CK_BYTE_PTR         pVersion;
+} CK_WTLS_MASTER_KEY_DERIVE_PARAMS;
+
+typedef CK_WTLS_MASTER_KEY_DERIVE_PARAMS CK_PTR \
+  CK_WTLS_MASTER_KEY_DERIVE_PARAMS_PTR;
+
+typedef struct CK_WTLS_PRF_PARAMS {
+  CK_MECHANISM_TYPE DigestMechanism;
+  CK_BYTE_PTR       pSeed;
+  CK_ULONG          ulSeedLen;
+  CK_BYTE_PTR       pLabel;
+  CK_ULONG          ulLabelLen;
+  CK_BYTE_PTR       pOutput;
+  CK_ULONG_PTR      pulOutputLen;
+} CK_WTLS_PRF_PARAMS;
+
+typedef CK_WTLS_PRF_PARAMS CK_PTR CK_WTLS_PRF_PARAMS_PTR;
+
+typedef struct CK_WTLS_KEY_MAT_OUT {
+  CK_OBJECT_HANDLE hMacSecret;
+  CK_OBJECT_HANDLE hKey;
+  CK_BYTE_PTR      pIV;
+} CK_WTLS_KEY_MAT_OUT;
+
+typedef CK_WTLS_KEY_MAT_OUT CK_PTR CK_WTLS_KEY_MAT_OUT_PTR;
+
+typedef struct CK_WTLS_KEY_MAT_PARAMS {
+  CK_MECHANISM_TYPE       DigestMechanism;
+  CK_ULONG                ulMacSizeInBits;
+  CK_ULONG                ulKeySizeInBits;
+  CK_ULONG                ulIVSizeInBits;
+  CK_ULONG                ulSequenceNumber;
+  CK_BBOOL                bIsExport;
+  CK_WTLS_RANDOM_DATA     RandomInfo;
+  CK_WTLS_KEY_MAT_OUT_PTR pReturnedKeyMaterial;
+} CK_WTLS_KEY_MAT_PARAMS;
+
+typedef CK_WTLS_KEY_MAT_PARAMS CK_PTR CK_WTLS_KEY_MAT_PARAMS_PTR;
+
+/* CMS is new for version 2.20 */
+typedef struct CK_CMS_SIG_PARAMS {
+  CK_OBJECT_HANDLE      certificateHandle;
+  CK_MECHANISM_PTR      pSigningMechanism;
+  CK_MECHANISM_PTR      pDigestMechanism;
+  CK_UTF8CHAR_PTR       pContentType;
+  CK_BYTE_PTR           pRequestedAttributes;
+  CK_ULONG              ulRequestedAttributesLen;
+  CK_BYTE_PTR           pRequiredAttributes;
+  CK_ULONG              ulRequiredAttributesLen;
+} CK_CMS_SIG_PARAMS;
+
+typedef CK_CMS_SIG_PARAMS CK_PTR CK_CMS_SIG_PARAMS_PTR;
+
+typedef struct CK_KEY_DERIVATION_STRING_DATA {
+  CK_BYTE_PTR pData;
+  CK_ULONG    ulLen;
+} CK_KEY_DERIVATION_STRING_DATA;
+
+typedef CK_KEY_DERIVATION_STRING_DATA CK_PTR \
+  CK_KEY_DERIVATION_STRING_DATA_PTR;
+
+
+/* The CK_EXTRACT_PARAMS is used for the
+ * CKM_EXTRACT_KEY_FROM_KEY mechanism.  It specifies which bit
+ * of the base key should be used as the first bit of the
+ * derived key */
+/* CK_EXTRACT_PARAMS is new for v2.0 */
+typedef CK_ULONG CK_EXTRACT_PARAMS;
+
+typedef CK_EXTRACT_PARAMS CK_PTR CK_EXTRACT_PARAMS_PTR;
+
+/* CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE is new for v2.10.
+ * CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE is used to
+ * indicate the Pseudo-Random Function (PRF) used to generate
+ * key bits using PKCS #5 PBKDF2. */
+typedef CK_ULONG CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE;
+
+typedef CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE CK_PTR CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR;
+
+/* The following PRFs are defined in PKCS #5 v2.0. */
+#define CKP_PKCS5_PBKD2_HMAC_SHA1 0x00000001
+
+
+/* CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE is new for v2.10.
+ * CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE is used to indicate the
+ * source of the salt value when deriving a key using PKCS #5
+ * PBKDF2. */
+typedef CK_ULONG CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE;
+
+typedef CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE CK_PTR CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR;
+
+/* The following salt value sources are defined in PKCS #5 v2.0. */
+#define CKZ_SALT_SPECIFIED        0x00000001
+
+/* CK_PKCS5_PBKD2_PARAMS is new for v2.10.
+ * CK_PKCS5_PBKD2_PARAMS is a structure that provides the
+ * parameters to the CKM_PKCS5_PBKD2 mechanism. */
+typedef struct CK_PKCS5_PBKD2_PARAMS {
+        CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE           saltSource;
+        CK_VOID_PTR                                pSaltSourceData;
+        CK_ULONG                                   ulSaltSourceDataLen;
+        CK_ULONG                                   iterations;
+        CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE prf;
+        CK_VOID_PTR                                pPrfData;
+        CK_ULONG                                   ulPrfDataLen;
+        CK_UTF8CHAR_PTR                            pPassword;
+        CK_ULONG_PTR                               ulPasswordLen;
+} CK_PKCS5_PBKD2_PARAMS;
+
+typedef CK_PKCS5_PBKD2_PARAMS CK_PTR CK_PKCS5_PBKD2_PARAMS_PTR;
+
+#endif
diff -r -u -N openssl-0.9.8g/demos/easy_tls/cacerts.pem openssl/demos/easy_tls/cacerts.pem
--- openssl-0.9.8g/demos/easy_tls/cacerts.pem	2001-09-17 21:06:57.000000000 +0200
+++ openssl/demos/easy_tls/cacerts.pem	2007-10-25 01:27:09.000000000 +0200
@@ -1,4 +1,4 @@
-$Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $
+$Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $
 
 issuer= /C=AU/ST=Queensland/O=CryptSoft Pty Ltd/CN=Test PCA (1024 bit)
 subject=/C=AU/ST=Queensland/O=CryptSoft Pty Ltd/CN=Test CA (1024 bit)
diff -r -u -N openssl-0.9.8g/demos/easy_tls/cert.pem openssl/demos/easy_tls/cert.pem
--- openssl-0.9.8g/demos/easy_tls/cert.pem	2001-09-17 21:06:57.000000000 +0200
+++ openssl/demos/easy_tls/cert.pem	2007-10-25 01:27:09.000000000 +0200
@@ -1,4 +1,4 @@
-$Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $
+$Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $
 
 Example certificate and key.
 
diff -r -u -N openssl-0.9.8g/demos/easy_tls/easy-tls.c openssl/demos/easy_tls/easy-tls.c
--- openssl-0.9.8g/demos/easy_tls/easy-tls.c	2002-03-05 10:07:16.000000000 +0100
+++ openssl/demos/easy_tls/easy-tls.c	2007-10-25 01:27:09.000000000 +0200
@@ -1,7 +1,7 @@
 /* -*- Mode: C; c-file-style: "bsd" -*- */
 /*
  * easy-tls.c -- generic TLS proxy.
- * $Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $
+ * $Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $
  */
 /*
  (c) Copyright 1999 Bodo Moeller.  All rights reserved.
@@ -73,7 +73,7 @@
  */
 
 static char const rcsid[] =
-"$Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $";
+"$Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $";
 
 #include <assert.h>
 #include <errno.h>
diff -r -u -N openssl-0.9.8g/demos/easy_tls/easy-tls.h openssl/demos/easy_tls/easy-tls.h
--- openssl-0.9.8g/demos/easy_tls/easy-tls.h	2001-09-17 21:06:59.000000000 +0200
+++ openssl/demos/easy_tls/easy-tls.h	2007-10-25 01:27:09.000000000 +0200
@@ -1,7 +1,7 @@
 /* -*- Mode: C; c-file-style: "bsd" -*- */
 /*
  * easy-tls.h -- generic TLS proxy.
- * $Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $
+ * $Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $
  */
 /*
  * (c) Copyright 1999 Bodo Moeller.  All rights reserved.
diff -r -u -N openssl-0.9.8g/demos/easy_tls/Makefile openssl/demos/easy_tls/Makefile
--- openssl-0.9.8g/demos/easy_tls/Makefile	2001-09-18 11:15:40.000000000 +0200
+++ openssl/demos/easy_tls/Makefile	2007-10-25 01:27:09.000000000 +0200
@@ -1,5 +1,5 @@
 # Makefile for easy-tls example application (rudimentary client and server)
-# $Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $
+# $Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $
 
 SOLARIS_CFLAGS=-Wall -pedantic -g -O2
 SOLARIS_LIBS=-lxnet
diff -r -u -N openssl-0.9.8g/demos/easy_tls/test.c openssl/demos/easy_tls/test.c
--- openssl-0.9.8g/demos/easy_tls/test.c	2001-09-17 21:06:59.000000000 +0200
+++ openssl/demos/easy_tls/test.c	2007-10-25 01:27:09.000000000 +0200
@@ -1,5 +1,5 @@
 /* test.c */
-/* $Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $ */
+/* $Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $ */
 
 #define L_PORT 9999
 #define C_PORT 443
diff -r -u -N openssl-0.9.8g/demos/easy_tls/test.h openssl/demos/easy_tls/test.h
--- openssl-0.9.8g/demos/easy_tls/test.h	2001-09-17 21:07:00.000000000 +0200
+++ openssl/demos/easy_tls/test.h	2007-10-25 01:27:09.000000000 +0200
@@ -1,5 +1,5 @@
 /* test.h */
-/* $Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $ */
+/* $Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $ */
 
 
 void test_process_init(int fd, int client_p, void *apparg);
diff -r -u -N openssl-0.9.8g/engines/vendor_defns/hwcryptohook.h openssl/engines/vendor_defns/hwcryptohook.h
--- openssl-0.9.8g/engines/vendor_defns/hwcryptohook.h	2002-10-11 19:10:59.000000000 +0200
+++ openssl/engines/vendor_defns/hwcryptohook.h	2007-10-25 01:27:09.000000000 +0200
@@ -65,7 +65,7 @@
  * please contact nCipher.
  *
  *
- * $Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $
+ * $Id: openssl-0.9.8g-patch,v 1.2 2008/03/31 14:42:50 fdupont Exp $
  */
 
 #ifndef HWCRYPTOHOOK_H
diff -r -u -N openssl-0.9.8g/Makefile.org openssl/Makefile.org
--- openssl-0.9.8g/Makefile.org	2007-04-24 01:49:54.000000000 +0200
+++ openssl/Makefile.org	2007-10-25 01:27:08.000000000 +0200
@@ -26,6 +26,9 @@
 INSTALL_PREFIX=
 INSTALLTOP=/usr/local/ssl
 
+# You must set this through --pk11-libname configure option.
+PK11_LIB_LOCATION=
+
 # Do not edit this manually. Use Configure --openssldir=DIR do change this!
 OPENSSLDIR=/usr/local/ssl
 
diff -r -u -N openssl-0.9.8g/README.pkcs11 openssl/README.pkcs11
--- openssl-0.9.8g/README.pkcs11	1970-01-01 01:00:00.000000000 +0100
+++ openssl/README.pkcs11	2008-01-31 15:24:32.000000000 +0100
@@ -0,0 +1,153 @@
+PKCS#11 engine support for OpenSSL 0.9.8g
+=========================================
+
+[Nov 21, 2007]
+
+This patch containing code available in OpenSolaris adds support for PKCS#11
+engine into OpenSSL and implements PKCS#11 v2.20. It is to be applied against
+OpenSSL 0.9.8g. Your system must provide PKCS#11 backend otherwise the patch
+is useless.
+
+Patch can be applied like this:
+
+	tar xfzv openssl-0.9.8g.tar.gz
+	cd openssl-0.9.8g
+	patch -p1 < ../pkcs11_engine-0.9.8g.patch.2007-11-21
+
+It is designed to support pure acceleration for RSA, DSA, DH and all the
+symetric ciphers and message digest algorithms that PKCS#11 and OpenSSL share
+except for missing support for patented algorithms MDC2, RC3, RC5 and IDEA.
+
+It also contains experimental code for accessing RSA keys stored in pkcs#11 key
+stores by reference. See below for more information.
+
+You must provide the location of PKCS#11 library in your system to the
+configure script, eg. if you use libraries from openCryptoki project on Linux
+AMD64 box, run configure like this:
+
+	./config --pk11-libname=/usr/lib64/pkcs11/PKCS11_API.so
+
+To check whether newly built openssl really supports PKCS#11 it's enough to
+run "apps/openssl engine" and look for "(pkcs11) PKCS #11 engine support" in
+the output.
+
+This patch was tested on Solaris against PKCS#11 engine available from Solaris
+Cryptographic Framework (Solaris 10 and OpenSolaris) and also on Linux using
+PKCS#11 libraries from openCryptoki project (see openCryptoki website
+http://sourceforge.net/projects/opencryptoki for more information). Some Linux
+distributions even ship those libraries with the system. The patch should work
+on any system that is supported by OpenSSL itself and has functional PKCS#11
+library.
+
+The patch contains "RSA Security Inc. PKCS #11 Cryptographic Token Interface
+(Cryptoki)" - files cryptoki.h, pkcs11.h, pkcs11f.h and pkcs11t.h which are
+copyrighted by RSA Security Inc., see pkcs11.h for more information.
+
+Other added/modified code in this patch is copyrighted by Sun Microsystems,
+Inc. and is released under the OpenSSL license (see LICENSE file for more
+information).
+
+Revisions of patch for 0.9.8 branch
+===================================
+
+2007-11-21
+- update for 0.9.8g version 
+- fixes in the draft code for "6607670 teach pkcs#11 engine how to use keys
+  be reference" so that it doesn't coredump when the referenced key is not
+  present
+
+2007-10-15
+- update for 0.9.8f version 
+- update for "6607670 teach pkcs#11 engine how to use keys be reference"
+
+2007-10-02
+- draft for "6607670 teach pkcs#11 engine how to use keys be reference"
+- draft for "6607307 pkcs#11 engine can't read RSA private keys"
+
+2007-09-26
+- 6375348 Using pkcs11 as the SSLCryptoDevice with Apache/OpenSSL causes
+	  significant performance drop
+- 6573196 memory is leaked when OpenSSL is used with PKCS#11 engine
+
+2007-05-25
+- 6558630 race in OpenSSL pkcs11 engine when using symetric block ciphers
+
+2007-05-19
+- initial patch for 0.9.8e using latest OpenSolaris code
+
+Notes
+=====
+
+This patch version contains not very well tested code for referencing RSA keys
+in keystores by labels. That code might and might not end up in OpenSolaris
+code base in the future. If you use this particular functionality with this
+patch I would be very grateful to get any feedback from you (please see my
+contact in the bottom).
+
+Issues
+------
+- can't reference public keys inside of certificates using certificate label
+- can't reference symetric keys
+- simple references in form of "pkcs11:LABEL" only are supported now. This is
+  supposed to be changed according to discussion on pkcs11 mailing list; comma
+  separated list of attributes is planned to be used.
+- getpassphrase(3c) is used for entering the PIN. This should be changed to a
+  more general approach; to check if the process has allocated tty and use
+  other means of entering the PIN if not.
+
+Usage
+-----
+See examples below using Solaris's pktool(1):
+
+# list private keys (note "mycert" label. Basically, we can't generate a
+# pub/priv key pair with pktool(1) without creating a certificate. This should
+# be changed in the future).
+$ pktool list objtype=private
+Enter PIN for Sun Software PKCS#11 softtoken  : 
+Found 1 keys.
+Key #1 - RSA private key:  mycert
+
+# this file is going to be signed
+$ cat test
+hello
+
+# sign it, note "pkcs11:mycert" private key's label
+$ openssl rsautl -inkey pkcs11:mycert -out test2 -in test -sign -keyform e -engine pkcs11
+engine "pkcs11" set.
+Enter PIN:
+
+# export the certificate out of the keyring
+$ pktool export keystore=pkcs11 label=mycert outfile=mycert.cert outformat=pem
+Warning: file "mycert.cert" exists, will be overwritten.
+Continue with export? y
+
+# verify using OpenSSL without pkcs#11 engine and with the certificate in the
+# file. This is proof of concept that a file signed with key by reference is
+# successfully verified when stock OpenSSL is used (I didn't have public key
+# in the keystore, only the certificate. There is no way to reference a public
+# key inside of the certificate).
+$ openssl rsautl -verify -inkey mycert.cert -certin -in test2
+hello
+
+API
+---
+You can use ENGINE_load_public_key() and ENGINE_load_private_key() functions
+only. The 2nd parameter of those calls is the one to use for "pkcs11:LABEL"
+filename overloading. If used that way, both functions will look for the key
+in the available keystores. Only one such key must be present. The private key
+is never extracted from the keystore. See OpenSSL's engine(3) or header file
+openssl/engine.h for more information.
+
+Note that those functions return a pointer to EVP_PKEY structure that contains
+all necessary information for accesing the key by label then. The pointer can be
+used in other functions that work with RSA keys - X509_sign() for example. See
+source code in apps/ subdirectory for reference.
+
+Feedback
+========
+
+Please send feedback to security-discuss@opensolaris.org. The patch was
+created by Jan.Pechanec@Sun.COM from code available in OpenSolaris.
+
+Latest version should be always available on http://blogs.sun.com/janp.
+