summaryrefslogtreecommitdiffstats
path: root/base/symkey/src/com/netscape/symkey/SessionKey.cpp
blob: 610928099feef62b44ceb75c4b26f89815bb738b (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

// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---

#ifdef __cplusplus
extern "C"
{
#endif
#include "pk11func.h"
#include "seccomon.h"
#include "nspr.h"
#ifdef __cplusplus
#include <jni.h>
#include <assert.h>
#include <string.h>
#include "secerr.h"

/*
#include <jss_exceptions.h>
#include <jssutil.h>
*/

}
#endif
#include <memory.h>
#include <assert.h>
#include <stdio.h>
#include <cstdarg>
#include <string>

// DRM_PROTO begins
#define PK11SYMKEY_CLASS_NAME "org/mozilla/jss/pkcs11/PK11SymKey"
#define PK11SYMKEY_CONSTRUCTOR_SIG "([B)V"
#define ALL_SYMKEY_OPS  (CKF_ENCRYPT | CKF_DECRYPT | CKF_WRAP | CKF_UNWRAP)
// DRM_PROTO ends

#include "Buffer.h"
#include "SymKey.h"

// AC: KDF SPEC CHANGE: Include headers for NIST SP800-108 KDF functions.
#include "NistSP800_108KDF.h"


#define STEAL_JSS
#ifdef STEAL_JSS
// stealing code from JSS to handle DRM support
/*
 * NativeProxy
 */
#define NATIVE_PROXY_CLASS_NAME  "org/mozilla/jss/util/NativeProxy"
#define NATIVE_PROXY_POINTER_FIELD "mPointer"
#define NATIVE_PROXY_POINTER_SIG "[B"

/*
 * SymKeyProxy
 */
#define SYM_KEY_PROXY_FIELD "keyProxy"
#define SYM_KEY_PROXY_SIG "Lorg/mozilla/jss/pkcs11/SymKeyProxy;"


/***********************************************************************
 **
 ** J S S _ p t r T o B y t e A r r a y
 **
 ** Turn a C pointer into a Java byte array. The byte array can be passed
 ** into a NativeProxy constructor.
 **
 ** Returns a byte array containing the pointer, or NULL if an exception
 ** was thrown.
 */
jbyteArray
JSS_ptrToByteArray(JNIEnv *env, void *ptr)
{
    jbyteArray byteArray;

    /* Construct byte array from the pointer */
    byteArray = (env)->NewByteArray(sizeof(ptr));
    if(byteArray==NULL)
    {
        PR_ASSERT( (env)->ExceptionOccurred() != NULL);
        return NULL;
    }
    (env)->SetByteArrayRegion(byteArray, 0, sizeof(ptr), (jbyte*)&ptr);
    if((env)->ExceptionOccurred() != NULL)
    {
        PR_ASSERT(PR_FALSE);
        return NULL;
    }
    return byteArray;
}


/***********************************************************************
 *
 * J S S _ P K 1 1 _ w r a p S y m K e y

 * Puts a Symmetric Key into a Java object.
 * (Does NOT perform a cryptographic "wrap" operation.)
 * symKey: will be stored in a Java wrapper.
 * Returns: a new PK11SymKey, or NULL if an exception occurred.
 */
jobject
JSS_PK11_wrapSymKey(JNIEnv *env, PK11SymKey **symKey)
{
//    return JSS_PK11_wrapSymKey(env, symKey, NULL);
// hmmm, looks like I may not need to steal code after all
    return JSS_PK11_wrapSymKey(env, symKey);
}


jobject
JSS_PK11_wrapSymKey(JNIEnv *env, PK11SymKey **symKey, PRFileDesc *debug_fd)
{
    jclass keyClass;
    jmethodID constructor;
    jbyteArray ptrArray;
    jobject Key=NULL;

    if (debug_fd)
        PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey\n");

    PR_ASSERT(env!=NULL && symKey!=NULL && *symKey!=NULL);

    /* find the class */
    keyClass = (env)->FindClass(PK11SYMKEY_CLASS_NAME);
    if (debug_fd)
        PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey called FindClass\n");
    if( keyClass == NULL )
    {
        if (debug_fd)
            PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey FindClass NULL\n");
//        ASSERT_OUTOFMEM(env);
        goto finish;
    }

    /* find the constructor */
    constructor = (env)->GetMethodID(keyClass,
        "<init>"/*PLAIN_CONSTRUCTOR*/,
        PK11SYMKEY_CONSTRUCTOR_SIG);
    if (debug_fd)
        PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey called GetMethodID\n");
    if(constructor == NULL)
    {
//        ASSERT_OUTOFMEM(env);
        if (debug_fd)
            PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey GetMethodID returns NULL\n");
        goto finish;
    }

    /* convert the pointer to a byte array */
    ptrArray = JSS_ptrToByteArray(env, (void*)*symKey);
    if (debug_fd)
        PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey called JSS_ptrToByteArray\n");
    if( ptrArray == NULL )
    {
        if (debug_fd)
            PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey JSS_ptrToByteArray returns NULL\n");
        goto finish;
    }

    /* call the constructor */
    Key = (env)->NewObject( keyClass, constructor, ptrArray);
    if (debug_fd)
        PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey called NewObject\n");

finish:
    if(Key == NULL)
    {
        if (debug_fd)
            PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey NewObject returns NULL\n");
        PK11_FreeSymKey(*symKey);
    }
    *symKey = NULL;
    return Key;
}


/***********************************************************************
 **
 ** J S S _ g e t P t r F r o m P r o x y
 **
 ** Given a NativeProxy, extract the pointer and store it at the given
 ** address.
 **
 ** nativeProxy: a JNI reference to a NativeProxy.
 ** ptr: address of a void* that will receive the pointer extracted from
 **      the NativeProxy.
 ** Returns: PR_SUCCESS on success, PR_FAILURE if an exception was thrown.
 **
 ** Example:
 **  DataStructure *recovered;
 **  jobject proxy;
 **  JNIEnv *env;
 **  [...]
 **  if(JSS_getPtrFromProxy(env, proxy, (void**)&recovered) != PR_SUCCESS) {
 **      return;  // exception was thrown!
 **  }
 */
PRStatus
JSS_getPtrFromProxy(JNIEnv *env, jobject nativeProxy, void **ptr)
{
#ifdef DEBUG
    jclass nativeProxyClass;
#endif
    jclass proxyClass;
    jfieldID byteArrayField;
    jbyteArray byteArray;
    int size;

    PR_ASSERT(env!=NULL && nativeProxy != NULL && ptr != NULL);
    if( nativeProxy == NULL )
    {
//        JSS_throw(env, NULL_POINTER_EXCEPTION);
        return PR_FAILURE;
    }

    proxyClass = (env)->GetObjectClass(nativeProxy);
    PR_ASSERT(proxyClass != NULL);

#ifdef DEBUG
    nativeProxyClass = (env)->FindClass(
        NATIVE_PROXY_CLASS_NAME);
    if(nativeProxyClass == NULL)
    {
//        ASSERT_OUTOFMEM(env);
        return PR_FAILURE;
    }

    /* make sure what we got was really a NativeProxy object */
    PR_ASSERT( (env)->IsInstanceOf(nativeProxy, nativeProxyClass) );
#endif

    byteArrayField = (env)->GetFieldID(
        proxyClass,
        NATIVE_PROXY_POINTER_FIELD,
        NATIVE_PROXY_POINTER_SIG);
    if(byteArrayField==NULL)
    {
//        ASSERT_OUTOFMEM(env);
        return PR_FAILURE;
    }

    byteArray = (jbyteArray) (env)->GetObjectField(nativeProxy,
        byteArrayField);
    PR_ASSERT(byteArray != NULL);

    size = sizeof(*ptr);
    PR_ASSERT((env)->GetArrayLength( byteArray) == size);
    (env)->GetByteArrayRegion(byteArray, 0, size, (jbyte*)ptr);
    if( (env)->ExceptionOccurred() )
    {
        PR_ASSERT(PR_FALSE);
        return PR_FAILURE;
    }
    else
    {
        return PR_SUCCESS;
    }
}


/***********************************************************************
 **
 ** J S S _ g e t P t r F r o m P r o x y O w n e r
 **
 ** Given an object which contains a NativeProxy, extract the pointer
 ** from the NativeProxy and store it at the given address.
 **
 ** proxyOwner: an object which contains a NativeProxy member.
 ** proxyFieldName: the name of the NativeProxy member.
 ** proxyFieldSig: the signature of the NativeProxy member.
 ** ptr: address of a void* that will receive the extract pointer.
 ** Returns: PR_SUCCESS for success, PR_FAILURE if an exception was thrown.
 **
 ** Example:
 ** <Java>
 ** public class Owner {
 **      protected MyProxy myProxy;
 **      [...]
 ** }
 **
 ** <C>
 **  DataStructure *recovered;
 **  jobject owner;
 **  JNIEnv *env;
 **  [...]
 **  if(JSS_getPtrFromProxyOwner(env, owner, "myProxy", (void**)&recovered)
 **              != PR_SUCCESS) {
 **      return;  // exception was thrown!
 **  }
 */
PRStatus
JSS_getPtrFromProxyOwner(JNIEnv *env, jobject proxyOwner, char* proxyFieldName,
char *proxyFieldSig, void **ptr)
{
    jclass ownerClass;
    jfieldID proxyField;
    jobject proxyObject;

    PR_ASSERT(env!=NULL && proxyOwner!=NULL && proxyFieldName!=NULL &&
        ptr!=NULL);

    /*
     * Get proxy object
     */
    ownerClass = (env)->GetObjectClass(proxyOwner);
    proxyField = (env)->GetFieldID(ownerClass, proxyFieldName,
        proxyFieldSig);
    if(proxyField == NULL)
    {
        return PR_FAILURE;
    }
    proxyObject = (env)->GetObjectField(proxyOwner, proxyField);
    PR_ASSERT(proxyObject != NULL);

    /*
     * Get the pointer from the Native Reference object
     */
    return JSS_getPtrFromProxy(env, proxyObject, ptr);
}


/***********************************************************************
 *
 * J S S _ P K 1 1 _ g e t S y m K e y P t r
 *
 */
PRStatus
JSS_PK11_getSymKeyPtr(JNIEnv *env, jobject symKeyObject, PK11SymKey **ptr)
{
    PR_ASSERT(env!=NULL && symKeyObject!=NULL);

    /* Get the pointer from the key proxy */
    return JSS_getPtrFromProxyOwner(env, symKeyObject, SYM_KEY_PROXY_FIELD,
        SYM_KEY_PROXY_SIG, (void**)ptr);
}
#endif                                            //STEAL_JSS


/* ToDo: fully support nistSP800 in next ticket
*/
PK11SymKey *DeriveKeySCP02(PK11SymKey *cardKey, const Buffer& sequenceCounter, const Buffer& derivationConstant)
{

    PK11SymKey *key = NULL;
    PK11SymKey *master = NULL;
    unsigned char message[KEYLENGTH] = {0};
    unsigned char derivationData[DES3_LENGTH] = {0};

    PRBool invalid_mechanism = PR_TRUE;
    SECStatus s = SECFailure;
    int len = 0;
    int i = 0;

    SECItem *secParam = NULL;

    PK11SlotInfo *slot = PK11_GetInternalKeySlot();
    PK11Context *context = NULL;
     SECItem param = { siBuffer, NULL, 0 };

    unsigned char icv[EIGHT_BYTES] = { 0 };

    if( sequenceCounter == NULL || derivationConstant == NULL || 
        sequenceCounter.size() != 2 || derivationConstant.size() != 2 || 
        cardKey == NULL) {
         PR_fprintf(PR_STDERR,"In DeriveKeySCP02!  Error invalid input data!\n");
         goto done;
    }

    PR_fprintf(PR_STDOUT,"In DeriveKeySCP02! \n");
    PR_fprintf(PR_STDOUT,"In DeriveKeySCP02! seqCounter[0] : %d sequenceCounter [1] : %d \n", sequenceCounter[0], sequenceCounter[1]);
    PR_fprintf(PR_STDOUT,"In DeriveKeySCP02! derivationConstant[0] : %x derivationConstant[1] : %x \n", derivationConstant[0], derivationConstant[1]);

    master = cardKey;

    message[0] = (unsigned char) derivationConstant[0];
    message[1] = (unsigned char) derivationConstant[1];
    message[2] = (unsigned char) sequenceCounter[0];
    message[3] = (unsigned char) sequenceCounter[1];


    //ToDo use the new NSS provided derive mechanisms for this operation
    if(invalid_mechanism == PR_FALSE) {
       // Use derive mechanisms
    } else {

        //Use encryption method
        param.data = (unsigned char *) &icv;
        param.len = 8;
        secParam = PK11_ParamFromIV(CKM_DES3_CBC_PAD, &param);
        context = PK11_CreateContextBySymKey(CKM_DES3_CBC_PAD, CKA_ENCRYPT, master, secParam);
        if(context == NULL) {
            goto done;
        }
         s = PK11_CipherOp(context,&derivationData[0] , &len, EIGHT_BYTES, &message[0], EIGHT_BYTES);

         if (s != SECSuccess) { goto done; }
        
         s = PK11_CipherOp(context, &derivationData[EIGHT_BYTES], &len, EIGHT_BYTES, &message[EIGHT_BYTES], EIGHT_BYTES); 
         if (s != SECSuccess) { goto done; } 

         for(i = 0;i < EIGHT_BYTES ;i++)
         {
             derivationData[i+KEYLENGTH] = derivationData[i];
         }

         key = CreateUnWrappedSymKeyOnToken( slot,  master, &derivationData[0] , DES3_LENGTH, PR_FALSE );

          PR_fprintf(PR_STDOUT,"In DeriveKeySCP02! calculated key: %p  \n", key);
    }

    done:

    memset(derivationData, 0, sizeof derivationData);
    if ( context != NULL) {
        PK11_DestroyContext(context, PR_TRUE);
        context = NULL;
    }

    if (slot) {
        PK11_FreeSlot(slot);
        slot = NULL;
    }

    if (secParam) {
        SECITEM_FreeItem(secParam, PR_TRUE);
        secParam = NULL;
    }

    return key;
}

// Function takes wither a symkey OR a keybuffer (for the default keyset case)
// To derive a new key.
PK11SymKey *DeriveKey(PK11SymKey *cardKey, const Buffer& hostChallenge, const Buffer& cardChallenge)
{
    PK11SymKey *key = NULL, *master = NULL;
    PK11SlotInfo *slot = PK11_GetInternalKeySlot();
    PK11Context *context = NULL;
    unsigned char derivationData[KEYLENGTH];
#ifdef DES2_WORKAROUND
    unsigned char keyData[DES3_LENGTH];
#else
    unsigned char keyData[KEYLENGTH];
#endif
    int i = 0;
    SECStatus s = SECSuccess;
    int len = 0;;
    static SECItem noParams = { siBuffer, NULL, 0 };

    /* vars for PK11_Derive section */
    SECItem param = { siBuffer, NULL, 0 };
    CK_KEY_DERIVATION_STRING_DATA string;
    PK11SymKey *tmp1  = NULL;
    PK11SymKey *tmp2 = NULL; 
    PRBool invalid_mechanism = PR_FALSE;
    CK_OBJECT_HANDLE keyhandle = 0;

    PR_fprintf(PR_STDOUT,"In DeriveKey! \n");
    master = cardKey;

    if( ! master ) goto done;

    for(i = 0;i < 4;i++)
    {
        derivationData[i] = cardChallenge[i+4];
        derivationData[i+4] = hostChallenge[i];
        derivationData[i+8] = cardChallenge[i];
        derivationData[i+12] = hostChallenge[i+4];
    }

    string.pData = &derivationData[0];
    string.ulLen = EIGHT_BYTES;
    param.data = (unsigned char*)&string;
    param.len = sizeof(string);

    invalid_mechanism = PR_TRUE;

    /* When NSS gets full ability to perform this mechanism in soft token, revisit this code to make sure it works. */
    /*
    tmp1 = PK11_Derive( master , CKM_DES_ECB_ENCRYPT_DATA , &param , CKM_CONCATENATE_BASE_AND_KEY  , CKA_DERIVE, 0);

    if ( tmp1 == NULL) {
       if ( PR_GetError() == SEC_ERROR_NO_TOKEN) 
           invalid_mechanism = PR_TRUE;

       PR_fprintf(PR_STDERR,"DeriveKey: Can't create key, using encrypt and derive method ! error %d \n", PR_GetError());
    } else {
       PR_fprintf(PR_STDOUT,"DeriveKey: Successfully created key using encrypt and derive method! \n");
    }
    */
    if ( invalid_mechanism == PR_FALSE) {

        string.pData = &derivationData[EIGHT_BYTES];
        string.ulLen = EIGHT_BYTES;

        tmp2 = PK11_Derive( master , CKM_DES_ECB_ENCRYPT_DATA , &param , CKM_CONCATENATE_BASE_AND_KEY , CKA_DERIVE , 0);

        if ( tmp2 == NULL) {
           PR_fprintf(PR_STDERR,"DeriveKey: Can't derive key using CONCATENATE method! \n");
           goto done;
        } else {
           PR_fprintf(PR_STDOUT,"DeriveKey: Successfully created key using CONCATENATE method! \n");
        }

        keyhandle = PK11_GetSymKeyHandle(tmp2);

        param.data=(unsigned char *) &keyhandle;
        param.len=sizeof(keyhandle);

        key = PK11_Derive ( tmp1 , CKM_CONCATENATE_BASE_AND_KEY , &param ,CKM_DES3_ECB , CKA_DERIVE , 16);

        if ( key == NULL) {
           PR_fprintf(PR_STDERR,"DeriveKey: Can't create final  derived key! \n");
           goto done;
        } else {
           PR_fprintf(PR_STDOUT,"DeriveKey: Successfully created final derived  key! \n");
        }

    }  else { /* We don't have access to the proper derive mechanism, use primitive mechanisms now */

        context = PK11_CreateContextBySymKey(CKM_DES3_ECB, CKA_ENCRYPT, master,
                      &noParams);

        if (!context) goto done;

        s = PK11_CipherOp(context, &keyData[0], &len, EIGHT_BYTES, &derivationData[0], EIGHT_BYTES);
        if (s != SECSuccess) goto done;

        s = PK11_CipherOp(context, &keyData[EIGHT_BYTES], &len, 8, &derivationData[EIGHT_BYTES], EIGHT_BYTES);
        if (s != SECSuccess) goto done;

         for(i = 0;i < EIGHT_BYTES ;i++)
         {
             keyData[i+KEYLENGTH] = keyData[i];
         }
         
         key = CreateUnWrappedSymKeyOnToken( slot,  master, &keyData[0] , DES3_LENGTH, PR_FALSE );

         if ( key  == NULL ) {
             PR_fprintf(PR_STDERR,"DeriveKey: CreateUnWrappedSymKey failed! %d \n", PR_GetError());
         } else {
            PR_fprintf(PR_STDOUT,"DeriveKey: CreateUnWrappedSymKey succeeded! \n");
         }
    }

    done:
    memset(keyData, 0, sizeof keyData);
    if ( context != NULL) {
        PK11_DestroyContext(context, PR_TRUE);
        context = NULL;
    }

    if (slot) {
        PK11_FreeSlot(slot);  
        slot = NULL;
    }
 
    if (tmp1) {
        PK11_FreeSymKey(tmp1);
        tmp1 = NULL;
    }

    if (tmp2) {
        PK11_FreeSymKey(tmp2);
        tmp2 = NULL;
    }

    return key;
}

#ifdef __cplusplus
extern "C"
{
#endif
    JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeKeyCheck
        (JNIEnv *, jclass, jobject deskeyObj);
#ifdef __cplusplus
}
#endif
extern "C" JNIEXPORT jbyteArray JNICALL
Java_com_netscape_symkey_SessionKey_ComputeKeyCheck
(JNIEnv* env, jclass this2, jobject deskeyObj)
{
    jbyteArray handleBA=NULL;
    jbyte *handleBytes=NULL;

    PK11SymKey *key = NULL;
//    PK11SlotInfo *slot = PK11_GetInternalKeySlot();
    PK11Context *context = NULL;
    SECStatus s = SECFailure;
    PRStatus  r = PR_FAILURE;
    int lenx = 0;
    static SECItem noParams = { siBuffer, NULL, 0 };

    unsigned char value[EIGHT_BYTES];

    memset(value, 0, sizeof value);

    r = JSS_PK11_getSymKeyPtr(env, deskeyObj, &key);

    if (r != PR_SUCCESS) {
        goto finish;
    }

    if ( ! key ) {
        goto finish;
    }

    context = PK11_CreateContextBySymKey(CKM_DES3_ECB, CKA_ENCRYPT, key,
        &noParams);
    if (!context) {
        goto finish;
    }

    s = PK11_CipherOp(context, &value[0], &lenx, EIGHT_BYTES, &value[0], EIGHT_BYTES);
    if (s != SECSuccess)
    {
        goto finish;
    }
    handleBA = (env)->NewByteArray(3);
    if(handleBA == NULL ) {
        goto finish;
    }
    handleBytes = (env)->GetByteArrayElements(handleBA, NULL);
    if(handleBytes==NULL) {
        goto finish;
    }
    memcpy(handleBytes, value, 3);

    if( handleBytes != NULL) {
        (env)->ReleaseByteArrayElements(handleBA, handleBytes, 0);
    }

finish:

    if ( context != NULL) {
        PK11_DestroyContext(context, PR_TRUE);
        context = NULL;
    }

//    if ( slot != NULL) {
//        PK11_FreeSlot(slot);
//        slot = NULL;
//    }

    return handleBA;
}


//ToDo: Fix this to conform the nistSP800
//=================================================================================
#ifdef __cplusplus
extern "C"
{
#endif
/*
 * Class:     com_netscape_cms_servlet_tks_RASessionKey
 * Method:    ComputeSessionKeySCP02
 * Signature: ([B[B[B[B)[B
 */
    JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeSessionKeySCP02
        (JNIEnv *, jclass, jstring, jstring, jbyteArray, jbyteArray, jbyteArray, jbyteArray, jbyteArray, jstring, jstring, jstring);
#ifdef __cplusplus
}
#endif
#define KEYLENGTH 16
extern "C" JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeSessionKeySCP02(JNIEnv * env, jclass this2, jstring tokenName, jstring keyName, jbyteArray keyInfo, jbyteArray CUID, jbyteArray devKeyArray, jbyteArray sequenceCounter, jbyteArray derivationConstant, jstring useSoftToken_s, jstring keySet, jstring sharedSecretKeyName)
{
    /* hardcode permanent dev key */
    jbyte *dev_key = NULL;
    if (devKeyArray != NULL) {
       dev_key = (jbyte*)(env)->GetByteArrayElements(devKeyArray, NULL);
    } else {
        return NULL;
    }

    SECItem wrappedKeyItem = { siBuffer, NULL , 0};
    SECItem noParams = { siBuffer, NULL, 0 };
    SECStatus wrapStatus = SECFailure;


    char *keyNameChars=NULL;
    char *tokenNameChars=NULL;
    PK11SlotInfo *slot = NULL;
    PK11SlotInfo *internal = PK11_GetInternalKeySlot();

    PK11SymKey *symkey = NULL;
    PK11SymKey *transportKey = NULL;
    PK11SymKey *masterKey = NULL;

    PK11SymKey *devSymKey = NULL;
    PK11SymKey *symkey16 = NULL;
    PK11SymKey *devKey = NULL;


    BYTE devData[KEYLENGTH];
    char keyname[KEYNAMELENGTH];
    
    const char *devKeyName = NULL;

    const char *macName = "mac";
    const char *encName = "enc";
    const char *kekName = "kek";

    keyType kType = mac;

    /* Derive vars */

    CK_ULONG bitPosition = 0;
    SECItem paramsItem = { siBuffer, NULL, 0 };

    /* Java object return vars */

    jbyteArray handleBA=NULL;
    jbyte *handleBytes=NULL;

    jbyte *    cuidValue = NULL;

    jbyte *sc = NULL;
    int sc_len = 0;

    int dc_len = 0;
    jbyte *dc = NULL;

    jbyte *    keyVersion = NULL;
    int keyVersion_len = 0;

    Buffer devBuff( ( BYTE *) dev_key , KEYLENGTH );

    char *keySetStringChars = NULL;
    if( keySet != NULL ) {
       keySetStringChars = (char *) (env)->GetStringUTFChars( keySet, NULL);
    }

    char *keySetString =  keySetStringChars;

    if ( keySetString == NULL ) {
        keySetString = (char *) DEFKEYSET_NAME;
    }

    char *sharedSecretKeyNameChars =  NULL;

    if( sharedSecretKeyName != NULL ) {
        sharedSecretKeyNameChars = (char *) (env)->GetStringUTFChars( sharedSecretKeyName, NULL);
    }

    char *sharedSecretKeyNameString = sharedSecretKeyNameChars;

    if ( sharedSecretKeyNameString == NULL ) {
        sharedSecretKeyNameString = (char *) TRANSPORT_KEY_NAME;
    }

    GetSharedSecretKeyName(sharedSecretKeyNameString);

    if( sequenceCounter != NULL) {
        sc = (jbyte*)(env)->GetByteArrayElements( sequenceCounter, NULL);
        sc_len =  (env)->GetArrayLength(sequenceCounter);
    } 

    if( sc == NULL || sc_len != 2) {
        goto done;
    } 

    if( derivationConstant != NULL) {
        dc = (jbyte*)(env)->GetByteArrayElements( derivationConstant, NULL);
        dc_len = (env)->GetArrayLength( derivationConstant);
    }
 
    if( dc == NULL || dc_len != 2) {
        goto done;
    }
 
    if( keyInfo != NULL) { 
      keyVersion = (jbyte*)(env)->GetByteArrayElements( keyInfo, NULL);

      if( keyVersion) {
          keyVersion_len =  (env)->GetArrayLength(keyInfo);
      }
    }

    if( !keyVersion || (keyVersion_len < 2) ){
        goto done;
    }

    if ( CUID != NULL ) {
        cuidValue =  (jbyte*)(env)->GetByteArrayElements( CUID, NULL);
    }

    if( cuidValue == NULL) {
        goto done;
    }

    if(tokenName)
    {
        tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
        slot = ReturnSlot(tokenNameChars);
        (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
    }

    if(keyName)
    {
        keyNameChars = (char *)(env)->GetStringUTFChars(keyName, NULL);
        strncpy(keyname,keyNameChars,KEYNAMELENGTH);
        (env)->ReleaseStringUTFChars(keyName, (const char *)keyNameChars);
    }else
        GetKeyName(keyVersion,keyname);

    //Get  key type from derivation constant
    switch((unsigned char) dc[1]) {
       case 0x1 :
           kType = mac;
           devKeyName = macName;
       break;

       case 0x82:
           kType = enc;
           devKeyName = encName;
       break;

       case 0x81:
           kType = kek;
           devKeyName = kekName;
       break;

       default:
          kType = mac;
          devKeyName = macName;
      break;
    }

    GetDiversificationData(cuidValue,devData,kType);

    PR_fprintf(PR_STDOUT,"In SessionKey.ComputeSessionKeySCP02! keyName %s keyVersion[0] %d keyVersion[1] %d \n",keyname,(int) keyVersion[0],(int) keyVersion[1]);

    if ( (keyVersion[0] == 0x1 && keyVersion[1]== 0x1 ) ||
        (keyVersion[0] == -1 && keyVersion[1] == 0x1))
     
    {
        /* default manufacturers key */

        devSymKey = ReturnDeveloperSymKey(slot, (char *) devKeyName , keySetString, devBuff);

        if( devSymKey == NULL ) {
            goto done;
        }

        PR_fprintf(PR_STDOUT,"SessionKey.ComputeSessionKeySCP02! sc[0] : %d sc[1] : %d \n", sc[0], sc[1]);
        symkey = DeriveKeySCP02(                       //Util::DeriveKey(
            devSymKey, Buffer((BYTE*)sc, sc_len), Buffer((BYTE*)dc, dc_len));

        if(symkey == NULL) 
        {
            goto done;
        }

        //In the enc key case create the auth as well, we may need it later.

        if(kType == enc) {

            PK11SymKey *authKey = NULL;

            authKey = ReturnDeveloperSymKey(slot, (char *) "auth" , keySetString, devBuff);
     
            if(authKey == NULL)
            {
               goto done;
            }

            PK11_FreeSymKey(authKey);
            authKey = NULL; 

        }

    }else
    {
        PR_fprintf(PR_STDOUT,"SessionKey.ComputeSessionKeySCP02! Attempting with master key. \n");
        masterKey = ReturnSymKey( slot,keyname);
        if(masterKey == NULL)
        {
            goto done;
        }

        devKey =ComputeCardKeyOnToken(masterKey,devData,2);
        if(devKey == NULL)
        {
            goto done;
        }
         
        symkey = DeriveKeySCP02(devKey, Buffer((BYTE*)sc, sc_len), Buffer((BYTE*)dc, dc_len));

        if(symkey == NULL)
        {
            goto done;
        }
    }
    //Now wrap the key for the trip back to TPS with shared secret transport key

    symkey16 = NULL;
     transportKey = ReturnSymKey( internal, GetSharedSecretKeyName(NULL));
    if ( transportKey == NULL ) {
        PR_fprintf(PR_STDERR, "Can't find shared secret transport key! \n");
        goto done;
    }

    handleBA = (env)->NewByteArray( KEYLENGTH);
    handleBytes = (env)->GetByteArrayElements(handleBA, NULL);

    paramsItem.data = (CK_BYTE *) &bitPosition;
    paramsItem.len = sizeof bitPosition;

    symkey16 = PK11_Derive(symkey, CKM_EXTRACT_KEY_FROM_KEY, &paramsItem, CKA_ENCRYPT,
                                                            CKA_DERIVE, 16);
    if ( !symkey16 ) {
        PR_fprintf(PR_STDERR,"Can't derive 16 byte key from 24 byte symkey! \n");
        goto done;
    }

    wrappedKeyItem.data = (unsigned char *) handleBytes;
    wrappedKeyItem.len  =  KEYLENGTH;
    wrapStatus = PK11_WrapSymKey(CKM_DES3_ECB,&noParams, transportKey, symkey16, &wrappedKeyItem);

    if(wrapStatus == SECFailure )
    {
        PR_fprintf(PR_STDERR, "Can't wrap session key! Error: %d \n", PR_GetError());
    }

done:

    if( slot) {
        PK11_FreeSlot(slot);
        slot = NULL;
    }

    if( internal ) {
        PK11_FreeSlot(internal);
        internal = NULL;
    }

    if ( symkey ) {
        PK11_FreeSymKey( symkey);
        symkey = NULL;
    }

    if ( transportKey )  {
        PK11_FreeSymKey( transportKey );
        transportKey = NULL;
    }

    if ( symkey16 ) {
        PK11_FreeSymKey( symkey16 );
        symkey16 = NULL;
    }

    if( masterKey ) {
        PK11_FreeSymKey( masterKey);
        masterKey = NULL;
    }
           
    if( devKey ) {
        PK11_FreeSymKey( devKey);
        devKey = NULL;
    }

    if( devSymKey ) {
        PK11_FreeSymKey( devSymKey );
        devSymKey = NULL;
    }

    if( keySetStringChars ) {
        (env)->ReleaseStringUTFChars(keySet, (const char *)keySetStringChars);
        keySetStringChars = NULL;
    }

    if( sharedSecretKeyNameChars ) {
        (env)->ReleaseStringUTFChars(sharedSecretKeyName, (const char *)sharedSecretKeyNameChars);
        sharedSecretKeyNameChars = NULL;
    }

    if ( handleBytes != NULL) {
        (env)->ReleaseByteArrayElements( handleBA, handleBytes, 0);
    }

    if ( sc != NULL) {
        (env)->ReleaseByteArrayElements(sequenceCounter, sc, JNI_ABORT);
    }

    if ( dc != NULL) {
        (env)->ReleaseByteArrayElements(derivationConstant, dc, JNI_ABORT);
    }

    if( keyVersion != NULL) {
        (env)->ReleaseByteArrayElements(keyInfo, keyVersion, JNI_ABORT);
    }

    if ( cuidValue != NULL) {
        (env)->ReleaseByteArrayElements(CUID, cuidValue, JNI_ABORT);
    }

    if( dev_key != NULL) {
        (env)->ReleaseByteArrayElements(devKeyArray, dev_key, JNI_ABORT);
    }

    if (wrapStatus != SECFailure ){
        return handleBA;
    }else{
        return NULL;
    }

}



//=================================================================================
#ifdef __cplusplus
extern "C"
{
#endif
/*
 * Class:     com_netscape_cms_servlet_tks_RASessionKey
 * Method:    ComputeSessionKey
 * Signature: ([B[B[B[B)[B
 */
// AC: KDF SPEC CHANGE: function signature change - added jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, and jbyteArray KDD
    JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeSessionKey
        (JNIEnv *, jclass, jstring, jstring, jbyteArray, jbyteArray, jbyteArray, jbyte, jboolean, jbyteArray, jbyteArray, jbyteArray, jstring, jstring, jstring);
#ifdef __cplusplus
}
#endif
#define KEYLENGTH 16
// AC: KDF SPEC CHANGE: function signature change - added jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, and jbyteArray KDD
extern "C" JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeSessionKey(JNIEnv * env, jclass this2, jstring tokenName, jstring keyName, jbyteArray card_challenge, jbyteArray host_challenge, jbyteArray keyInfo, jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, jbyteArray CUID, jbyteArray KDD, jbyteArray macKeyArray, jstring useSoftToken_s, jstring keySet, jstring sharedSecretKeyName)
{
    /* hardcore permanent mac key */
    jbyte *mac_key = NULL;
    if (macKeyArray != NULL) {
       mac_key = (jbyte*)(env)->GetByteArrayElements(macKeyArray, NULL);
    } else {
        return NULL;
    }

    unsigned char input[KEYLENGTH] = {0};
    int i = 0;

    SECItem wrappedKeyItem = { siBuffer, NULL , 0};
    SECItem noParams = { siBuffer, NULL, 0 };
    SECStatus wrapStatus = SECFailure;


    char *keyNameChars=NULL;
    char *tokenNameChars=NULL;
    PK11SlotInfo *slot = NULL;
    PK11SlotInfo *internal = PK11_GetInternalKeySlot();

    PK11SymKey *symkey = NULL;
    PK11SymKey *transportKey = NULL;
    PK11SymKey *masterKey = NULL;

    PK11SymKey *macSymKey = NULL;
    PK11SymKey *symkey16 = NULL;

    // AC: KDF SPEC CHANGE:  For the NIST SP800-108 KDF, we build all 3 keys despite only using one of them (Mac) in this function.
    //                       We do this because our NIST SP800-108 KDF outputs the data for all three keys simultaneously.
    // KDF output keys
    PK11SymKey* macKey = NULL;
    PK11SymKey* encKey = NULL;
    PK11SymKey* kekKey = NULL;

    BYTE macData[KEYLENGTH];
    char keyname[KEYNAMELENGTH];


    /* Derive vars */

    CK_ULONG bitPosition = 0;
    SECItem paramsItem = { siBuffer, NULL, 0 };

    /* Java object return vars */

    jbyteArray handleBA=NULL;
    jbyte *handleBytes=NULL;

    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    //                       Also added "len" variable for CUID (for sanity check).
    jbyte* cuidValue = NULL;
    jsize cuidValue_len = -1;
    jbyte* kddValue = NULL;
    jsize kddValue_len = -1;

    jbyte *cc = NULL;
    int cc_len = 0;

    int hc_len = 0;
    jbyte *hc = NULL;

    jbyte *    keyVersion = NULL;
    int keyVersion_len = 0;

    Buffer macBuff( ( BYTE *) mac_key , KEYLENGTH );

    char *keySetStringChars = NULL;
    if( keySet != NULL ) {
       keySetStringChars = (char *) (env)->GetStringUTFChars( keySet, NULL);
    }

    char *keySetString =  keySetStringChars;

    if ( keySetString == NULL ) {
        keySetString = (char *) DEFKEYSET_NAME;
    }

    char *sharedSecretKeyNameChars =  NULL;

    if( sharedSecretKeyName != NULL ) {
        sharedSecretKeyNameChars = (char *) (env)->GetStringUTFChars( sharedSecretKeyName, NULL);
    }

    char *sharedSecretKeyNameString = sharedSecretKeyNameChars;

    if ( sharedSecretKeyNameString == NULL ) {
        sharedSecretKeyNameString = (char *) TRANSPORT_KEY_NAME;
    }

    GetSharedSecretKeyName(sharedSecretKeyNameString);

    if( card_challenge != NULL) {
        cc = (jbyte*)(env)->GetByteArrayElements( card_challenge, NULL);
        cc_len =  (env)->GetArrayLength(card_challenge);
    } 

    if( cc == NULL) {
        goto done;
    } 

    if( host_challenge != NULL) {
        hc = (jbyte*)(env)->GetByteArrayElements( host_challenge, NULL);
        hc_len = (env)->GetArrayLength( host_challenge);
    }
 
    if( hc == NULL) {
        goto done;
    }
 
    if( keyInfo != NULL) { 
      keyVersion = (jbyte*)(env)->GetByteArrayElements( keyInfo, NULL);

      if( keyVersion) {
          keyVersion_len =  (env)->GetArrayLength(keyInfo);
      }
    }

    if( !keyVersion || (keyVersion_len < 2) ){
        goto done;
    }


    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    //                       Also added "len" variable for CUID (for sanity check).
    if ( CUID != NULL ) {
        cuidValue =  (jbyte*)(env)->GetByteArrayElements( CUID, NULL);
        cuidValue_len = env->GetArrayLength(CUID);
    }
    if( cuidValue == NULL) {
        goto done;
    }
    if ( cuidValue_len <= 0){  // check that CUID is at least 1 byte in length
        goto done;
    }
    if ( KDD != NULL ){
        kddValue = env->GetByteArrayElements(KDD, NULL);
        kddValue_len = env->GetArrayLength(KDD);
    }
    if ( kddValue == NULL ){
        goto done;
    }
    if ( kddValue_len != static_cast<jsize>(NistSP800_108KDF::KDD_SIZE_BYTES) ){   // check that KDD is expected size
        goto done;
    }


    /* copy card and host challenge into input buffer */
    for (i = 0; i < 8; i++)
    {
        input[i] = cc[i];
    }
    for (i = 0; i < 8; i++)
    {
        input[8+i] = hc[i];
    }

    // AC: KDF SPEC CHANGE: Moved this call down. (We don't necessarily need it anymore depending on the KDF we're going to use.)
    //GetDiversificationData(cuidValue,macData,mac);//keytype is mac

    if(tokenName)
    {
        tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
        slot = ReturnSlot(tokenNameChars);
        (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
    }

    if(keyName)
    {
        keyNameChars = (char *)(env)->GetStringUTFChars(keyName, NULL);
        strncpy(keyname,keyNameChars,KEYNAMELENGTH);
        (env)->ReleaseStringUTFChars(keyName, (const char *)keyNameChars);
    }else
    GetKeyName(keyVersion,keyname);

    PR_fprintf(PR_STDOUT,"In SessionKey.ComputeSessionKey! keyName %s keyVersion[0] %d keyVersion[1] %d \n",keyname,(int) keyVersion[0],(int) keyVersion[1]);

    if ( (keyVersion[0] == 0x1 && keyVersion[1]== 0x1 && strcmp( keyname, "#01#01") == 0) ||
        (keyVersion[0] == -1 && strstr(keyname, "#FF")))
     
    {
        /* default manufacturers key */

        macSymKey = ReturnDeveloperSymKey(slot, (char *) "mac" , keySetString, macBuff);

        if( macSymKey == NULL ) {
            goto done;
        }
 
        symkey = DeriveKey(                       //Util::DeriveKey(
            macSymKey, Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));

    }else
    {
        PR_fprintf(PR_STDOUT,"In SessionKey.ComputeSessionKey! Upgraded keyset mode. \n");
        masterKey = ReturnSymKey( slot,keyname);
        if(masterKey == NULL)
        {
            goto done;
        }

        // ---------------------------------
        // AC KDF SPEC CHANGE: Determine which KDF to use.
        //
        // Convert to unsigned types
        BYTE nistSP800_108KdfOnKeyVersion_byte = static_cast<BYTE>(nistSP800_108KdfOnKeyVersion);
        BYTE requestedKeyVersion_byte = static_cast<BYTE>(keyVersion[0]);
        // if requested key version meets setting value, use NIST SP800-108 KDF
        if (NistSP800_108KDF::useNistSP800_108KDF(nistSP800_108KdfOnKeyVersion_byte, requestedKeyVersion_byte) == true){

            PR_fprintf(PR_STDOUT,"ComputeSessionKey NistSP800_108KDF code: Using NIST SP800-108 KDF.\n");

            // react to "UseCUIDAsKDD" setting value
            jbyte* context_jbyte = NULL;
            jsize context_len_jsize = 0;
            if (nistSP800_108KdfUseCuidAsKdd == JNI_TRUE){
                context_jbyte = cuidValue;
                context_len_jsize = cuidValue_len;
            }else{
                context_jbyte = kddValue;
                context_len_jsize = kddValue_len;
            }

            // Converting this way is safe since jbyte is guaranteed to be 8 bits
            // Of course, this assumes that "char" is 8 bits (not guaranteed, but typical),
            //            but it looks like this assumption is also made in GetDiversificationData
            const BYTE* const context = reinterpret_cast<const BYTE*>(context_jbyte);

            // Convert jsize to size_t
            const size_t context_len = static_cast<size_t>(context_len_jsize);
            if (context_len > 0x000000FF){  // sanity check (CUID should never be larger than 255 bytes)
                PR_fprintf(PR_STDERR, "ComputeSessionKey NistSP800_108KDF code: Error; context_len larger than 255 bytes.\n");
                goto done;
            }

            // call NIST SP800-108 KDF routine
            try{
                NistSP800_108KDF::ComputeCardKeys(masterKey, context, context_len, &encKey, &macKey, &kekKey);
            }catch(std::runtime_error& ex){
                PR_fprintf(PR_STDERR, "ComputeSessionKey NistSP800_108KDF code: Exception invoking NistSP800_108KDF::ComputeCardKeys: ");
                PR_fprintf(PR_STDERR, "%s\n", ex.what() == NULL ? "null" : ex.what());
                goto done;
            }catch(...){
                PR_fprintf(PR_STDERR, "ComputeSessionKey NistSP800_108KDF code: Unknown exception invoking NistSP800_108KDF::ComputeCardKeys.\n");
                goto done;
            }

        // if not a key version where we use the NIST SP800-108 KDF, use the original KDF
        }else{

            PR_fprintf(PR_STDOUT,"ComputeSessionKey NistSP800_108KDF code: Using original KDF.\n");

            // AC: KDF SPEC CHANGE: Moved this call down from the original location.
            //                      (We don't always need to call it anymore; it depends on the KDF we're going to use.)
            //
            // Note the change from "cuidValue" to "kddValue".
            //   This change is necessary due to the semantics change in the parameters passed between TPS and TKS.
            GetDiversificationData(kddValue,macData,mac);//keytype is mac

            // AC: Derives the mac key for the token.
            macKey =ComputeCardKeyOnToken(masterKey,macData,1);

        } // endif use original KDF
        // ---------------------------------


        // AC: This computes the GP session key using the card-specific MAC key we previously derived.
        symkey = DeriveKey(macKey, Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));

    }

    // AC: Moved this check out of the else block so we catch NULL keys in the developer key case
    //     (The call already exists outside the "else" block for ComputeEncSessionKey and ComputeKekKey.)
    if(symkey == NULL)
    {
        goto done;
    }

    //Now wrap the key for the trip back to TPS with shared secret transport key
    symkey16 = NULL;
     transportKey = ReturnSymKey( internal, GetSharedSecretKeyName(NULL));
    if ( transportKey == NULL ) {
        PR_fprintf(PR_STDERR, "Can't find shared secret transport key! \n");
        goto done;
    }

    handleBA = (env)->NewByteArray( KEYLENGTH);
    handleBytes = (env)->GetByteArrayElements(handleBA, NULL);

    paramsItem.data = (CK_BYTE *) &bitPosition;
    paramsItem.len = sizeof bitPosition;

    symkey16 = PK11_Derive(symkey, CKM_EXTRACT_KEY_FROM_KEY, &paramsItem, CKA_ENCRYPT,
                                                            CKA_DERIVE, 16);
    if ( !symkey16 ) {
        PR_fprintf(PR_STDERR,"Can't derive 16 byte key from 24 byte symkey! \n");
        goto done;
    }

    wrappedKeyItem.data = (unsigned char *) handleBytes;
    wrappedKeyItem.len  =  KEYLENGTH;
    wrapStatus = PK11_WrapSymKey(CKM_DES3_ECB,&noParams, transportKey, symkey16, &wrappedKeyItem);

    if(wrapStatus == SECFailure )
    {
        PR_fprintf(PR_STDERR, "Can't wrap session key! Error: %d \n", PR_GetError());
    }

done:

    if( slot) {
        PK11_FreeSlot(slot);
        slot = NULL;
    }

    if( internal ) {
        PK11_FreeSlot(internal);
        internal = NULL;
    }

    if ( symkey ) {
        PK11_FreeSymKey( symkey);
        symkey = NULL;
    }

    if ( transportKey )  {
        PK11_FreeSymKey( transportKey );
        transportKey = NULL;
    }

    if ( symkey16 ) {
        PK11_FreeSymKey( symkey16 );
        symkey16 = NULL;
    }

    if( masterKey ) {
        PK11_FreeSymKey( masterKey);
        masterKey = NULL;
    }
           
    // AC: KDF SPEC CHANGE:  For the NIST SP800-108 KDF, we build all 3 keys despite only using one of them (Mac) in this function.
    //                       We do this because our NIST SP800-108 KDF outputs the data for all three keys simultaneously.
    if( macKey ) {
        PK11_FreeSymKey( macKey);
        macKey = NULL;
    }
    if ( encKey ) {
        PK11_FreeSymKey(encKey);
        encKey = NULL;
    }
    if ( kekKey ) {
        PK11_FreeSymKey(kekKey);
        kekKey = NULL;
    }

    if( macSymKey ) {
        PK11_FreeSymKey( macSymKey );
        macSymKey = NULL;
    }

    if( keySetStringChars ) {
        (env)->ReleaseStringUTFChars(keySet, (const char *)keySetStringChars);
        keySetStringChars = NULL;
    }

    if( sharedSecretKeyNameChars ) {
        (env)->ReleaseStringUTFChars(sharedSecretKeyName, (const char *)sharedSecretKeyNameChars);
        sharedSecretKeyNameChars = NULL;
    }

    // AC BUGFIX:  Check the value of handleBytes (not handleBA) before freeing handleBytes!
    //if ( handleBA != NULL) {
    if ( handleBytes != NULL) {
        (env)->ReleaseByteArrayElements( handleBA, handleBytes, 0);
    }

    if ( cc != NULL) {
        (env)->ReleaseByteArrayElements(card_challenge, cc, JNI_ABORT);
    }

    if ( hc != NULL) {
        (env)->ReleaseByteArrayElements(host_challenge, hc, JNI_ABORT);
    }

    if( keyVersion != NULL) {
        (env)->ReleaseByteArrayElements(keyInfo, keyVersion, JNI_ABORT);
    }

    if ( cuidValue != NULL) {
        (env)->ReleaseByteArrayElements(CUID, cuidValue, JNI_ABORT);
    }

    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    if ( kddValue != NULL){
        env->ReleaseByteArrayElements(KDD, kddValue, JNI_ABORT);
        kddValue = NULL;
    }

    if( mac_key != NULL) {
        (env)->ReleaseByteArrayElements(macKeyArray, mac_key, JNI_ABORT);
    }

    // AC: BUGFIX: Don't return a java array with uninitialized or zero'd data.
    if (wrapStatus != SECFailure ){
        return handleBA;
    }else{
        return NULL;
    }
}


#ifdef __cplusplus
extern "C"
{
#endif
/*
 * Class:     com_netscape_cms_servlet_tks_RASessionKey
 * Method:    ComputeEncSessionKey
 * Signature: ([B[B[B[B)[B
 */
// AC: KDF SPEC CHANGE: function signature change - added jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, and jbyteArray KDD
    JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeEncSessionKey
        (JNIEnv *, jclass, jstring, jstring, jbyteArray, jbyteArray, jbyteArray, jbyte, jboolean, jbyteArray, jbyteArray, jbyteArray, jstring, jstring);
#ifdef __cplusplus
}
#endif
#define KEYLENGTH 16
// AC: KDF SPEC CHANGE: function signature change - added jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, and jbyteArray KDD
extern "C" JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeEncSessionKey(JNIEnv * env, jclass this2, jstring tokenName, jstring keyName, jbyteArray card_challenge, jbyteArray host_challenge, jbyteArray keyInfo, jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, jbyteArray CUID, jbyteArray KDD, jbyteArray encKeyArray, jstring useSoftToken_s, jstring keySet)
{
    /* hardcoded permanent enc key */
    jbyte *enc_key = NULL;
    if(encKeyArray != NULL ) {
       enc_key  =  (jbyte*)(env)->GetByteArrayElements(encKeyArray, NULL);
    } else {
        return NULL;
    }

    unsigned char input[KEYLENGTH] = {0};
    int i = 0;

    SECItem wrappedKeyItem = { siBuffer, NULL , 0};
    SECItem noParams = { siBuffer, NULL, 0 };
    SECStatus wrapStatus = SECFailure;

    char *keyNameChars = NULL;
    char *tokenNameChars = NULL;
    PK11SlotInfo *slot = NULL;
    PK11SlotInfo *internal = PK11_GetInternalKeySlot();

    PK11SymKey *symkey = NULL;
    PK11SymKey * transportKey = NULL;
    PK11SymKey *masterKey  = NULL;

    PK11SymKey *encSymKey  = NULL;
    PK11SymKey *symkey16   = NULL;

    // AC: KDF SPEC CHANGE:  For the NIST SP800-108 KDF, we build all 3 keys despite only using one of them (Enc) in this function.
    //                       We do this because our NIST SP800-108 KDF outputs the data for all three keys simultaneously.
    // KDF output keys
    PK11SymKey* macKey = NULL;
    PK11SymKey* encKey = NULL;
    PK11SymKey* kekKey = NULL;

    BYTE encData[KEYLENGTH];
    char keyname[KEYNAMELENGTH];

     /* Derive vars */
    CK_ULONG bitPosition = 0;
    SECItem paramsItem = { siBuffer, NULL, 0 };

    /* Java object return vars */

    jbyteArray handleBA=NULL;
    jbyte *handleBytes=NULL;

    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    //                       Also added "len" variable for CUID (for sanity check).
    jbyte* cuidValue = NULL;
    jsize cuidValue_len = -1;
    jbyte* kddValue = NULL;
    jsize kddValue_len = -1;

    jbyte *cc = NULL;
    int cc_len = 0;

    int hc_len = 0;
    jbyte *hc = NULL;

    jbyte *    keyVersion = NULL;
    int keyVersion_len = 0;

    Buffer encBuff( ( BYTE *) enc_key , KEYLENGTH );

    char *keySetStringChars = NULL; 

    if( keySet != NULL ) {
       keySetStringChars = (char *) (env)->GetStringUTFChars( keySet, NULL);
    }

    char *keySetString =  keySetStringChars;

    if ( keySetString == NULL ) {
        keySetString = (char *) DEFKEYSET_NAME;
    }

    if( card_challenge != NULL) {
        cc = (jbyte*)(env)->GetByteArrayElements( card_challenge, NULL);
        cc_len =  (env)->GetArrayLength(card_challenge);
    }

    if( cc == NULL) {
        goto done;
    }

    if( host_challenge != NULL) {
        hc = (jbyte*)(env)->GetByteArrayElements( host_challenge, NULL);
        hc_len = (env)->GetArrayLength( host_challenge);
    }

    if( hc == NULL) {
        goto done;
    }

    if( keyInfo != NULL) {
        keyVersion = (jbyte*)(env)->GetByteArrayElements( keyInfo, NULL);

        if( keyVersion) {
            keyVersion_len = (env)->GetArrayLength(keyInfo);
        }
    }

    if( !keyVersion || (keyVersion_len < 2) ){
        goto done;
    }


    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    //                       Also added "len" variable for CUID (for sanity check).
    if ( CUID != NULL ) {
        cuidValue =  (jbyte*)(env)->GetByteArrayElements( CUID, NULL);
        cuidValue_len = env->GetArrayLength(CUID);
    }
    if( cuidValue == NULL) {
        goto done;
    }
    if ( cuidValue_len <= 0){  // check that CUID is at least 1 byte in length
        goto done;
    }
    if ( KDD != NULL ){
        kddValue = env->GetByteArrayElements(KDD, NULL);
        kddValue_len = env->GetArrayLength(KDD);
    }
    if ( kddValue == NULL ){
        goto done;
    }
    if ( kddValue_len != static_cast<jsize>(NistSP800_108KDF::KDD_SIZE_BYTES) ){   // check that KDD is expected size
        goto done;
    }


    /* copy card and host challenge into input buffer */
    for (i = 0; i < 8; i++)
    {
        input[i] = cc[i];
    }
    for (i = 0; i < 8; i++)
    {
        input[8+i] = hc[i];
    }

    // AC: KDF SPEC CHANGE: Moved this call down. (We don't necessarily need it anymore depending on the KDF we're going to use.)
    //GetDiversificationData(cuidValue,encData,enc);

    if(tokenName)
    {
        tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
        slot = ReturnSlot(tokenNameChars);
        (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
    }

    if(keyName)
    {
        keyNameChars = (char *)(env)->GetStringUTFChars(keyName, NULL);
        strncpy(keyname,keyNameChars,KEYNAMELENGTH);
        (env)->ReleaseStringUTFChars(keyName, (const char *)keyNameChars);
    }
    else {
        GetKeyName(keyVersion,keyname);
    }

    if ( (keyVersion[0] == 0x1 && keyVersion[1]== 0x1 &&strcmp( keyname, "#01#01") == 0) ||
        (keyVersion[0] == -1 && strstr(keyname, "#FF")))
    {
        /* default manufacturers key */

        encSymKey = ReturnDeveloperSymKey(slot, (char *) "auth" , keySetString, encBuff);

        if( encSymKey == NULL ) {
            goto done;
        }

        symkey = DeriveKey(                       //Util::DeriveKey(
                encSymKey, Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));

    }else
    {
        masterKey = ReturnSymKey( slot,keyname);

        if(masterKey == NULL) {
            goto done;
        }

        // ---------------------------------
        // AC KDF SPEC CHANGE: Determine which KDF to use.
        //
        // Convert to unsigned types
        BYTE nistSP800_108KdfOnKeyVersion_byte = static_cast<BYTE>(nistSP800_108KdfOnKeyVersion);
        BYTE requestedKeyVersion_byte = static_cast<BYTE>(keyVersion[0]);
        // if requested key version meets setting value, use NIST SP800-108 KDF
        if (NistSP800_108KDF::useNistSP800_108KDF(nistSP800_108KdfOnKeyVersion_byte, requestedKeyVersion_byte) == true){

            PR_fprintf(PR_STDOUT,"ComputeEncSessionKey NistSP800_108KDF code: Using NIST SP800-108 KDF.\n");

            // react to "UseCUIDAsKDD" setting value
            jbyte* context_jbyte = NULL;
            jsize context_len_jsize = 0;
            if (nistSP800_108KdfUseCuidAsKdd == JNI_TRUE){
                context_jbyte = cuidValue;
                context_len_jsize = cuidValue_len;
            }else{
                context_jbyte = kddValue;
                context_len_jsize = kddValue_len;
            }

            // Converting this way is safe since jbyte is guaranteed to be 8 bits
            // Of course, this assumes that "char" is 8 bits (not guaranteed, but typical),
            //            but it looks like this assumption is also made in GetDiversificationData
            const BYTE* const context = reinterpret_cast<const BYTE*>(context_jbyte);

            // Convert jsize to size_t
            const size_t context_len = static_cast<size_t>(context_len_jsize);
            if (context_len > 0x000000FF){  // sanity check (CUID should never be larger than 255 bytes)
                PR_fprintf(PR_STDERR, "ComputeEncSessionKey NistSP800_108KDF code: Error; context_len larger than 255 bytes.\n");
                goto done;
            }

            // call NIST SP800-108 KDF routine
            try{
                NistSP800_108KDF::ComputeCardKeys(masterKey, context, context_len, &encKey, &macKey, &kekKey);
            }catch(std::runtime_error& ex){
                PR_fprintf(PR_STDERR, "ComputeEncSessionKey NistSP800_108KDF code: Exception invoking NistSP800_108KDF::ComputeCardKeys: ");
                PR_fprintf(PR_STDERR, "%s\n", ex.what() == NULL ? "null" : ex.what());
                goto done;
            }catch(...){
                PR_fprintf(PR_STDERR, "ComputeEncSessionKey NistSP800_108KDF code: Unknown exception invoking NistSP800_108KDF::ComputeCardKeys.\n");
                goto done;
            }

        // if not a key version where we use the NIST SP800-108 KDF, use the original KDF
        }else{

            PR_fprintf(PR_STDOUT,"ComputeEncSessionKey NistSP800_108KDF code: Using original KDF.\n");

            // AC: KDF SPEC CHANGE: Moved this call down from the original location.
            //                      (We don't always need to call it anymore; it depends on the KDF we're going to use.)
            //
            // Note the change from "cuidValue" to "kddValue".
            //   This change is necessary due to the semantics change in the parameters passed between TPS and TKS.
            GetDiversificationData(kddValue,encData,enc);

            // AC: Derives the enc key for the token.
            encKey =ComputeCardKeyOnToken(masterKey,encData,1);

        } // endif use original KDF
        // ---------------------------------

        if(encKey == NULL) {
            goto done;
        }

        // AC: This computes the GP session key using the card-specific ENC key we previously derived.
        symkey = DeriveKey(encKey, Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));
    }

    if(symkey == NULL) {
        goto done;
    }

    //Now wrap the key for the trip back to TPS with shared secret transport key
    transportKey = ReturnSymKey( internal, GetSharedSecretKeyName(NULL));
    if ( transportKey == NULL ) {
        goto done;
    }

    handleBA = (env)->NewByteArray( KEYLENGTH);
    handleBytes = (env)->GetByteArrayElements(handleBA, NULL);

    paramsItem.data = (CK_BYTE *) &bitPosition;
    paramsItem.len = sizeof bitPosition;

    symkey16 = PK11_Derive(symkey, CKM_EXTRACT_KEY_FROM_KEY, &paramsItem, CKA_ENCRYPT,
                                                            CKA_DERIVE, KEYLENGTH);

    if ( !symkey16 ) {
        PR_fprintf(PR_STDERR,"SessionKey: ComputeEncSessionKey - Can't derive 16 byte key from 24 byte symkey! \n");
        goto done;
    }

    wrappedKeyItem.data = (unsigned char *) handleBytes;
    wrappedKeyItem.len  =   KEYLENGTH;
    wrapStatus = PK11_WrapSymKey(CKM_DES3_ECB,&noParams, transportKey, symkey16, &wrappedKeyItem);

    if ( wrapStatus == SECFailure ) {
        PR_fprintf(PR_STDERR,"SessionKey: ComputeEncSessionKey - Can't wrap encSessionKey !  Error: %d \n", PR_GetError());
    }

done:

    if ( slot )  {
       PK11_FreeSlot ( slot );
       slot = NULL;
    }

    if ( internal) {
       PK11_FreeSlot( internal);
       internal = NULL;
    }

    if( symkey) {
        PK11_FreeSymKey( symkey);
        symkey = NULL;
    }

    if( transportKey) {
        PK11_FreeSymKey( transportKey );
        transportKey = NULL;
    }

    if( masterKey) {
        PK11_FreeSymKey( masterKey);
        masterKey = NULL;
    }

    if( symkey16) {
        PK11_FreeSymKey( symkey16);
        symkey16 = NULL;
    }

    if ( encSymKey ) { 
        PK11_FreeSymKey( encSymKey);
        encSymKey = NULL;
    }
   
    // AC: KDF SPEC CHANGE:  For the NIST SP800-108 KDF, we build all 3 keys despite only using one of them (Enc) in this function.
    //                       We do this because our NIST SP800-108 KDF outputs the data for all three keys simultaneously.
    if( macKey ) {
        PK11_FreeSymKey(macKey);
        macKey = NULL;
    }
    if ( encKey) {
        PK11_FreeSymKey( encKey);
        encKey = NULL;
    }
    if ( kekKey ) {
        PK11_FreeSymKey(kekKey);
        kekKey = NULL;
    }

    if( keySetStringChars ) {
        (env)->ReleaseStringUTFChars(keySet, (const char *)keySetStringChars);
        keySetStringChars = NULL;
    }

    if ( handleBytes != NULL ) {
        (env)->ReleaseByteArrayElements( handleBA, handleBytes, 0);
    }

    if( cc != NULL ) {
        (env)->ReleaseByteArrayElements(card_challenge, cc, JNI_ABORT);
    }

    if( hc != NULL ) {
        (env)->ReleaseByteArrayElements(host_challenge, hc, JNI_ABORT);
    }
    if(keyVersion != NULL ) {
        (env)->ReleaseByteArrayElements(keyInfo, keyVersion, JNI_ABORT);
    }

    if(cuidValue != NULL) {
        (env)->ReleaseByteArrayElements(CUID, cuidValue, JNI_ABORT);
    }

    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    if ( kddValue != NULL){
        env->ReleaseByteArrayElements(KDD, kddValue, JNI_ABORT);
        kddValue = NULL;
    }

    if( enc_key != NULL) {
        (env)->ReleaseByteArrayElements(encKeyArray, enc_key, JNI_ABORT);
    }

    // AC: BUGFIX: Don't return a java array with uninitialized or zero'd data.
    if (wrapStatus != SECFailure ){
        return handleBA;
    }else{
        return NULL;
    }
}

#ifdef __cplusplus
extern "C"
{
#endif
/*
 * Class:     com_netscape_cms_servlet_tks_RASessionKey
 * Method:    ComputeKekKey
 * Signature: ([B[B[B[B)[B
 */
// AC: KDF SPEC CHANGE: function signature change - added jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, and jbyteArray KDD
    JNIEXPORT jobject JNICALL Java_com_netscape_symkey_SessionKey_ComputeKekKey
        (JNIEnv *, jclass, jstring, jstring, jbyteArray, jbyteArray, jbyteArray, jbyte, jboolean, jbyteArray, jbyteArray, jbyteArray, jstring, jstring);
#ifdef __cplusplus
}
#endif
#define KEYLENGTH 16

// AC: KDF SPEC CHANGE: function signature change - added jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, and jbyteArray KDD
extern "C" JNIEXPORT jobject JNICALL Java_com_netscape_symkey_SessionKey_ComputeKekKey(JNIEnv * env, jclass this2, jstring tokenName, jstring keyName, jbyteArray card_challenge, jbyteArray host_challenge, jbyteArray keyInfo, jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, jbyteArray CUID, jbyteArray KDD, jbyteArray kekKeyArray, jstring useSoftToken_s, jstring keySet)
{
    /* hardcoded permanent kek key */
    jbyte *kek_key = NULL;
    if( kekKeyArray != NULL) {
        kek_key = (jbyte*)(env)->GetByteArrayElements(kekKeyArray, NULL);
    } else {
        return NULL;
    }

    Buffer kekBuff( ( BYTE *) kek_key , KEYLENGTH );

    char *keySetStringChars = NULL; 
    if( keySet != NULL ) {
       keySetStringChars = (char *) (env)->GetStringUTFChars( keySet, NULL);
    }

    char *keySetString = keySetStringChars;

    if ( keySetString == NULL ) {
        keySetString = (char *) DEFKEYSET_NAME;
    }

    unsigned char input[KEYLENGTH] = {0};
    int i;
    jobject keyObj = NULL;

    jbyte *cc =  NULL;
    jbyte *hc = NULL;
    jbyte *    keyVersion = NULL;
    int keyVersion_len = 0;

    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    //                       Also added "len" variable for CUID (for sanity check).
    jbyte* cuidValue = NULL;
    jsize cuidValue_len = -1;
    jbyte* kddValue = NULL;
    jsize kddValue_len = -1;

    char *keyNameChars=NULL;
    char *tokenNameChars = NULL;
    PK11SlotInfo *slot = NULL;

    // AC: KDF SPEC CHANGE:  For the NIST SP800-108 KDF, we build all 3 keys despite only using one of them (KEK) in this function.
    //                       We do this because our NIST SP800-108 KDF outputs the data for all three keys simultaneously.
    // KDF output keys
    PK11SymKey* macKey = NULL;
    PK11SymKey* encKey = NULL;
    PK11SymKey* kekKey = NULL;

    PK11SymKey *masterKey = NULL;

    BYTE kekData[KEYLENGTH];
    char keyname[KEYNAMELENGTH];

    if( card_challenge != NULL) {
        cc = (jbyte*)(env)->GetByteArrayElements( card_challenge, NULL);
    }

    if( cc == NULL) {
        goto done;
    }

    if( host_challenge != NULL) {
        hc = (jbyte*)(env)->GetByteArrayElements( host_challenge, NULL);
    }

    if( hc == NULL) {
        goto done;
    }

    if( keyInfo != NULL) {
        keyVersion = (jbyte*)(env)->GetByteArrayElements( keyInfo, NULL);
        if( keyVersion) {
          keyVersion_len =  (env)->GetArrayLength(keyInfo);
      }
    }

    if( !keyVersion || (keyVersion_len < 2) ){
        goto done;
    }


    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    //                       Also added "len" variable for CUID (for sanity check).
    if ( CUID != NULL ) {
        cuidValue =  (jbyte*)(env)->GetByteArrayElements( CUID, NULL);
        cuidValue_len = env->GetArrayLength(CUID);
    }
    if( cuidValue == NULL) {
        goto done;
    }
    if ( cuidValue_len <= 0){  // check that CUID is at least 1 byte in length
        goto done;
    }
    if ( KDD != NULL ){
        kddValue = env->GetByteArrayElements(KDD, NULL);
        kddValue_len = env->GetArrayLength(KDD);
    }
    if ( kddValue == NULL ){
        goto done;
    }
    if ( kddValue_len != static_cast<jsize>(NistSP800_108KDF::KDD_SIZE_BYTES) ){   // check that KDD is expected size
        goto done;
    }


    /* copy card and host challenge into input buffer */
    for (i = 0; i < 8; i++)
    {
        input[i] = cc[i];
    }
    for (i = 0; i < 8; i++)
    {
        input[8+i] = hc[i];
    }

    // AC: KDF SPEC CHANGE: Moved this call down. (We don't necessarily need it anymore depending on the KDF we're going to use.)
    //GetDiversificationData(cuidValue,kekData,kek);//keytype is kek

    if (tokenName)
    {
        tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
        slot = ReturnSlot(tokenNameChars);
        (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
    }

    if (keyName)
    {
        keyNameChars = (char *)(env)->GetStringUTFChars(keyName, NULL);
        strcpy(keyname,keyNameChars);
        (env)->ReleaseStringUTFChars(keyName, (const char *)keyNameChars);
    }else
    GetKeyName(keyVersion,keyname);

    PR_fprintf(PR_STDOUT,"In SessionKey.ComputeKekKey! \n");

    if (( keyVersion[0] == 0x1 && keyVersion[1]== 0x1 &&strcmp( keyname, "#01#01") == 0 ) ||
        (keyVersion[0] == -1 && strcmp(keyname, "#FF")))
    {
        /* default manufacturers key */

         kekKey = ReturnDeveloperSymKey(slot, (char *) "kek" , keySetString, kekBuff);

    } else {
        masterKey = ReturnSymKey( slot,keyname);

        if(masterKey == NULL)
        {
            goto done;
        }

        // ---------------------------------
        // AC KDF SPEC CHANGE: Determine which KDF to use.
        //
        // Convert to unsigned types
        BYTE nistSP800_108KdfOnKeyVersion_byte = static_cast<BYTE>(nistSP800_108KdfOnKeyVersion);
        BYTE requestedKeyVersion_byte = static_cast<BYTE>(keyVersion[0]);
        // if requested key version meets setting value, use NIST SP800-108 KDF
        if (NistSP800_108KDF::useNistSP800_108KDF(nistSP800_108KdfOnKeyVersion_byte, requestedKeyVersion_byte) == true){

            PR_fprintf(PR_STDOUT,"ComputeKekKey NistSP800_108KDF code: Using NIST SP800-108 KDF.\n");

            // react to "UseCUIDAsKDD" setting value
            jbyte* context_jbyte = NULL;
            jsize context_len_jsize = 0;
            if (nistSP800_108KdfUseCuidAsKdd == JNI_TRUE){
                context_jbyte = cuidValue;
                context_len_jsize = cuidValue_len;
            }else{
                context_jbyte = kddValue;
                context_len_jsize = kddValue_len;
            }

            // Converting this way is safe since jbyte is guaranteed to be 8 bits
            // Of course, this assumes that "char" is 8 bits (not guaranteed, but typical),
            //            but it looks like this assumption is also made in GetDiversificationData
            const BYTE* const context = reinterpret_cast<const BYTE*>(context_jbyte);

            // Convert jsize to size_t
            const size_t context_len = static_cast<size_t>(context_len_jsize);
            if (context_len > 0x000000FF){  // sanity check (CUID should never be larger than 255 bytes)
                PR_fprintf(PR_STDERR, "ComputeKekKey NistSP800_108KDF code: Error; context_len larger than 255 bytes.\n");
                goto done;
            }

            // call NIST SP800-108 KDF routine
            try{
                NistSP800_108KDF::ComputeCardKeys(masterKey, context, context_len, &encKey, &macKey, &kekKey);
            }catch(std::runtime_error& ex){
                PR_fprintf(PR_STDERR, "ComputeKekKey NistSP800_108KDF code: Exception invoking NistSP800_108KDF::ComputeCardKeys: ");
                PR_fprintf(PR_STDERR, "%s\n", ex.what() == NULL ? "null" : ex.what());
                goto done;
            }catch(...){
                PR_fprintf(PR_STDERR, "ComputeKekKey NistSP800_108KDF code: Unknown exception invoking NistSP800_108KDF::ComputeCardKeys.\n");
                goto done;
            }

        // if not a key version where we use the NIST SP800-108 KDF, use the original KDF
        }else{

            PR_fprintf(PR_STDOUT,"ComputeKekKey NistSP800_108KDF code: Using original KDF.\n");

            // AC: KDF SPEC CHANGE: Moved this call down from the original location.
            //                      (We don't always need to call it anymore; it depends on the KDF we're going to use.)
            //
            // Note the change from "cuidValue" to "kddValue".
            //   This change is necessary due to the semantics change in the parameters passed between TPS and TKS.
            GetDiversificationData(kddValue,kekData,kek);//keytype is kek

            // AC: Derives the mac key for the token.
            kekKey =ComputeCardKeyOnToken(masterKey,kekData,1);

        } // endif use original KDF
        // ---------------------------------

    }

    if(kekKey == NULL) {
        goto done;
    }

    keyObj = JSS_PK11_wrapSymKey(env, &kekKey, NULL);

done:

    if( keySetStringChars ) {
        (env)->ReleaseStringUTFChars(keySet, (const char *)keySetStringChars);
        keySetStringChars = NULL;
    }

    if(masterKey) {
        PK11_FreeSymKey( masterKey);
        masterKey = NULL;
    }

    // AC: KDF SPEC CHANGE:  For the NIST SP800-108 KDF, we build all 3 keys despite only using one of them (Kek) in this function.
    //                       We do this because our NIST SP800-108 KDF outputs the data for all three keys simultaneously.
    if( macKey ) {
        PK11_FreeSymKey(macKey);
        macKey = NULL;
    }
    if ( encKey ) {
        PK11_FreeSymKey(encKey);
        encKey = NULL;
    }
    if(kekKey) {
        PK11_FreeSymKey( kekKey);
        kekKey = NULL;
    }

    if(slot) {
        PK11_FreeSlot(slot);
        slot = NULL;
    }

    if (cc != NULL) {
        (env)->ReleaseByteArrayElements(card_challenge, cc, JNI_ABORT);
    }

    if (hc != NULL) {
        (env)->ReleaseByteArrayElements(host_challenge, hc, JNI_ABORT);
    }

    if( keyVersion != NULL ) {
        (env)->ReleaseByteArrayElements(keyInfo, keyVersion, JNI_ABORT);
    }

    if (cuidValue != NULL ) {
        (env)->ReleaseByteArrayElements(CUID, cuidValue, JNI_ABORT);
    }

    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    if ( kddValue != NULL){
        env->ReleaseByteArrayElements(KDD, kddValue, JNI_ABORT);
        kddValue = NULL;
    }

    return keyObj;
}

PRStatus ComputeMAC(PK11SymKey *key, Buffer &x_input,
const Buffer &icv, Buffer &output)
{
    PRStatus rv = PR_SUCCESS;
    PK11Context *context = NULL;
//    NetkeyICV temp;
    unsigned char result[8];
    int i;
    SECStatus s;
    int len;
#ifdef USE_DESMAC
    CK_ULONG macLen = sizeof result;
    SECItem params = { siBuffer, (unsigned char *)&macLen, sizeof macLen };
#endif
    static SECItem noParams = { siBuffer, NULL, 0 };
    static unsigned char macPad[] =
    {
        0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    };
    BYTE *input = (BYTE *) x_input;
    int inputLen = x_input.size();

    if(key == NULL)
    {
        rv = PR_FAILURE; goto done;
    }

#ifdef USE_DESMAC
    context = PK11_CreateContextBySymKey(CKM_DES3_MAC_GENERAL, CKA_SIGN,
        key, &params);
    if (!context) { rv = PR_FAILURE; goto done; }

    s = PK11_DigestBegin(context);
    if (s != SECSuccess) { rv = PR_FAILURE; goto done; }

    s = PK11_DigestOp(context, icv, 8);
    if (s != SECSuccess) { rv = PR_FAILURE; goto done; }

    while(inputLen >= 8)
    {
        s = PK11_DigestOp(context, input, 8);
        if (s != SECSuccess) { rv = PR_FAILURE; goto done; }

        input += 8;
        inputLen -= 8;
    }

    for (i = 0;i < inputLen;i++)
    {
        result[i] = input[i];
    }

    input = macPad;
    for(;i < 8;i++)
    {
        result[i] = *input++;
    }

    s = PK11_DigestOp(context, result, sizeof result);
    if (s != SECSuccess) { rv = PR_FAILURE; goto done; }

    s = PK11_DigestFinal(context, output, (unsigned int *)&len, sizeof output);
    if (1 != SECSuccess) { rv = PR_FAILURE; goto done; }

#else

    context = PK11_CreateContextBySymKey(CKM_DES3_ECB, CKA_ENCRYPT, key, &noParams);
    if (!context) { rv = PR_FAILURE; goto done; }

    memcpy(result, icv, sizeof result);

    /* Process whole blocks */
    while (inputLen >= 8)
    {
        for(i = 0;i < 8;i++)
        {
            result[i] ^= input[i];
        }

        s = PK11_CipherOp(context, result, &len, sizeof result, result, sizeof result);
        if (s != SECSuccess) { rv = PR_FAILURE; goto done; }
        if (len != sizeof result)                 /* assert? */
        {
//PR_SetError(PR_UNKNOWN_ERROR, 0);
            rv = PR_FAILURE;
            goto done;
        }

        input += 8;
        inputLen -= 8;
    }

/*
 * Fold in remaining data (if any)
 * Set i to number of bytes processed
 */
    for(i = 0;i < inputLen;i++)
    {
        result[i] ^= input[i];
    }

    /*
     * Fill remainder of last block. There
     * will be at least one byte handled here.
     */
    input = macPad;
    while(i < 8)
    {
        result[i] ^= *input++;
        i++;
    }

    s = PK11_CipherOp(context, result, &len, sizeof result, result, sizeof result);
    if (s != SECSuccess) { rv = PR_FAILURE; goto done; }
    if (len != sizeof result)
    {
//PR_SetError(PR_UNKNOWN_ERROR, 0);
        rv = PR_FAILURE;
        goto done;
    }

    output.replace(0, result, sizeof result);
#endif

    done:
    if (context)
    {
        PK11_Finalize(context);
        PK11_DestroyContext(context, PR_TRUE);
    }
    memset(result, 0, sizeof result);

    return rv;
}                                                 /* ComputeMAC */


//=================================================================================
#ifdef __cplusplus
extern "C"
{
#endif
/*
 * Class:     com_netscape_cms_servlet_tks_RASessionKey
 * Method:    ComputeCryptogram
 * Signature: ([B[B[B[B)[B
 */
// AC: KDF SPEC CHANGE: function signature change - added jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, and jbyteArray KDD
    JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeCryptogram
        (JNIEnv *, jclass, jstring, jstring, jbyteArray, jbyteArray, jbyteArray, jbyte, jboolean, jbyteArray, jbyteArray, int, jbyteArray, jstring, jstring);
#ifdef __cplusplus
}
#endif
#define KEYLENGTH 16
// AC: KDF SPEC CHANGE: function signature change - added jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, and jbyteArray KDD
extern "C" JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeCryptogram(JNIEnv * env, jclass this2, jstring tokenName, jstring keyName, jbyteArray card_challenge, jbyteArray host_challenge, jbyteArray keyInfo, jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, jbyteArray CUID, jbyteArray KDD, int type, jbyteArray authKeyArray, jstring useSoftToken_s, jstring keySet)
{
/* hardcore permanent mac key */
    jbyte *auth_key = NULL;
    if( authKeyArray != NULL) {
        auth_key = (jbyte*)(env)->GetByteArrayElements(authKeyArray, NULL);
    } else {
        return NULL;
    }

    Buffer authBuff( ( BYTE *) auth_key , KEYLENGTH );
    Buffer icv = Buffer(EIGHT_BYTES, (BYTE)0);
    Buffer output = Buffer(EIGHT_BYTES, (BYTE)0);

    char *keySetStringChars = NULL; 
    if( keySet != NULL ) {
       keySetStringChars = (char *) (env)->GetStringUTFChars( keySet, NULL);
    }

    char *keySetString = keySetStringChars;

    if ( keySetString == NULL ) {
        keySetString = (char *) DEFKEYSET_NAME;
    }

    char input[KEYLENGTH];
    int i;

    PR_fprintf(PR_STDOUT,"In SessionKey: ComputeCryptogram! \n");
    jbyteArray handleBA=NULL;
    jbyte *handleBytes=NULL;

    jbyte *cc = NULL;
    jbyte *hc = NULL;
    int cc_len = 0;
    int hc_len = 0;
    jbyte *    keyVersion = NULL;
    int keyVersion_len = 0;

    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    //                       Also added "len" variable for CUID (for sanity check).
    jbyte* cuidValue = NULL;
    jsize cuidValue_len = -1;
    jbyte* kddValue = NULL;
    jsize kddValue_len = -1;

    char *tokenNameChars = NULL;
    char *keyNameChars=NULL;
    PK11SlotInfo *slot = NULL;

    jbyte * session_key = NULL;
    PK11SymKey *symkey     = NULL;
    PK11SymKey *masterKey  = NULL;
    PK11SymKey *authSymKey = NULL;

    // AC: KDF SPEC CHANGE:  For the NIST SP800-108 KDF, we build all 3 keys despite only using one of them (Enc/Auth) in this function.
    //                       We do this because our NIST SP800-108 KDF outputs the data for all three keys simultaneously.
    // KDF output keys
    PK11SymKey* macKey = NULL;
    PK11SymKey* authKey = NULL;
    PK11SymKey* kekKey = NULL;

    BYTE authData[KEYLENGTH];
    char keyname[KEYNAMELENGTH];
    Buffer input_x = Buffer(KEYLENGTH);

    // AC: BUGFIX: Don't return a java array with uninitialized or zero'd data.
    bool error_computing_result = true;

    if( card_challenge != NULL ) {
        cc = (jbyte*)(env)->GetByteArrayElements( card_challenge, NULL);
        cc_len =  (env)->GetArrayLength(card_challenge);
    }

    if( cc == NULL) {
        goto done;
    }

    if( host_challenge != NULL ) {
        hc = (jbyte*)(env)->GetByteArrayElements( host_challenge, NULL);
        hc_len = (env)->GetArrayLength( host_challenge);
    }

    if( hc == NULL) {
        goto done;
    }

    if( keyInfo != NULL) {
        keyVersion = (jbyte*)(env)->GetByteArrayElements( keyInfo, NULL);
        if( keyVersion) {
          keyVersion_len =  (env)->GetArrayLength(keyInfo);
      }
    }

    if( !keyVersion || (keyVersion_len < 2) ){
        goto done;
    }


    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    //                       Also added "len" variable for CUID (for sanity check).
    if ( CUID != NULL ) {
        cuidValue =  (jbyte*)(env)->GetByteArrayElements( CUID, NULL);
        cuidValue_len = env->GetArrayLength(CUID);
    }
    if( cuidValue == NULL) {
        goto done;
    }
    if ( cuidValue_len <= 0){  // check that CUID is at least 1 byte in length
        goto done;
    }
    if ( KDD != NULL ){
        kddValue = env->GetByteArrayElements(KDD, NULL);
        kddValue_len = env->GetArrayLength(KDD);
    }
    if ( kddValue == NULL ){
        goto done;
    }
    if ( kddValue_len != static_cast<jsize>(NistSP800_108KDF::KDD_SIZE_BYTES) ){   // check that KDD is expected size
        goto done;
    }


    if (type == 0)                                // compute host cryptogram
    {
        /* copy card and host challenge into input buffer */
        for (i = 0; i < EIGHT_BYTES; i++)
        {
            input[i] = cc[i];
        }
        for (i = 0; i < EIGHT_BYTES; i++)
        {
            input[EIGHT_BYTES +i] = hc[i];
        }
    }                                             // compute card cryptogram
    else if (type == 1)
    {
        for (i = 0; i < EIGHT_BYTES; i++)
        {
            input[i] = hc[i];
        }
        for (i = 0; i < EIGHT_BYTES; i++)
        {
            input[EIGHT_BYTES+i] = cc[i];
        }
    }

    input_x.replace(0, (BYTE*) input, KEYLENGTH); 

    // AC: KDF SPEC CHANGE: Moved this call down. (We don't necessarily need it anymore depending on the KDF we're going to use.)
    //GetDiversificationData(cuidValue,authData,enc);

    if (tokenName)
    {
        tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
        slot = ReturnSlot(tokenNameChars);
        (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
    }

    if (keyName)
    {
        keyNameChars = (char *)(env)->GetStringUTFChars(keyName, NULL);
        strcpy(keyname,keyNameChars);
        (env)->ReleaseStringUTFChars(keyName, (const char *)keyNameChars);
    }else
    GetKeyName(keyVersion,keyname);

    if ( (keyVersion[0] == 0x1 && keyVersion[1]== 0x1 &&strcmp( keyname, "#01#01") == 0 ) ||
        (keyVersion[0] == -1 && strstr(keyname, "#FF")))
    {

        /* default manufacturers key */

        authSymKey = ReturnDeveloperSymKey(slot, (char *) "auth" , keySetString, authBuff);
        if( authSymKey == NULL ) {
            goto done;
        }

        symkey = DeriveKey(                      
            authSymKey, Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));
    }
    else
    {
        masterKey = ReturnSymKey( slot,keyname);
        if (masterKey == NULL)
        {
            goto done;
        }

        // ---------------------------------
        // AC KDF SPEC CHANGE: Determine which KDF to use.
        //
        // Convert to unsigned types
        BYTE nistSP800_108KdfOnKeyVersion_byte = static_cast<BYTE>(nistSP800_108KdfOnKeyVersion);
        BYTE requestedKeyVersion_byte = static_cast<BYTE>(keyVersion[0]);
        // if requested key version meets setting value, use NIST SP800-108 KDF
        if (NistSP800_108KDF::useNistSP800_108KDF(nistSP800_108KdfOnKeyVersion_byte, requestedKeyVersion_byte) == true){

            PR_fprintf(PR_STDOUT,"ComputeCryptogram NistSP800_108KDF code: Using NIST SP800-108 KDF.\n");

            // react to "UseCUIDAsKDD" setting value
            jbyte* context_jbyte = NULL;
            jsize context_len_jsize = 0;
            if (nistSP800_108KdfUseCuidAsKdd == JNI_TRUE){
                context_jbyte = cuidValue;
                context_len_jsize = cuidValue_len;
            }else{
                context_jbyte = kddValue;
                context_len_jsize = kddValue_len;
            }

            // Converting this way is safe since jbyte is guaranteed to be 8 bits
            // Of course, this assumes that "char" is 8 bits (not guaranteed, but typical),
            //            but it looks like this assumption is also made in GetDiversificationData
            const BYTE* const context = reinterpret_cast<const BYTE*>(context_jbyte);

            // Convert jsize to size_t
            const size_t context_len = static_cast<size_t>(context_len_jsize);
            if (context_len > 0x000000FF){  // sanity check (CUID should never be larger than 255 bytes)
                PR_fprintf(PR_STDERR, "ComputeCryptogram NistSP800_108KDF code: Error; context_len larger than 255 bytes.\n");
                goto done;
            }

            // call NIST SP800-108 KDF routine
            try{
                NistSP800_108KDF::ComputeCardKeys(masterKey, context, context_len, &authKey, &macKey, &kekKey);
            }catch(std::runtime_error& ex){
                PR_fprintf(PR_STDERR, "ComputeCryptogram NistSP800_108KDF code: Exception invoking NistSP800_108KDF::ComputeCardKeys: ");
                PR_fprintf(PR_STDERR, "%s\n", ex.what() == NULL ? "null" : ex.what());
                goto done;
            }catch(...){
                PR_fprintf(PR_STDERR, "ComputeCryptogram NistSP800_108KDF code: Unknown exception invoking NistSP800_108KDF::ComputeCardKeys.\n");
                goto done;
            }

        // if not a key version where we use the NIST SP800-108 KDF, use the original KDF
        }else{

            PR_fprintf(PR_STDOUT,"ComputeCryptogram NistSP800_108KDF code: Using original KDF.\n");

            // AC: KDF SPEC CHANGE: Moved this call down from the original location.
            //                      (We don't always need to call it anymore; it depends on the KDF we're going to use.)
            //
            // Note the change from "cuidValue" to "kddValue".
            //   This change is necessary due to the semantics change in the parameters passed between TPS and TKS.
            GetDiversificationData(kddValue,authData,enc);

            // AC: Derives the mac key for the token.
            authKey = ComputeCardKeyOnToken(masterKey,authData,1);

        } // endif use original KDF
        // ---------------------------------

        if (authKey == NULL)
        {
            goto done;
        }

        // AC: This computes the GP session key using the card-specific ENC key we previously derived.
        symkey = DeriveKey(authKey,
            Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));

    }

    ComputeMAC(symkey, input_x, icv, output);
    session_key = (jbyte *) (BYTE*)output;

    handleBA = (env)->NewByteArray( EIGHT_BYTES);
    handleBytes = (env)->GetByteArrayElements(handleBA, NULL);
    if( handleBytes ) {
        memcpy(handleBytes, session_key, EIGHT_BYTES);

        // AC: BUGFIX: Don't return a java array with uninitialized or zero'd data.
        // Set flag that we've successfully copied.
        error_computing_result = false;
    }

done:

    if( slot ) {
        PK11_FreeSlot( slot );
        slot = NULL;
    }

    if( symkey ) {
        PK11_FreeSymKey( symkey );
        symkey = NULL;
    }

    if( authSymKey ) {
        PK11_FreeSymKey( authSymKey );
        authSymKey = NULL;
    }
 
    // AC: KDF SPEC CHANGE:  For the NIST SP800-108 KDF, we build all 3 keys despite only using one of them (Enc/Auth) in this function.
    //                       We do this because our NIST SP800-108 KDF outputs the data for all three keys simultaneously.
    if( macKey ) {
        PK11_FreeSymKey(macKey);
        macKey = NULL;
    }
    if( authKey) {
        PK11_FreeSymKey( authKey);
        authKey = NULL;
    }
    if ( kekKey ) {
        PK11_FreeSymKey(kekKey);
        kekKey = NULL;
    }

    if( masterKey) {
        PK11_FreeSymKey( masterKey);
        masterKey = NULL;
    }

    if( keySetStringChars ) {
        (env)->ReleaseStringUTFChars(keySet, (const char *)keySetStringChars);
        keySetStringChars = NULL;
    }

    if( handleBytes != NULL) {
        (env)->ReleaseByteArrayElements( handleBA, handleBytes, 0);
    }

    if( cc != NULL) {
        (env)->ReleaseByteArrayElements(card_challenge, cc, JNI_ABORT);
    }

    if( hc != NULL) {
        (env)->ReleaseByteArrayElements(host_challenge, hc, JNI_ABORT);
    }

    if( keyVersion != NULL) {
        (env)->ReleaseByteArrayElements(keyInfo, keyVersion, JNI_ABORT);
    }

    if( cuidValue != NULL) {
        (env)->ReleaseByteArrayElements(CUID, cuidValue, JNI_ABORT);
    }

    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    if ( kddValue != NULL){
        env->ReleaseByteArrayElements(KDD, kddValue, JNI_ABORT);
        kddValue = NULL;
    }

    // AC: BUGFIX: Don't return a java array with uninitialized or zero'd data.
    if (error_computing_result == false){
        return handleBA;
    }else{
        return NULL;
    }
}


//=================================================================================

#ifdef __cplusplus
extern "C"
{
#endif
/*
 * Class:     com_netscape_cms_servlet_tks_ECBencrypt
 * Method:    ECBencrypt
 * Signature: ([B[B[B[B)[B
 */
    JNIEXPORT jbyteArray JNICALL
        Java_com_netscape_symkey_SessionKey_ECBencrypt
        (JNIEnv*, jclass, jobject, jobject);
#ifdef __cplusplus
}
#endif
extern "C" JNIEXPORT jbyteArray JNICALL
Java_com_netscape_symkey_SessionKey_ECBencrypt
(JNIEnv* env, jclass this2, jobject symkeyObj, jobject deskeyObj )
{
    jbyteArray handleBA=NULL;
    jint dlen=KEYLENGTH; // applet only supports 16 bytes
    jbyte *handleBytes=NULL;

    PK11SymKey *symkey = NULL;
    PK11SymKey *deskey = NULL;
    PK11SymKey *newdeskey = NULL;
    PRStatus r = PR_FAILURE;
    static SECItem noParams = { siBuffer, NULL, 0 };
    SECItem wrappedKeyItem   = { siBuffer, NULL, 0 };
    SECStatus wrapStatus = SECFailure;

    /* PK11_Derive vars. */

    SECItem paramsItem = { siBuffer, NULL, 0 };
    CK_ULONG bitPosition = 0;

    PR_fprintf(PR_STDOUT,"In SessionKey: ECBencrypt! \n");

    if( !symkeyObj || !deskeyObj) {
       goto finish;
    }

    r = JSS_PK11_getSymKeyPtr(env, symkeyObj, &symkey);
    if (r != PR_SUCCESS) {
        goto finish;
    }

    r = JSS_PK11_getSymKeyPtr(env, deskeyObj, &deskey);
    if (r != PR_SUCCESS) {
        goto finish;
    }
    // Instead of playing with raw keys, let's derive the 16 byte des2 key from 
    // the 24 byte des2 key.

    bitPosition = 0;
    paramsItem.data = (CK_BYTE *) &bitPosition;
    paramsItem.len = sizeof bitPosition;

    newdeskey = PK11_Derive(deskey, CKM_EXTRACT_KEY_FROM_KEY, &paramsItem, CKA_ENCRYPT,
                                                            CKA_DERIVE, 16);

    if ( ! newdeskey ) {
        goto finish;
    }

    dlen = KEYLENGTH;                                // applet suports only 16 bytes

    handleBA = (env)->NewByteArray(dlen);
    if(handleBA == NULL )
    {
        goto finish;
    }
    handleBytes = (jbyte *)(env)->GetByteArrayElements(handleBA, NULL);

    if(handleBytes==NULL)
    {
        goto finish;
    }

    PR_fprintf(PR_STDOUT,"In SessionKey: ECBencrypt! 16 byte key derived....  \n");

    //Wrap the new 16 bit key with the input symkey.

    wrappedKeyItem.data = (unsigned char *) handleBytes;
    wrappedKeyItem.len  = dlen;

    PR_fprintf(PR_STDOUT,"In SessionKey: ECBencrypt! About to wrap des key with sym key.\n");
    wrapStatus = PK11_WrapSymKey(CKM_DES3_ECB,&noParams, symkey, newdeskey, &wrappedKeyItem);

    if( wrapStatus == SECSuccess) {
       PR_fprintf(PR_STDERR, "ECBencrypt wrapStatus %d wrappedKeySize %d \n", wrapStatus, wrappedKeyItem.len); 

       PR_fprintf(PR_STDOUT," ECBencrypt wrapped data: \n");
         Buffer wrappedDataBuf(wrappedKeyItem.data,wrappedKeyItem.len);
         wrappedDataBuf.dump();


    } else {
       PR_fprintf(PR_STDERR, "ECBecrypt wrap failed! Error %d \n", PR_GetError());
    }

finish:

    if( handleBytes != NULL) {
        (env)->ReleaseByteArrayElements( handleBA, handleBytes, 0);
    }

    if ( newdeskey ) {
         PK11_FreeSymKey( newdeskey );
         newdeskey = NULL;
    }

    return handleBA;
}

#ifdef __cplusplus
extern "C"
{
#endif
/*
 * Class:     com_netscape_cms_servlet_tks_DeriveDESKeyFrom3DesKey
 * Method:    DeriveDESKeyFrom3DesKey 
 * Signature: ([B[B[B[B)[B
 */
    JNIEXPORT jobject JNICALL
        Java_com_netscape_symkey_SessionKey_DeriveDESKeyFrom3DesKey
        (JNIEnv*, jclass,jstring ,jobject,jlong);
#ifdef __cplusplus
}
#endif
extern "C" JNIEXPORT jobject JNICALL 
Java_com_netscape_symkey_SessionKey_DeriveDESKeyFrom3DesKey
(JNIEnv* env, jclass this2, jstring tokenName, jobject des3Key,jlong alg)
{
    PK11SymKey * des3 = NULL;
    PK11SymKey * des  = NULL;
    PK11SymKey * desFinal = NULL;
    PRStatus  r = PR_FAILURE;
    CK_ULONG bitPosition = 0;
    SECItem paramsItem = { siBuffer, NULL, 0 };
    jobject keyObj = NULL;
    char *tokenNameChars = NULL;
    PK11SlotInfo *slot = NULL;

    if( des3Key == NULL) {
        goto loser;
    }

    if(alg != CKM_DES_CBC && alg != CKM_DES_ECB) {
        PR_fprintf(PR_STDOUT,"SessionKey.DeriveDESKeyFrom3DesKey invalid alg!.. \n");
        goto loser;
    }

    if (tokenName)
    {
        tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
        if ( tokenNameChars && !strcmp(tokenNameChars, "internal")) {
            slot = PK11_GetInternalSlot();
        } else {
            slot = ReturnSlot(tokenNameChars);
        }

        (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
    } else {
        slot = PK11_GetInternalKeySlot();
    }

    if(slot == NULL) {
        goto loser;
    }

    r = JSS_PK11_getSymKeyPtr(env, des3Key, &des3);

    if (r != PR_SUCCESS) {
        PR_fprintf(PR_STDOUT,"SessionKey: DeriveDESKeyFrom3DesKey Unable to get input session 3des sym key! \n");
        goto loser;
    }

    /* Now create a DES key with the first 8 bytes of the input 3des key */

    // Extract first eight bytes from generated key into another key.
     bitPosition = 0;
     paramsItem.data = (CK_BYTE *) &bitPosition;
     paramsItem.len = sizeof bitPosition;


     des = PK11_Derive(des3, CKM_EXTRACT_KEY_FROM_KEY, &paramsItem,  alg , CKA_DERIVE, 8);
     if (des  == NULL ) {
         goto loser;
     }

     //Make sure we move this to the orig token, in case it got moved by NSS
     //during the derive phase.

     desFinal =  PK11_MoveSymKey ( slot, CKA_ENCRYPT, 0, PR_FALSE, des);


         /* wrap the sesssion in java object. */
     keyObj = JSS_PK11_wrapSymKey(env, &desFinal, NULL);

loser:

    if ( slot != NULL ) {
       PK11_FreeSlot( slot);
       slot = NULL;
    }

    if ( des != NULL) {
        PK11_FreeSymKey(des);
        des = NULL;
    }
    return keyObj;
}

#ifdef __cplusplus
extern "C"
{
#endif
/*
 * Class:     com_netscape_cms_servlet_tks_UnwrapSessionKeyWithSharedSecret
 * Method:    UnwrapSessionKeyWithSharedSecret 
 * Signature: ([B[B[B[B)[B
 */
    JNIEXPORT jobject JNICALL
        Java_com_netscape_symkey_SessionKey_
        (JNIEnv*, jclass, jstring, jobject,jbyteArray);
#ifdef __cplusplus
}
#endif
extern "C" JNIEXPORT jobject JNICALL
Java_com_netscape_symkey_SessionKey_UnwrapSessionKeyWithSharedSecret
(JNIEnv* env, jclass this2, jstring tokenName, jobject sharedSecretKey,jbyteArray sessionKeyBA)
{
    jobject keyObj = NULL;
    PK11SymKey *sessionKey = NULL;
    PK11SymKey *sharedSecret = NULL;
    PK11SymKey *finalKey = NULL;
    PK11SlotInfo *slot = NULL;
    char *tokenNameChars = NULL;
    PRStatus  r = PR_FAILURE;
    int sessionKeyLen = 0;
    jbyte *sessionKeyBytes = NULL;
    SECItem *SecParam = PK11_ParamFromIV(CKM_DES3_ECB, NULL);
    SECItem wrappedItem = {siBuffer , NULL, 0 };

    PR_fprintf(PR_STDOUT,"In SessionKey.UnwrapSessionKeyWithSharedSecret!\n");

    if( sharedSecretKey == NULL || sessionKeyBA == NULL) {
        goto loser;
    }

    if (tokenName)
    {
        tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
        if ( tokenNameChars && !strcmp(tokenNameChars, "internal")) {
            slot = PK11_GetInternalSlot();
        } else {
            slot = ReturnSlot(tokenNameChars);
        }

        PR_fprintf(PR_STDOUT,"SessionKey.UnwrapSessionKeyWithSharedSecret  slot %p  name %s tokenName %s  \n",slot, PK11_GetSlotName(slot), PK11_GetTokenName(slot));
        (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
    } else {
        slot = PK11_GetInternalKeySlot();
    }

    if(slot == NULL) {
        goto loser;
    }

    sessionKeyBytes = (jbyte *)(env)->GetByteArrayElements(sessionKeyBA, NULL);
    sessionKeyLen = (env)->GetArrayLength(sessionKeyBA); 

    if(sessionKeyBytes == NULL) {
        goto loser;
    }

    r = JSS_PK11_getSymKeyPtr(env, sharedSecretKey, &sharedSecret);

    if (r != PR_SUCCESS) {
        PR_fprintf(PR_STDOUT,"SessionKey: UnwrapSessionKeyWithSharedSecret Unable to get input shared secret sym key! \n"); 
        goto loser;
    }

    wrappedItem.data = (unsigned char *) sessionKeyBytes;
    wrappedItem.len =  sessionKeyLen;


    sessionKey = PK11_UnwrapSymKey(sharedSecret,
                          CKM_DES3_ECB,SecParam, &wrappedItem,
                          CKM_DES3_ECB,
                          CKA_UNWRAP,
                          16);

    PR_fprintf(PR_STDOUT,"SessionKey: UnwrapSessionKeyWithSharedSecret symKey: %p \n",sessionKey);

    if(sessionKey == NULL) {
         PR_fprintf(PR_STDOUT,"SessionKey:UnwrapSessionKeyWithSharedSecret  Error unwrapping a session key! \n");
         goto loser;
    }

    // Done to be compat with current system. Current TPS does this.
    finalKey = CreateDesKey24Byte(slot, sessionKey);

    if(finalKey == NULL) {
          PR_fprintf(PR_STDOUT,"SessionKey:UnwrapSessionKeyWithSharedSecret Error final unwrapped key! \n");
          goto loser;

    }

     /* wrap the sesssion in java object. */
    keyObj = JSS_PK11_wrapSymKey(env, &finalKey, NULL);

loser:

    if ( slot != NULL ) {
       PK11_FreeSlot( slot);
       slot = NULL;
    }

    if ( sessionKeyBA != NULL) {
        (env)->ReleaseByteArrayElements( sessionKeyBA, sessionKeyBytes, 0);
    }

    if(sessionKey) {
        PK11_FreeSymKey(sessionKey);
        sessionKey = NULL; 
    }

    if (SecParam) {
        SECITEM_FreeItem(SecParam, PR_TRUE);
        SecParam = NULL;
    }


    // Don't free finalKey ptr because wrapping routine takes that out of our hands.

    return keyObj;
}

#ifdef __cplusplus
extern "C"
{
#endif
/*
 * Class:     com_netscape_cms_servlet_tks_GetSymKeyByName
 * Method:    GetSymKeyByName
 * Signature: ([B[B[B[B)[B
 */
    JNIEXPORT jobject JNICALL
        Java_com_netscape_symkey_SessionKey_GetSymKeyByName
        (JNIEnv*, jclass, jstring, jstring);
#ifdef __cplusplus
}
#endif
extern "C" JNIEXPORT jobject JNICALL
Java_com_netscape_symkey_SessionKey_GetSymKeyByName
(JNIEnv* env, jclass this2, jstring tokenName, jstring keyName)
{

    jobject keyObj = NULL;
    PK11SymKey *key = NULL;
    char *tokenNameChars = NULL;
    char *keyNameChars = NULL;
    PK11SlotInfo *slot = NULL;

    PR_fprintf(PR_STDOUT,"In SessionKey GetSymKeyByName!\n");

    if (keyName) {
        keyNameChars = (char *)(env)->GetStringUTFChars(keyName,NULL);
    }

    if (tokenName)
    {
        tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
        if ( tokenNameChars && !strcmp(tokenNameChars, "internal")) {
            slot = PK11_GetInternalSlot();
        } else {
            slot = ReturnSlot(tokenNameChars);
        }

        PR_fprintf(PR_STDOUT,"SessionKey: GetSymKeyByName slot %p  name %s tokenName %s keyName %s \n",slot, PK11_GetSlotName(slot), PK11_GetTokenName(slot),keyNameChars);
        (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
    } else {
        slot = PK11_GetInternalKeySlot();
    }

    if(slot == NULL)
        goto finish;

    key = ReturnSymKey( slot, keyNameChars);

    PR_fprintf(PR_STDOUT,"SessionKey: GetSymKeyByName returned key %p \n",key);
    if (key == NULL) {
        goto finish;
    }

    /* wrap the symkey in java object. */
    keyObj = JSS_PK11_wrapSymKey(env, &key, NULL);

finish:

    if (keyName) {
        (env)->ReleaseStringUTFChars(keyName, (const char *)keyNameChars);
    }

    if(slot) {
        PK11_FreeSlot(slot);
        slot = NULL;
    }

    return keyObj;
}

#ifdef __cplusplus
extern "C"
{
#endif
/*
 * Class:     com_netscape_cms_servlet_tks_GenerateSymkey
 * Method:    GenerateSymkey
 * Signature: ([B[B[B[B)[B
 */
    JNIEXPORT jobject JNICALL
        Java_com_netscape_symkey_SessionKey_GenerateSymkey
        (JNIEnv*, jclass, jstring);
#ifdef __cplusplus
}
#endif
extern "C" JNIEXPORT jobject JNICALL
Java_com_netscape_symkey_SessionKey_GenerateSymkey
(JNIEnv* env, jclass this2, jstring tokenName)
{
    jobject keyObj = NULL;
    PK11SymKey *okey = NULL;
    PK11SymKey *okeyFirstEight = NULL;
    PK11SymKey *concatKey = NULL;
    PK11SymKey *finalKey = NULL;

    char *tokenNameChars = NULL;
    PK11SlotInfo *slot = NULL;
    CK_ULONG bitPosition = 0;
    SECItem paramsItem = { siBuffer, NULL, 0 };
    CK_OBJECT_HANDLE keyhandle = 0;

    PR_fprintf(PR_STDOUT,"In SessionKey GenerateSymkey!\n");
    if (tokenName)
    {
        tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
        if ( tokenNameChars && !strcmp(tokenNameChars, "internal")) {
            slot = PK11_GetInternalSlot();
        } else {
            slot = ReturnSlot(tokenNameChars);
        }

        PR_fprintf(PR_STDOUT,"SessinKey: GenerateSymkey slot %p  name %s tokenName %s \n",slot, PK11_GetSlotName(slot), PK11_GetTokenName(slot));
        (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
    }

    //Generate original 16 byte DES2  key
    okey = PK11_TokenKeyGen(slot, CKM_DES2_KEY_GEN,0, 0, 0, PR_FALSE, NULL);

    if (okey == NULL) {
        goto finish;
    }

     // Extract first eight bytes from generated key into another key.
     bitPosition = 0;
     paramsItem.data = (CK_BYTE *) &bitPosition;
     paramsItem.len = sizeof bitPosition;

     okeyFirstEight = PK11_Derive(okey, CKM_EXTRACT_KEY_FROM_KEY, &paramsItem, CKA_ENCRYPT , CKA_DERIVE, 8);
     if (okeyFirstEight  == NULL ) {
         goto finish;
     }

     //Concatenate 8 byte key to the end of the original key, giving new 24 byte key
     keyhandle = PK11_GetSymKeyHandle(okeyFirstEight);
     paramsItem.data=(unsigned char *) &keyhandle;
     paramsItem.len=sizeof(keyhandle);

     concatKey = PK11_Derive ( okey , CKM_CONCATENATE_BASE_AND_KEY , &paramsItem ,CKM_DES3_ECB , CKA_DERIVE , 0);
     if ( concatKey == NULL ) {
         goto finish;
     }

     //Make sure we move this to the orig token, in case it got moved by NSS
     //during the derive phase.

     finalKey =  PK11_MoveSymKey ( slot, CKA_ENCRYPT, 0, PR_FALSE, concatKey);

    /* wrap the symkey in java object. This sets symkey to NULL. */
    keyObj = JSS_PK11_wrapSymKey(env, &finalKey, NULL);

finish:
    if ( slot != NULL) {
        PK11_FreeSlot(slot);
        slot = NULL;
    }

    if ( okey != NULL) {
        PK11_FreeSymKey(okey);
        okey = NULL;
    }

    if ( okeyFirstEight != NULL)  {
        PK11_FreeSymKey(okeyFirstEight);
        okeyFirstEight = NULL;
    }

    if ( concatKey != NULL) {
        PK11_FreeSymKey(concatKey);
        concatKey = NULL;
    }

    if ( finalKey != NULL) {
        PK11_FreeSymKey(finalKey);
        finalKey = NULL;
    }

    return keyObj;
}

// begin DRM proto

#ifdef __cplusplus
extern "C"
{
#endif
/*
 * Class:     com_netscape_cms_servlet_tks_RASessionKey
 * Method:    bytes2PK11SymKey
 * Signature:
 */
    JNIEXPORT jobject JNICALL Java_com_netscape_symkey_SessionKey_bytes2PK11SymKey
        (JNIEnv *, jclass, jbyteArray);
#ifdef __cplusplus
}
#endif

#ifdef DRM_SUPPORT_DEBUG
extern "C" JNIEXPORT jobject JNICALL Java_com_netscape_symkey_SessionKey_bytes2PK11SymKey(JNIEnv * env, jclass this2, jbyteArray symKeyBytes)
{
    PK11SlotInfo *slot=NULL;
    jobject keyObj = NULL;
    PK11SymKey *symKey=NULL;

// how about do unwrap (decrypt of the symkey in here??

// DRM proto just use internal slot
    slot = PK11_GetInternalKeySlot();

    BYTE masterKeyData[24];
    SECItem masterKeyItem = {siBuffer, masterKeyData, sizeof(masterKeyData)};

    memcpy(masterKeyData, (char*)symKeyBytes, 16);
    memcpy(masterKeyData+16, (char*)symKeyBytes, 8);

    // ToDo: possibly get rid of whole function, not used
    // For now , no need to get rid of PK11_ImportSymKeyWithFlags call.

    symKey = PK11_ImportSymKeyWithFlags(slot, CKM_DES3_ECB,
        PK11_OriginUnwrap, CKA_ENCRYPT, &masterKeyItem,
        ALL_SYMKEY_OPS    /*CKF_ENCRYPT*/, PR_FALSE, 0);

    /* wrap the symkey in java object. This sets symkey to NULL. */
    keyObj = JSS_PK11_wrapSymKey(env, &symKey, debug_fd);

finish:
    return keyObj;
}


// end DRM proto
#endif                                            // DRM_SUPPORT_DEBUG