summaryrefslogtreecommitdiff
path: root/security/nss/lib/cryptohi/seckey.c
blob: d1b3f6a050c0e174a53cc4c6c57e55d492a5d18c (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
/*
 * The contents of this file are subject to the Mozilla Public
 * License Version 1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 * 
 * The Original Code is the Netscape security libraries.
 * 
 * The Initial Developer of the Original Code is Netscape
 * Communications Corporation.  Portions created by Netscape are 
 * Copyright (C) 1994-2000 Netscape Communications Corporation.  All
 * Rights Reserved.
 * 
 * Portions created by Sun Microsystems, Inc. are Copyright (C) 2003
 * Sun Microsystems, Inc. All Rights Reserved. 
 *
 * Contributor(s): 
 *	Dr Stephen Henson <stephen.henson@gemplus.com>
 *	Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL"), in which case the provisions of the GPL are applicable 
 * instead of those above.  If you wish to allow use of your 
 * version of this file only under the terms of the GPL and not to
 * allow others to use your version of this file under the MPL,
 * indicate your decision by deleting the provisions above and
 * replace them with the notice and other provisions required by
 * the GPL.  If you do not delete the provisions above, a recipient
 * may use your version of this file under either the MPL or the
 * GPL.
 */
#include "cryptohi.h"
#include "keyhi.h"
#include "secoid.h"
#include "secitem.h"
#include "secder.h"
#include "base64.h"
#include "secasn1.h"
#include "cert.h"
#include "pk11func.h"
#include "secerr.h"
#include "secdig.h"
#include "prtime.h"
#include "ec.h"

const SEC_ASN1Template CERT_SubjectPublicKeyInfoTemplate[] = {
    { SEC_ASN1_SEQUENCE,
	  0, NULL, sizeof(CERTSubjectPublicKeyInfo) },
    { SEC_ASN1_INLINE,
	  offsetof(CERTSubjectPublicKeyInfo,algorithm),
	  SECOID_AlgorithmIDTemplate },
    { SEC_ASN1_BIT_STRING,
	  offsetof(CERTSubjectPublicKeyInfo,subjectPublicKey), },
    { 0, }
};

const SEC_ASN1Template CERT_PublicKeyAndChallengeTemplate[] =
{
    { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTPublicKeyAndChallenge) },
    { SEC_ASN1_ANY, offsetof(CERTPublicKeyAndChallenge,spki) },
    { SEC_ASN1_IA5_STRING, offsetof(CERTPublicKeyAndChallenge,challenge) },
    { 0 }
};

const SEC_ASN1Template SECKEY_RSAPublicKeyTemplate[] = {
    { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECKEYPublicKey) },
    { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey,u.rsa.modulus), },
    { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey,u.rsa.publicExponent), },
    { 0, }
};

const SEC_ASN1Template SECKEY_DSAPublicKeyTemplate[] = {
    { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey,u.dsa.publicValue), },
    { 0, }
};

const SEC_ASN1Template SECKEY_PQGParamsTemplate[] = {
    { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECKEYPQGParams) },
    { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams,prime) },
    { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams,subPrime) },
    { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams,base) },
    { 0, }
};

const SEC_ASN1Template SECKEY_DHPublicKeyTemplate[] = {
    { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey,u.dh.publicValue), },
    { 0, }
};

const SEC_ASN1Template SECKEY_DHParamKeyTemplate[] = {
    { SEC_ASN1_SEQUENCE,  0, NULL, sizeof(SECKEYPublicKey) },
    { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey,u.dh.prime), },
    { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey,u.dh.base), },
    /* XXX chrisk: this needs to be expanded for decoding of j and validationParms (RFC2459 7.3.2) */
    { SEC_ASN1_SKIP_REST },
    { 0, }
};

const SEC_ASN1Template SECKEY_FortezzaParameterTemplate[] = {
    { SEC_ASN1_SEQUENCE,  0, NULL, sizeof(SECKEYPQGParams) },
    { SEC_ASN1_OCTET_STRING, offsetof(SECKEYPQGParams,prime), },
    { SEC_ASN1_OCTET_STRING, offsetof(SECKEYPQGParams,subPrime), },
    { SEC_ASN1_OCTET_STRING, offsetof(SECKEYPQGParams,base), },
    { 0 },
};
 
const SEC_ASN1Template SECKEY_FortezzaDiffParameterTemplate[] = {
    { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECKEYDiffPQGParams) },
    { SEC_ASN1_INLINE, offsetof(SECKEYDiffPQGParams,DiffKEAParams), 
                       SECKEY_FortezzaParameterTemplate},
    { SEC_ASN1_INLINE, offsetof(SECKEYDiffPQGParams,DiffDSAParams), 
                       SECKEY_FortezzaParameterTemplate},
    { 0 },
};

const SEC_ASN1Template SECKEY_FortezzaPreParamTemplate[] = {
    { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED |
      SEC_ASN1_CONTEXT_SPECIFIC | 1, offsetof(SECKEYPQGDualParams,CommParams),
                SECKEY_FortezzaParameterTemplate},
    { 0, }
};

const SEC_ASN1Template SECKEY_FortezzaAltPreParamTemplate[] = {
    { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED |
      SEC_ASN1_CONTEXT_SPECIFIC | 0, offsetof(SECKEYPQGDualParams,DiffParams),
                SECKEY_FortezzaDiffParameterTemplate},
    { 0, }
};

const SEC_ASN1Template SECKEY_KEAPublicKeyTemplate[] = {
    { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey,u.kea.publicValue), },
    { 0, }
};

const SEC_ASN1Template SECKEY_KEAParamsTemplate[] = {
    { SEC_ASN1_OCTET_STRING, offsetof(SECKEYPublicKey,u.kea.params.hash), }, 
    { 0, }
};

SEC_ASN1_CHOOSER_IMPLEMENT(SECKEY_DSAPublicKeyTemplate)
SEC_ASN1_CHOOSER_IMPLEMENT(SECKEY_RSAPublicKeyTemplate)
SEC_ASN1_CHOOSER_IMPLEMENT(CERT_SubjectPublicKeyInfoTemplate)

/*
 * See bugzilla bug 125359
 * Since NSS (via PKCS#11) wants to handle big integers as unsigned ints,
 * all of the templates above that en/decode into integers must be converted
 * from ASN.1's signed integer type.  This is done by marking either the
 * source or destination (encoding or decoding, respectively) type as
 * siUnsignedInteger.
 */
static void
prepare_rsa_pub_key_for_asn1(SECKEYPublicKey *pubk)
{
    pubk->u.rsa.modulus.type = siUnsignedInteger;
    pubk->u.rsa.publicExponent.type = siUnsignedInteger;
}

static void
prepare_dsa_pub_key_for_asn1(SECKEYPublicKey *pubk)
{
    pubk->u.dsa.publicValue.type = siUnsignedInteger;
}

static void
prepare_pqg_params_for_asn1(SECKEYPQGParams *params)
{
    params->prime.type = siUnsignedInteger;
    params->subPrime.type = siUnsignedInteger;
    params->base.type = siUnsignedInteger;
}

static void
prepare_dh_pub_key_for_asn1(SECKEYPublicKey *pubk)
{
    pubk->u.dh.prime.type = siUnsignedInteger;
    pubk->u.dh.base.type = siUnsignedInteger;
    pubk->u.dh.publicValue.type = siUnsignedInteger;
}

static void
prepare_kea_pub_key_for_asn1(SECKEYPublicKey *pubk)
{
    pubk->u.kea.publicValue.type = siUnsignedInteger;
}

/* Create an RSA key pair is any slot able to do so.
** The created keys are "session" (temporary), not "token" (permanent), 
** and they are "sensitive", which makes them costly to move to another token.
*/
SECKEYPrivateKey *
SECKEY_CreateRSAPrivateKey(int keySizeInBits,SECKEYPublicKey **pubk, void *cx)
{
    SECKEYPrivateKey *privk;
    PK11SlotInfo *slot = PK11_GetBestSlot(CKM_RSA_PKCS_KEY_PAIR_GEN,cx);
    PK11RSAGenParams param;

    param.keySizeInBits = keySizeInBits;
    param.pe = 65537L;
    
    privk = PK11_GenerateKeyPair(slot,CKM_RSA_PKCS_KEY_PAIR_GEN,&param,pubk,
					PR_FALSE, PR_TRUE, cx);
    PK11_FreeSlot(slot);
    return(privk);
}

/* Create a DH key pair in any slot able to do so, 
** This is a "session" (temporary), not "token" (permanent) key. 
** Because of the high probability that this key will need to be moved to
** another token, and the high cost of moving "sensitive" keys, we attempt
** to create this key pair without the "sensitive" attribute, but revert to 
** creating a "sensitive" key if necessary.
*/
SECKEYPrivateKey *
SECKEY_CreateDHPrivateKey(SECKEYDHParams *param, SECKEYPublicKey **pubk, void *cx)
{
    SECKEYPrivateKey *privk;
    PK11SlotInfo *slot = PK11_GetBestSlot(CKM_DH_PKCS_KEY_PAIR_GEN,cx);

    privk = PK11_GenerateKeyPair(slot, CKM_DH_PKCS_KEY_PAIR_GEN, param, 
                                 pubk, PR_FALSE, PR_FALSE, cx);
    if (!privk) 
	privk = PK11_GenerateKeyPair(slot, CKM_DH_PKCS_KEY_PAIR_GEN, param, 
	                             pubk, PR_FALSE, PR_TRUE, cx);

    PK11_FreeSlot(slot);
    return(privk);
}

/* Create an EC key pair in any slot able to do so, 
** This is a "session" (temporary), not "token" (permanent) key. 
** Because of the high probability that this key will need to be moved to
** another token, and the high cost of moving "sensitive" keys, we attempt
** to create this key pair without the "sensitive" attribute, but revert to 
** creating a "sensitive" key if necessary.
*/
SECKEYPrivateKey *
SECKEY_CreateECPrivateKey(SECKEYECParams *param, SECKEYPublicKey **pubk, void *cx)
{
#ifdef NSS_ENABLE_ECC
    SECKEYPrivateKey *privk;
    PK11SlotInfo *slot = PK11_GetBestSlot(CKM_EC_KEY_PAIR_GEN,cx);

    privk = PK11_GenerateKeyPair(slot, CKM_EC_KEY_PAIR_GEN, param, 
                                 pubk, PR_FALSE, PR_FALSE, cx);
    if (!privk) 
	privk = PK11_GenerateKeyPair(slot, CKM_EC_KEY_PAIR_GEN, param, 
	                             pubk, PR_FALSE, PR_TRUE, cx);

    PK11_FreeSlot(slot);
    return(privk);
#else
    return NULL;
#endif /* NSS_ENABLE_ECC */
}

void
SECKEY_DestroyPrivateKey(SECKEYPrivateKey *privk)
{
    if (privk) {
	if (privk->pkcs11Slot) {
	    if (privk->pkcs11IsTemp) {
	    	PK11_DestroyObject(privk->pkcs11Slot,privk->pkcs11ID);
	    }
	    PK11_FreeSlot(privk->pkcs11Slot);

	}
    	if (privk->arena) {
	    PORT_FreeArena(privk->arena, PR_TRUE);
	}
    }
}

void
SECKEY_DestroyPublicKey(SECKEYPublicKey *pubk)
{
    if (pubk) {
	if (pubk->pkcs11Slot) {
	    if (!PK11_IsPermObject(pubk->pkcs11Slot,pubk->pkcs11ID)) {
		PK11_DestroyObject(pubk->pkcs11Slot,pubk->pkcs11ID);
	    }
	    PK11_FreeSlot(pubk->pkcs11Slot);
	}
    	if (pubk->arena) {
	    PORT_FreeArena(pubk->arena, PR_FALSE);
	}
    }
}

SECStatus
SECKEY_CopySubjectPublicKeyInfo(PRArenaPool *arena,
			     CERTSubjectPublicKeyInfo *to,
			     CERTSubjectPublicKeyInfo *from)
{
    SECStatus rv;

    rv = SECOID_CopyAlgorithmID(arena, &to->algorithm, &from->algorithm);
    if (rv == SECSuccess)
	rv = SECITEM_CopyItem(arena, &to->subjectPublicKey, &from->subjectPublicKey);

    return rv;
}

SECStatus
SECKEY_KEASetParams(SECKEYKEAParams * params, SECKEYPublicKey * pubKey) {

    if (pubKey->keyType == fortezzaKey) {
        /* the key is a fortezza V1 public key  */

	/* obtain hash of pubkey->u.fortezza.params.prime.data +
		          pubkey->u.fortezza.params.subPrime.data +
			  pubkey->u.fortezza.params.base.data  */

	/* store hash in params->hash */

    } else if (pubKey->keyType == keaKey) {

        /* the key is a new fortezza KEA public key. */
        SECITEM_CopyItem(pubKey->arena, &params->hash, 
	                 &pubKey->u.kea.params.hash );

    } else {

	/* the key has no KEA parameters */
	return SECFailure;
    }
    return SECSuccess;
}


SECStatus
SECKEY_KEAParamCompare(CERTCertificate *cert1,CERTCertificate *cert2) 
{

    SECStatus rv;

    SECKEYPublicKey *pubKey1 = 0;
    SECKEYPublicKey *pubKey2 = 0;

    SECKEYKEAParams params1;
    SECKEYKEAParams params2;


    rv = SECFailure;

    /* get cert1's public key */
    pubKey1 = CERT_ExtractPublicKey(cert1);
    if ( !pubKey1 ) {
	return(SECFailure);
    }
    

    /* get cert2's public key */
    pubKey2 = CERT_ExtractPublicKey(cert2);
    if ( !pubKey2 ) {
	return(SECFailure);
    }

    /* handle the case when both public keys are new
     * fortezza KEA public keys.    */

    if ((pubKey1->keyType == keaKey) &&
        (pubKey2->keyType == keaKey) ) {

        rv = (SECStatus)SECITEM_CompareItem(&pubKey1->u.kea.params.hash,
	                         &pubKey2->u.kea.params.hash);
	goto done;
    }

    /* handle the case when both public keys are old fortezza
     * public keys.              */

    if ((pubKey1->keyType == fortezzaKey) &&
        (pubKey2->keyType == fortezzaKey) ) {

        rv = (SECStatus)SECITEM_CompareItem(&pubKey1->u.fortezza.keaParams.prime,
	                         &pubKey2->u.fortezza.keaParams.prime);

	if (rv == SECEqual) {
	    rv = (SECStatus)SECITEM_CompareItem(&pubKey1->u.fortezza.keaParams.subPrime,
	                             &pubKey2->u.fortezza.keaParams.subPrime);
	}

	if (rv == SECEqual) {
	    rv = (SECStatus)SECITEM_CompareItem(&pubKey1->u.fortezza.keaParams.base,
	                             &pubKey2->u.fortezza.keaParams.base);
	}
	
	goto done;
    }


    /* handle the case when the public keys are a mixture of 
     * old and new.                          */

    rv = SECKEY_KEASetParams(&params1, pubKey1);
    if (rv != SECSuccess) return rv;

    rv = SECKEY_KEASetParams(&params2, pubKey2);
    if (rv != SECSuccess) return rv;

    rv = (SECStatus)SECITEM_CompareItem(&params1.hash, &params2.hash);

done:
    SECKEY_DestroyPublicKey(pubKey1);
    SECKEY_DestroyPublicKey(pubKey2);

    return rv;   /* returns SECEqual if parameters are equal */

}


/* Procedure to update the pqg parameters for a cert's public key.
 * pqg parameters only need to be updated for DSA and fortezza certificates.
 * The procedure uses calls to itself recursively to update a certificate
 * issuer's pqg parameters.  Some important rules are:
 *    - Do nothing if the cert already has PQG parameters.
 *    - If the cert does not have PQG parameters, obtain them from the issuer.
 *    - A valid cert chain cannot have a DSA or Fortezza cert without
 *      pqg parameters that has a parent that is not a DSA or Fortezza cert.
 *    - pqg paramters are stored in two different formats: the standard
 *      DER encoded format and the fortezza-only wrapped format.  The params
 *      should be copied from issuer to subject cert without modifying the
 *      formats.  The public key extraction code will deal with the different
 *      formats at the time of extraction.  */

static SECStatus
seckey_UpdateCertPQGChain(CERTCertificate * subjectCert, int count)
{
    SECStatus rv, rvCompare;
    SECOidData *oid=NULL;
    int tag;
    CERTSubjectPublicKeyInfo * subjectSpki=NULL;
    CERTSubjectPublicKeyInfo * issuerSpki=NULL;
    CERTCertificate *issuerCert = NULL;

    rv = SECSuccess;

    /* increment cert chain length counter*/
    count++;

    /* check if cert chain length exceeds the maximum length*/
    if (count > CERT_MAX_CERT_CHAIN) {
	return SECFailure;
    }

    oid = SECOID_FindOID(&subjectCert->subjectPublicKeyInfo.algorithm.algorithm);            
    if (oid != NULL) {  
        tag = oid->offset;
             
        /* Check if cert has a DSA or Fortezza public key. If not, return
         * success since no PQG params need to be updated.  */

	if ( (tag != SEC_OID_MISSI_KEA_DSS_OLD) &&
	     (tag != SEC_OID_MISSI_DSS_OLD) &&
             (tag != SEC_OID_MISSI_KEA_DSS) &&
             (tag != SEC_OID_MISSI_DSS) &&               
             (tag != SEC_OID_ANSIX9_DSA_SIGNATURE) &&
             (tag != SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST) &&
             (tag != SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST) &&
             (tag != SEC_OID_SDN702_DSA_SIGNATURE) &&
             (tag != SEC_OID_ANSIX962_EC_PUBLIC_KEY) ) {
            
            return SECSuccess;
        }
    } else {
        return SECFailure;  /* return failure if oid is NULL */  
    }

    /* if cert has PQG parameters, return success */

    subjectSpki=&subjectCert->subjectPublicKeyInfo;

    if (subjectSpki->algorithm.parameters.len != 0) {
        return SECSuccess;
    }

    /* check if the cert is self-signed */
    rvCompare = (SECStatus)SECITEM_CompareItem(&subjectCert->derSubject,
				    &subjectCert->derIssuer);
    if (rvCompare == SECEqual) {
      /* fail since cert is self-signed and has no pqg params. */
	return SECFailure;     
    }
     
    /* get issuer cert */
    issuerCert = CERT_FindCertIssuer(subjectCert, PR_Now(), certUsageAnyCA);
    if ( ! issuerCert ) {
	return SECFailure;
    }

    /* if parent is not DSA or fortezza, return failure since
       we don't allow this case. */

    oid = SECOID_FindOID(&issuerCert->subjectPublicKeyInfo.algorithm.algorithm);
    if (oid != NULL) {  
        tag = oid->offset;
             
        /* Check if issuer cert has a DSA or Fortezza public key. If not,
         * return failure.   */

	if ( (tag != SEC_OID_MISSI_KEA_DSS_OLD) &&
	     (tag != SEC_OID_MISSI_DSS_OLD) &&
             (tag != SEC_OID_MISSI_KEA_DSS) &&
             (tag != SEC_OID_MISSI_DSS) &&               
             (tag != SEC_OID_ANSIX9_DSA_SIGNATURE) &&
             (tag != SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST) &&
             (tag != SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST) &&
             (tag != SEC_OID_SDN702_DSA_SIGNATURE) &&
             (tag != SEC_OID_ANSIX962_EC_PUBLIC_KEY) ) {            
            return SECFailure;
        }
    } else {
        return SECFailure;  /* return failure if oid is NULL */  
    }


    /* at this point the subject cert has no pqg parameters and the
     * issuer cert has a DSA or fortezza public key.  Update the issuer's
     * pqg parameters with a recursive call to this same function. */

    rv = seckey_UpdateCertPQGChain(issuerCert, count);
    if (rv != SECSuccess) return rv;

    /* ensure issuer has pqg parameters */

    issuerSpki=&issuerCert->subjectPublicKeyInfo;
    if (issuerSpki->algorithm.parameters.len == 0) {
        rv = SECFailure; 
    }

    /* if update was successful and pqg params present, then copy the
     * parameters to the subject cert's key. */

    if (rv == SECSuccess) {
        rv = SECITEM_CopyItem(subjectCert->arena,
                              &subjectSpki->algorithm.parameters, 
	   		      &issuerSpki->algorithm.parameters);
    }

    return rv;

}
 

SECStatus
SECKEY_UpdateCertPQG(CERTCertificate * subjectCert)
{
    if (!subjectCert) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
	return SECFailure;
    }
    return seckey_UpdateCertPQGChain(subjectCert,0);
}
   

/* Decode the PQG parameters.  The params could be stored in two
 * possible formats, the old fortezza-only wrapped format or
 * the standard DER encoded format.   Store the decoded parameters in an
 * old fortezza cert data structure */
 
SECStatus
SECKEY_FortezzaDecodePQGtoOld(PRArenaPool *arena, SECKEYPublicKey *pubk,
                              SECItem *params) {
        SECStatus rv;
	SECKEYPQGDualParams dual_params;

    if (params == NULL) return SECFailure; 
    
    if (params->data == NULL) return SECFailure;

    /* Check if params use the standard format.
     * The value 0xa1 will appear in the first byte of the parameter data
     * if the PQG parameters are not using the standard format. This
     * code should be changed to use a better method to detect non-standard
     * parameters.    */

    if ((params->data[0] != 0xa1) &&
        (params->data[0] != 0xa0)) {

            /* PQG params are in the standard format */

	    /* Store DSA PQG parameters */
	    prepare_pqg_params_for_asn1(&pubk->u.fortezza.params);
            rv = SEC_ASN1DecodeItem(arena, &pubk->u.fortezza.params,
                              SECKEY_PQGParamsTemplate,
                              params);

	    if (rv == SECSuccess) {

	        /* Copy the DSA PQG parameters to the KEA PQG parameters. */
	        rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.keaParams.prime,
                                      &pubk->u.fortezza.params.prime);
                if (rv != SECSuccess) return rv;
                rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.keaParams.subPrime,
                                      &pubk->u.fortezza.params.subPrime);
                if (rv != SECSuccess) return rv;
                rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.keaParams.base,
                                      &pubk->u.fortezza.params.base);
                if (rv != SECSuccess) return rv;
            }

    } else {

	dual_params.CommParams.prime.len = 0;
        dual_params.CommParams.subPrime.len = 0;
	dual_params.CommParams.base.len = 0;
	dual_params.DiffParams.DiffDSAParams.prime.len = 0;
        dual_params.DiffParams.DiffDSAParams.subPrime.len = 0;
	dual_params.DiffParams.DiffDSAParams.base.len = 0;

        /* else the old fortezza-only wrapped format is used. */

	if (params->data[0] == 0xa1) {
            rv = SEC_ASN1DecodeItem(arena, &dual_params, 
				SECKEY_FortezzaPreParamTemplate, params);
	} else {
            rv = SEC_ASN1DecodeItem(arena, &dual_params, 
	   			    SECKEY_FortezzaAltPreParamTemplate, params);
        }

        if (rv < 0) return rv;
	
        if ( (dual_params.CommParams.prime.len > 0) &&
             (dual_params.CommParams.subPrime.len > 0) && 
             (dual_params.CommParams.base.len > 0) ) {
            /* copy in common params */
	    
	    rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.params.prime,
                                  &dual_params.CommParams.prime);
            if (rv != SECSuccess) return rv;
            rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.params.subPrime,
                                  &dual_params.CommParams.subPrime);
            if (rv != SECSuccess) return rv;
            rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.params.base,
                                  &dual_params.CommParams.base);

	    /* Copy the DSA PQG parameters to the KEA PQG parameters. */
	    rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.keaParams.prime,
                                  &pubk->u.fortezza.params.prime);
            if (rv != SECSuccess) return rv;
            rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.keaParams.subPrime,
                                  &pubk->u.fortezza.params.subPrime);
            if (rv != SECSuccess) return rv;
            rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.keaParams.base,
                                  &pubk->u.fortezza.params.base);
            if (rv != SECSuccess) return rv;

        } else {

	    /* else copy in different params */

	    /* copy DSA PQG parameters */
	    rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.params.prime,
                                  &dual_params.DiffParams.DiffDSAParams.prime);
            if (rv != SECSuccess) return rv;
            rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.params.subPrime,
                                  &dual_params.DiffParams.DiffDSAParams.subPrime);
            if (rv != SECSuccess) return rv;
            rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.params.base,
                                  &dual_params.DiffParams.DiffDSAParams.base);

	    /* copy KEA PQG parameters */

	    rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.keaParams.prime,
                                  &dual_params.DiffParams.DiffKEAParams.prime);
            if (rv != SECSuccess) return rv;
            rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.keaParams.subPrime,
                                  &dual_params.DiffParams.DiffKEAParams.subPrime);
            if (rv != SECSuccess) return rv;
            rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.keaParams.base,
                                  &dual_params.DiffParams.DiffKEAParams.base);
        }
       
    }
    return rv;
}


/* Decode the DSA PQG parameters.  The params could be stored in two
 * possible formats, the old fortezza-only wrapped format or
 * the normal standard format.  Store the decoded parameters in
 * a V3 certificate data structure.  */ 

SECStatus
SECKEY_DSADecodePQG(PRArenaPool *arena, SECKEYPublicKey *pubk, SECItem *params) {
        SECStatus rv;
	SECKEYPQGDualParams dual_params;

    if (params == NULL) return SECFailure; 
    
    if (params->data == NULL) return SECFailure;

    /* Check if params use the standard format.
     * The value 0xa1 will appear in the first byte of the parameter data
     * if the PQG parameters are not using the standard format.  This
     * code should be changed to use a better method to detect non-standard
     * parameters.    */

    if ((params->data[0] != 0xa1) &&
        (params->data[0] != 0xa0)) {
    
         /* PQG params are in the standard format */
         prepare_pqg_params_for_asn1(&pubk->u.dsa.params);
         rv = SEC_ASN1DecodeItem(arena, &pubk->u.dsa.params,
                             SECKEY_PQGParamsTemplate,
                             params);
    } else {

	dual_params.CommParams.prime.len = 0;
        dual_params.CommParams.subPrime.len = 0;
	dual_params.CommParams.base.len = 0;
	dual_params.DiffParams.DiffDSAParams.prime.len = 0;
        dual_params.DiffParams.DiffDSAParams.subPrime.len = 0;
	dual_params.DiffParams.DiffDSAParams.base.len = 0;

        /* else the old fortezza-only wrapped format is used. */
        if (params->data[0] == 0xa1) {
            rv = SEC_ASN1DecodeItem(arena, &dual_params, 
				SECKEY_FortezzaPreParamTemplate, params);
	} else {
            rv = SEC_ASN1DecodeItem(arena, &dual_params, 
	   			    SECKEY_FortezzaAltPreParamTemplate, params);
        }

        if (rv < 0) return rv;

        if ( (dual_params.CommParams.prime.len > 0) &&
             (dual_params.CommParams.subPrime.len > 0) && 
             (dual_params.CommParams.base.len > 0) ) {
            /* copy in common params */
	    
	    rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.prime,
                                  &dual_params.CommParams.prime);
            if (rv != SECSuccess) return rv;
            rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.subPrime,
                                  &dual_params.CommParams.subPrime);
            if (rv != SECSuccess) return rv;
            rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.base,
                                  &dual_params.CommParams.base);

        } else {

	    /* else copy in different params */

	    /* copy DSA PQG parameters */
	    rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.prime,
                                  &dual_params.DiffParams.DiffDSAParams.prime);
            if (rv != SECSuccess) return rv;
            rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.subPrime,
                                  &dual_params.DiffParams.DiffDSAParams.subPrime);
            if (rv != SECSuccess) return rv;
            rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.base,
                                  &dual_params.DiffParams.DiffDSAParams.base);

        }
    }
    return rv;
}



/* Decodes the DER encoded fortezza public key and stores the results in a
 * structure of type SECKEYPublicKey. */

SECStatus
SECKEY_FortezzaDecodeCertKey(PRArenaPool *arena, SECKEYPublicKey *pubk,
                             SECItem *rawkey, SECItem *params) {

	unsigned char *rawptr = rawkey->data;
	unsigned char *end = rawkey->data + rawkey->len;
	unsigned char *clearptr;

	/* first march down and decode the raw key data */

	/* version */	
	pubk->u.fortezza.KEAversion = *rawptr++;
	if (*rawptr++ != 0x01) {
		return SECFailure;
	}

	/* KMID */
	PORT_Memcpy(pubk->u.fortezza.KMID,rawptr,
				sizeof(pubk->u.fortezza.KMID));
	rawptr += sizeof(pubk->u.fortezza.KMID);

	/* clearance (the string up to the first byte with the hi-bit on */
	clearptr = rawptr;
	while ((rawptr < end) && (*rawptr++ & 0x80));

	if (rawptr >= end) { return SECFailure; }
	pubk->u.fortezza.clearance.len = rawptr - clearptr;
	pubk->u.fortezza.clearance.data = 
		(unsigned char*)PORT_ArenaZAlloc(arena,pubk->u.fortezza.clearance.len);
	if (pubk->u.fortezza.clearance.data == NULL) {
		return SECFailure;
	}
	PORT_Memcpy(pubk->u.fortezza.clearance.data,clearptr,
					pubk->u.fortezza.clearance.len);

	/* KEAPrivilege (the string up to the first byte with the hi-bit on */
	clearptr = rawptr;
	while ((rawptr < end) && (*rawptr++ & 0x80));
	if (rawptr >= end) { return SECFailure; }
	pubk->u.fortezza.KEApriviledge.len = rawptr - clearptr;
	pubk->u.fortezza.KEApriviledge.data = 
		(unsigned char*)PORT_ArenaZAlloc(arena,pubk->u.fortezza.KEApriviledge.len);
	if (pubk->u.fortezza.KEApriviledge.data == NULL) {
		return SECFailure;
	}
	PORT_Memcpy(pubk->u.fortezza.KEApriviledge.data,clearptr,
				pubk->u.fortezza.KEApriviledge.len);


	/* now copy the key. The next to bytes are the key length, and the
	 * key follows */
	pubk->u.fortezza.KEAKey.len = (*rawptr << 8) | rawptr[1];

	rawptr += 2;
	if (rawptr+pubk->u.fortezza.KEAKey.len > end) { return SECFailure; }
	pubk->u.fortezza.KEAKey.data = 
			(unsigned char*)PORT_ArenaZAlloc(arena,pubk->u.fortezza.KEAKey.len);
	if (pubk->u.fortezza.KEAKey.data == NULL) {
		return SECFailure;
	}
	PORT_Memcpy(pubk->u.fortezza.KEAKey.data,rawptr,
					pubk->u.fortezza.KEAKey.len);
	rawptr += pubk->u.fortezza.KEAKey.len;

	/* shared key */
	if (rawptr >= end) {
	    pubk->u.fortezza.DSSKey.len = pubk->u.fortezza.KEAKey.len;
	    /* this depends on the fact that we are going to get freed with an
	     * ArenaFree call. We cannot free DSSKey and KEAKey separately */
	    pubk->u.fortezza.DSSKey.data=
					pubk->u.fortezza.KEAKey.data;
	    pubk->u.fortezza.DSSpriviledge.len = 
				pubk->u.fortezza.KEApriviledge.len;
	    pubk->u.fortezza.DSSpriviledge.data =
			pubk->u.fortezza.DSSpriviledge.data;
	    goto done;
	}
		

	/* DSS Version is next */
	pubk->u.fortezza.DSSversion = *rawptr++;

	if (*rawptr++ != 2) {
		return SECFailure;
	}

	/* DSSPrivilege (the string up to the first byte with the hi-bit on */
	clearptr = rawptr;
	while ((rawptr < end) && (*rawptr++ & 0x80));
	if (rawptr >= end) { return SECFailure; }
	pubk->u.fortezza.DSSpriviledge.len = rawptr - clearptr;
	pubk->u.fortezza.DSSpriviledge.data = 
		(unsigned char*)PORT_ArenaZAlloc(arena,pubk->u.fortezza.DSSpriviledge.len);
	if (pubk->u.fortezza.DSSpriviledge.data == NULL) {
		return SECFailure;
	}
	PORT_Memcpy(pubk->u.fortezza.DSSpriviledge.data,clearptr,
				pubk->u.fortezza.DSSpriviledge.len);

	/* finally copy the DSS key. The next to bytes are the key length,
	 *  and the key follows */
	pubk->u.fortezza.DSSKey.len = (*rawptr << 8) | rawptr[1];

	rawptr += 2;
	if (rawptr+pubk->u.fortezza.DSSKey.len > end){ return SECFailure; }
	pubk->u.fortezza.DSSKey.data = 
			(unsigned char*)PORT_ArenaZAlloc(arena,pubk->u.fortezza.DSSKey.len);
	if (pubk->u.fortezza.DSSKey.data == NULL) {
		return SECFailure;
	}
	PORT_Memcpy(pubk->u.fortezza.DSSKey.data,rawptr,
					pubk->u.fortezza.DSSKey.len);

	/* ok, now we decode the parameters */
done:

        return SECKEY_FortezzaDecodePQGtoOld(arena, pubk, params);
}


/* Function used to determine what kind of cert we are dealing with. */
KeyType 
CERT_GetCertKeyType (CERTSubjectPublicKeyInfo *spki) {
    int tag;
    KeyType keyType;

    tag = SECOID_GetAlgorithmTag(&spki->algorithm);
    switch (tag) {
      case SEC_OID_X500_RSA_ENCRYPTION:
      case SEC_OID_PKCS1_RSA_ENCRYPTION:
	keyType = rsaKey;
	break;
      case SEC_OID_ANSIX9_DSA_SIGNATURE:
	keyType = dsaKey;
	break;
      case SEC_OID_MISSI_KEA_DSS_OLD:
      case SEC_OID_MISSI_KEA_DSS:
      case SEC_OID_MISSI_DSS_OLD:
      case SEC_OID_MISSI_DSS:  
	keyType = fortezzaKey;
	break;
      case SEC_OID_MISSI_KEA:
      case SEC_OID_MISSI_ALT_KEA:
	keyType = keaKey;
	break;
      case SEC_OID_X942_DIFFIE_HELMAN_KEY:
	keyType = dhKey;
	break;
      case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
	keyType = ecKey;
	break;
      default:
	keyType = nullKey;
    }
    return keyType;
}

static SECKEYPublicKey *
seckey_ExtractPublicKey(CERTSubjectPublicKeyInfo *spki)
{
    SECKEYPublicKey *pubk;
    SECItem os, newOs, newParms;
    SECStatus rv;
    PRArenaPool *arena;
    SECOidTag tag;

    arena = PORT_NewArena (DER_DEFAULT_CHUNKSIZE);
    if (arena == NULL)
	return NULL;

    pubk = (SECKEYPublicKey *) PORT_ArenaZAlloc(arena, sizeof(SECKEYPublicKey));
    if (pubk == NULL) {
	PORT_FreeArena (arena, PR_FALSE);
	return NULL;
    }

    pubk->arena = arena;
    pubk->pkcs11Slot = 0;
    pubk->pkcs11ID = CK_INVALID_HANDLE;


    /* Convert bit string length from bits to bytes */
    os = spki->subjectPublicKey;
    DER_ConvertBitString (&os);

    tag = SECOID_GetAlgorithmTag(&spki->algorithm);

    /* copy the DER into the arena, since Quick DER returns data that points
       into the DER input, which may get freed by the caller */
    rv = SECITEM_CopyItem(arena, &newOs, &os);
    if ( rv == SECSuccess )
    switch ( tag ) {
      case SEC_OID_X500_RSA_ENCRYPTION:
      case SEC_OID_PKCS1_RSA_ENCRYPTION:
	pubk->keyType = rsaKey;
	prepare_rsa_pub_key_for_asn1(pubk);        
        rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_RSAPublicKeyTemplate, &newOs);
	if (rv == SECSuccess)
	    return pubk;
	break;
      case SEC_OID_ANSIX9_DSA_SIGNATURE:
      case SEC_OID_SDN702_DSA_SIGNATURE:
	pubk->keyType = dsaKey;
	prepare_dsa_pub_key_for_asn1(pubk);
	rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_DSAPublicKeyTemplate, &newOs);
	if (rv != SECSuccess) break;

        rv = SECKEY_DSADecodePQG(arena, pubk,
                                 &spki->algorithm.parameters); 

	if (rv == SECSuccess) return pubk;
	break;
      case SEC_OID_X942_DIFFIE_HELMAN_KEY:
	pubk->keyType = dhKey;
	prepare_dh_pub_key_for_asn1(pubk);
	rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_DHPublicKeyTemplate, &newOs);
	if (rv != SECSuccess) break;

        /* copy the DER into the arena, since Quick DER returns data that points
           into the DER input, which may get freed by the caller */
        rv = SECITEM_CopyItem(arena, &newParms, &spki->algorithm.parameters);
        if ( rv != SECSuccess )
            break;

        rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_DHParamKeyTemplate,
                                 &newParms); 

	if (rv == SECSuccess) return pubk;
	break;
      case SEC_OID_MISSI_KEA_DSS_OLD:
      case SEC_OID_MISSI_KEA_DSS:
      case SEC_OID_MISSI_DSS_OLD:
      case SEC_OID_MISSI_DSS:
	pubk->keyType = fortezzaKey;
	rv = SECKEY_FortezzaDecodeCertKey(arena, pubk, &newOs,
				          &spki->algorithm.parameters);
	if (rv == SECSuccess)
	    return pubk;
	break;

      case SEC_OID_MISSI_KEA:
	pubk->keyType = keaKey;

	prepare_kea_pub_key_for_asn1(pubk);
        rv = SEC_QuickDERDecodeItem(arena, pubk,
                                SECKEY_KEAPublicKeyTemplate, &newOs);
        if (rv != SECSuccess) break;

        /* copy the DER into the arena, since Quick DER returns data that points
           into the DER input, which may get freed by the caller */
        rv = SECITEM_CopyItem(arena, &newParms, &spki->algorithm.parameters);
        if ( rv != SECSuccess )
            break;

        rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_KEAParamsTemplate,
                        &newParms);

	if (rv == SECSuccess)
	    return pubk;

        break;

      case SEC_OID_MISSI_ALT_KEA:
	pubk->keyType = keaKey;

        rv = SECITEM_CopyItem(arena,&pubk->u.kea.publicValue,&newOs);
        if (rv != SECSuccess) break;
 
        /* copy the DER into the arena, since Quick DER returns data that points
           into the DER input, which may get freed by the caller */
        rv = SECITEM_CopyItem(arena, &newParms, &spki->algorithm.parameters);
        if ( rv != SECSuccess )
            break;

        rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_KEAParamsTemplate,
                        &newParms);

	if (rv == SECSuccess)
	    return pubk;

        break;

#ifdef NSS_ENABLE_ECC
      case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
	pubk->keyType = ecKey;
	pubk->u.ec.size = 0;

	/* Since PKCS#11 directly takes the DER encoding of EC params
	 * and public value, we don't need any decoding here.
	 */
        rv = SECITEM_CopyItem(arena, &pubk->u.ec.DEREncodedParams, 
	    &spki->algorithm.parameters);
        if ( rv != SECSuccess )
            break;
        rv = SECITEM_CopyItem(arena, &pubk->u.ec.publicValue, &newOs);
	if (rv == SECSuccess) return pubk;
	break;
#endif /* NSS_ENABLE_ECC */

      default:
	rv = SECFailure;
	break;
    }

    SECKEY_DestroyPublicKey (pubk);
    return NULL;
}


/* required for JSS */
SECKEYPublicKey *
SECKEY_ExtractPublicKey(CERTSubjectPublicKeyInfo *spki)
{
    return seckey_ExtractPublicKey(spki);
}

SECKEYPublicKey *
CERT_ExtractPublicKey(CERTCertificate *cert)
{
    SECStatus rv;

    if (!cert) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
	return NULL;
    }
    rv = SECKEY_UpdateCertPQG(cert);
    if (rv != SECSuccess) return NULL;

    return seckey_ExtractPublicKey(&cert->subjectPublicKeyInfo);
}

/*
 * Get the public key for the fortezza KMID. NOTE this requires the
 * PQG paramters to be set. We probably should have a fortezza call that 
 * just extracts the kmid for us directly so this function can work
 * without having the whole cert chain
 */
SECKEYPublicKey *
CERT_KMIDPublicKey(CERTCertificate *cert)
{
    return seckey_ExtractPublicKey(&cert->subjectPublicKeyInfo);
}

int
SECKEY_ECParamsToKeySize(const SECItem *encodedParams)
{
    SECOidTag tag;
    SECItem oid = { siBuffer, NULL, 0};
	
    /* The encodedParams data contains 0x06 (SEC_ASN1_OBJECT_ID),
     * followed by the length of the curve oid and the curve oid.
     */
    oid.len = encodedParams->data[1];
    oid.data = encodedParams->data + 2;
    if ((tag = SECOID_FindOIDTag(&oid)) == SEC_OID_UNKNOWN)
	return 0;

    switch (tag) {
    case SEC_OID_SECG_EC_SECP112R1:
    case SEC_OID_SECG_EC_SECP112R2:
        return 112;

    case SEC_OID_SECG_EC_SECT113R1:
    case SEC_OID_SECG_EC_SECT113R2:
	return 113;

    case SEC_OID_SECG_EC_SECP128R1:
    case SEC_OID_SECG_EC_SECP128R2:
	return 128;

    case SEC_OID_SECG_EC_SECT131R1:
    case SEC_OID_SECG_EC_SECT131R2:
	return 131;

    case SEC_OID_SECG_EC_SECP160K1:
    case SEC_OID_SECG_EC_SECP160R1:
    case SEC_OID_SECG_EC_SECP160R2:
	return 160;

    case SEC_OID_SECG_EC_SECT163K1:
    case SEC_OID_SECG_EC_SECT163R1:
    case SEC_OID_SECG_EC_SECT163R2:
    case SEC_OID_ANSIX962_EC_C2PNB163V1:
    case SEC_OID_ANSIX962_EC_C2PNB163V2:
    case SEC_OID_ANSIX962_EC_C2PNB163V3:
	return 163;

    case SEC_OID_ANSIX962_EC_C2PNB176V1:
	return 176;

    case SEC_OID_ANSIX962_EC_C2TNB191V1:
    case SEC_OID_ANSIX962_EC_C2TNB191V2:
    case SEC_OID_ANSIX962_EC_C2TNB191V3:
    case SEC_OID_ANSIX962_EC_C2ONB191V4:
    case SEC_OID_ANSIX962_EC_C2ONB191V5:
	return 191;

    case SEC_OID_SECG_EC_SECP192K1:
    case SEC_OID_ANSIX962_EC_PRIME192V1:
    case SEC_OID_ANSIX962_EC_PRIME192V2:
    case SEC_OID_ANSIX962_EC_PRIME192V3:
	return 192;

    case SEC_OID_SECG_EC_SECT193R1:
    case SEC_OID_SECG_EC_SECT193R2:
	return 193;

    case SEC_OID_ANSIX962_EC_C2PNB208W1:
	return 208;

    case SEC_OID_SECG_EC_SECP224K1:
    case SEC_OID_SECG_EC_SECP224R1:
	return 224;

    case SEC_OID_SECG_EC_SECT233K1:
    case SEC_OID_SECG_EC_SECT233R1:
	return 233;

    case SEC_OID_SECG_EC_SECT239K1:
    case SEC_OID_ANSIX962_EC_C2TNB239V1:
    case SEC_OID_ANSIX962_EC_C2TNB239V2:
    case SEC_OID_ANSIX962_EC_C2TNB239V3:
    case SEC_OID_ANSIX962_EC_C2ONB239V4:
    case SEC_OID_ANSIX962_EC_C2ONB239V5:
    case SEC_OID_ANSIX962_EC_PRIME239V1:
    case SEC_OID_ANSIX962_EC_PRIME239V2:
    case SEC_OID_ANSIX962_EC_PRIME239V3:
	return 239;

    case SEC_OID_SECG_EC_SECP256K1:
    case SEC_OID_ANSIX962_EC_PRIME256V1:
	return 256;

    case SEC_OID_ANSIX962_EC_C2PNB272W1:
	return 272;

    case SEC_OID_SECG_EC_SECT283K1:
    case SEC_OID_SECG_EC_SECT283R1:
	return 283;

    case SEC_OID_ANSIX962_EC_C2PNB304W1:
	return 304;

    case SEC_OID_ANSIX962_EC_C2TNB359V1:
	return 359;

    case SEC_OID_ANSIX962_EC_C2PNB368W1:
	return 368;

    case SEC_OID_SECG_EC_SECP384R1:
	return 384;

    case SEC_OID_SECG_EC_SECT409K1:
    case SEC_OID_SECG_EC_SECT409R1:
	return 409;

    case SEC_OID_ANSIX962_EC_C2TNB431R1:
	return 431;

    case SEC_OID_SECG_EC_SECP521R1:
	return 521;

    case SEC_OID_SECG_EC_SECT571K1:
    case SEC_OID_SECG_EC_SECT571R1:
	return 571;

    default:
	    return 0;
    }
}

/* returns key strength in bytes (not bits) */
unsigned
SECKEY_PublicKeyStrength(SECKEYPublicKey *pubk)
{
    unsigned char b0;

    /* interpret modulus length as key strength... in
     * fortezza that's the public key length */

    switch (pubk->keyType) {
    case rsaKey:
    	b0 = pubk->u.rsa.modulus.data[0];
    	return b0 ? pubk->u.rsa.modulus.len : pubk->u.rsa.modulus.len - 1;
    case dsaKey:
    	b0 = pubk->u.dsa.publicValue.data[0];
    	return b0 ? pubk->u.dsa.publicValue.len :
	    pubk->u.dsa.publicValue.len - 1;
    case dhKey:
    	b0 = pubk->u.dh.publicValue.data[0];
    	return b0 ? pubk->u.dh.publicValue.len :
	    pubk->u.dh.publicValue.len - 1;
    case fortezzaKey:
	return PR_MAX(pubk->u.fortezza.KEAKey.len, pubk->u.fortezza.DSSKey.len);
#ifdef NSS_ENABLE_ECC
    case ecKey:
	/* Get the key size in bits and adjust */
	if (pubk->u.ec.size == 0) {
	    pubk->u.ec.size = 
		SECKEY_ECParamsToKeySize(&pubk->u.ec.DEREncodedParams);
	} 
	return (pubk->u.ec.size + 7)/8;
#endif /* NSS_ENABLE_ECC */
    default:
	break;
    }
    return 0;
}

/* returns key strength in bits */
unsigned
SECKEY_PublicKeyStrengthInBits(SECKEYPublicKey *pubk)
{
    switch (pubk->keyType) {
    case rsaKey:
    case dsaKey:
    case dhKey:
    case fortezzaKey:
	return SECKEY_PublicKeyStrength(pubk) * 8; /* 1 byte = 8 bits */
#ifdef NSS_ENABLE_ECC
    case ecKey:
	if (pubk->u.ec.size == 0) {
	    pubk->u.ec.size = 
		SECKEY_ECParamsToKeySize(&pubk->u.ec.DEREncodedParams);
	} 
	return pubk->u.ec.size;
#endif /* NSS_ENABLE_ECC */
    default:
	break;
    }
    return 0;
}

SECKEYPrivateKey *
SECKEY_CopyPrivateKey(SECKEYPrivateKey *privk)
{
    SECKEYPrivateKey *copyk;
    PRArenaPool *arena;
    
    if (privk == NULL) {
	return NULL;
    }
    
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    if (arena == NULL) {
	PORT_SetError (SEC_ERROR_NO_MEMORY);
	return NULL;
    }

    copyk = (SECKEYPrivateKey *) PORT_ArenaZAlloc (arena, sizeof (SECKEYPrivateKey));
    if (copyk) {
	copyk->arena = arena;
	copyk->keyType = privk->keyType;

	/* copy the PKCS #11 parameters */
	copyk->pkcs11Slot = PK11_ReferenceSlot(privk->pkcs11Slot);
	/* if the key we're referencing was a temparary key we have just
	 * created, that we want to go away when we're through, we need
	 * to make a copy of it */
	if (privk->pkcs11IsTemp) {
	    copyk->pkcs11ID = 
			PK11_CopyKey(privk->pkcs11Slot,privk->pkcs11ID);
	    if (copyk->pkcs11ID == CK_INVALID_HANDLE) goto fail;
	} else {
	    copyk->pkcs11ID = privk->pkcs11ID;
	}
	copyk->pkcs11IsTemp = privk->pkcs11IsTemp;
	copyk->wincx = privk->wincx;
	return copyk;
    } else {
	PORT_SetError (SEC_ERROR_NO_MEMORY);
    }

fail:
    PORT_FreeArena (arena, PR_FALSE);
    return NULL;
}

SECKEYPublicKey *
SECKEY_CopyPublicKey(SECKEYPublicKey *pubk)
{
    SECKEYPublicKey *copyk;
    PRArenaPool *arena;
    
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    if (arena == NULL) {
	PORT_SetError (SEC_ERROR_NO_MEMORY);
	return NULL;
    }

    copyk = (SECKEYPublicKey *) PORT_ArenaZAlloc (arena, sizeof (SECKEYPublicKey));
    if (copyk != NULL) {
	SECStatus rv = SECSuccess;

	copyk->arena = arena;
	copyk->keyType = pubk->keyType;
	if (pubk->pkcs11Slot && 
			PK11_IsPermObject(pubk->pkcs11Slot,pubk->pkcs11ID)) {
	    copyk->pkcs11Slot = PK11_ReferenceSlot(pubk->pkcs11Slot);
	    copyk->pkcs11ID = pubk->pkcs11ID;
	} else {
	    copyk->pkcs11Slot = NULL;	/* go get own reference */
	    copyk->pkcs11ID = CK_INVALID_HANDLE;
	}
	switch (pubk->keyType) {
	  case rsaKey:
	    rv = SECITEM_CopyItem(arena, &copyk->u.rsa.modulus,
				  &pubk->u.rsa.modulus);
	    if (rv == SECSuccess) {
		rv = SECITEM_CopyItem (arena, &copyk->u.rsa.publicExponent,
				       &pubk->u.rsa.publicExponent);
		if (rv == SECSuccess)
		    return copyk;
	    }
	    break;
	  case dsaKey:
	    rv = SECITEM_CopyItem(arena, &copyk->u.dsa.publicValue,
				  &pubk->u.dsa.publicValue);
	    if (rv != SECSuccess) break;
	    rv = SECITEM_CopyItem(arena, &copyk->u.dsa.params.prime,
				  &pubk->u.dsa.params.prime);
	    if (rv != SECSuccess) break;
	    rv = SECITEM_CopyItem(arena, &copyk->u.dsa.params.subPrime,
				  &pubk->u.dsa.params.subPrime);
	    if (rv != SECSuccess) break;
	    rv = SECITEM_CopyItem(arena, &copyk->u.dsa.params.base,
				  &pubk->u.dsa.params.base);
	    break;
          case keaKey:
            rv = SECITEM_CopyItem(arena, &copyk->u.kea.publicValue,
                                  &pubk->u.kea.publicValue);
            if (rv != SECSuccess) break;
            rv = SECITEM_CopyItem(arena, &copyk->u.kea.params.hash,
                                  &pubk->u.kea.params.hash);
            break;
	  case fortezzaKey:
	    copyk->u.fortezza.KEAversion = pubk->u.fortezza.KEAversion;
	    copyk->u.fortezza.DSSversion = pubk->u.fortezza.DSSversion;
	    PORT_Memcpy(copyk->u.fortezza.KMID, pubk->u.fortezza.KMID,
			sizeof(pubk->u.fortezza.KMID));
	    rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.clearance, 
				  &pubk->u.fortezza.clearance);
	    if (rv != SECSuccess) break;
	    rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.KEApriviledge, 
				&pubk->u.fortezza.KEApriviledge);
	    if (rv != SECSuccess) break;
	    rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.DSSpriviledge, 
				&pubk->u.fortezza.DSSpriviledge);
	    if (rv != SECSuccess) break;
	    rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.KEAKey, 
				&pubk->u.fortezza.KEAKey);
	    if (rv != SECSuccess) break;
	    rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.DSSKey, 
				&pubk->u.fortezza.DSSKey);
	    if (rv != SECSuccess) break;
	    rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.params.prime, 
				  &pubk->u.fortezza.params.prime);
	    if (rv != SECSuccess) break;
	    rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.params.subPrime, 
				&pubk->u.fortezza.params.subPrime);
	    if (rv != SECSuccess) break;
	    rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.params.base, 
				&pubk->u.fortezza.params.base);
            if (rv != SECSuccess) break;
            rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.keaParams.prime, 
				  &pubk->u.fortezza.keaParams.prime);
	    if (rv != SECSuccess) break;
	    rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.keaParams.subPrime, 
				&pubk->u.fortezza.keaParams.subPrime);
	    if (rv != SECSuccess) break;
	    rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.keaParams.base, 
				&pubk->u.fortezza.keaParams.base);
	    break;
	  case dhKey:
            rv = SECITEM_CopyItem(arena,&copyk->u.dh.prime,&pubk->u.dh.prime);
	    if (rv != SECSuccess) break;
	    rv = SECITEM_CopyItem(arena,&copyk->u.dh.base,&pubk->u.dh.base);
	    if (rv != SECSuccess) break;
	    rv = SECITEM_CopyItem(arena, &copyk->u.dh.publicValue, 
				&pubk->u.dh.publicValue);
	    break;
#ifdef NSS_ENABLE_ECC
	  case ecKey:
	    copyk->u.ec.size = pubk->u.ec.size;
            rv = SECITEM_CopyItem(arena,&copyk->u.ec.DEREncodedParams,
		&pubk->u.ec.DEREncodedParams);
	    if (rv != SECSuccess) break;
            rv = SECITEM_CopyItem(arena,&copyk->u.ec.publicValue,
		&pubk->u.ec.publicValue);
	    break;
#endif /* NSS_ENABLE_ECC */
	  case nullKey:
	    return copyk;
	  default:
	    rv = SECFailure;
	    break;
	}
	if (rv == SECSuccess)
	    return copyk;

	SECKEY_DestroyPublicKey (copyk);
    } else {
	PORT_SetError (SEC_ERROR_NO_MEMORY);
    }

    PORT_FreeArena (arena, PR_FALSE);
    return NULL;
}


SECKEYPublicKey *
SECKEY_ConvertToPublicKey(SECKEYPrivateKey *privk)
{
    SECKEYPublicKey *pubk;
    PRArenaPool *arena;
    CERTCertificate *cert;
    SECStatus rv;

    /*
     * First try to look up the cert.
     */
    cert = PK11_GetCertFromPrivateKey(privk);
    if (cert) {
	pubk = CERT_ExtractPublicKey(cert);
	CERT_DestroyCertificate(cert);
	return pubk;
    }

    /* couldn't find the cert, build pub key by hand */
    arena = PORT_NewArena (DER_DEFAULT_CHUNKSIZE);
    if (arena == NULL) {
	PORT_SetError (SEC_ERROR_NO_MEMORY);
	return NULL;
    }
    pubk = (SECKEYPublicKey *)PORT_ArenaZAlloc(arena,
						   sizeof (SECKEYPublicKey));
    if (pubk == NULL) {
	PORT_FreeArena(arena,PR_FALSE);
	return NULL;
    }
    pubk->keyType = privk->keyType;
    pubk->pkcs11Slot = NULL;
    pubk->pkcs11ID = CK_INVALID_HANDLE;
    pubk->arena = arena;

    /*
     * fortezza is at the head of this switch, since we don't want to
     * allocate an arena... CERT_ExtractPublicKey will to that for us.
     */
    switch(privk->keyType) {
      case fortezzaKey:
      case nullKey:
      case dhKey:
      case dsaKey:
	/* Nothing to query, if the cert isn't there, we're done -- no way
	 * to get the public key */
	break;
      case rsaKey:
	rv = PK11_ReadAttribute(privk->pkcs11Slot,privk->pkcs11ID,
				CKA_MODULUS,arena,&pubk->u.rsa.modulus);
	if (rv != SECSuccess)  break;
	rv = PK11_ReadAttribute(privk->pkcs11Slot,privk->pkcs11ID,
			CKA_PUBLIC_EXPONENT,arena,&pubk->u.rsa.publicExponent);
	if (rv != SECSuccess)  break;
	return pubk;
	break;
    default:
	break;
    }

    PORT_FreeArena (arena, PR_FALSE);
    return NULL;
}

CERTSubjectPublicKeyInfo *
SECKEY_CreateSubjectPublicKeyInfo(SECKEYPublicKey *pubk)
{
    CERTSubjectPublicKeyInfo *spki;
    PRArenaPool *arena;
    SECItem params = { siBuffer, NULL, 0 };

    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    if (arena == NULL) {
	PORT_SetError(SEC_ERROR_NO_MEMORY);
	return NULL;
    }

    spki = (CERTSubjectPublicKeyInfo *) PORT_ArenaZAlloc(arena, sizeof (*spki));
    if (spki != NULL) {
	SECStatus rv;
	SECItem *rv_item;
	
	spki->arena = arena;
	switch(pubk->keyType) {
	  case rsaKey:
	    rv = SECOID_SetAlgorithmID(arena, &spki->algorithm,
				     SEC_OID_PKCS1_RSA_ENCRYPTION, 0);
	    if (rv == SECSuccess) {
		/*
		 * DER encode the public key into the subjectPublicKeyInfo.
		 */
		prepare_rsa_pub_key_for_asn1(pubk);
		rv_item = SEC_ASN1EncodeItem(arena, &spki->subjectPublicKey,
					     pubk, SECKEY_RSAPublicKeyTemplate);
		if (rv_item != NULL) {
		    /*
		     * The stored value is supposed to be a BIT_STRING,
		     * so convert the length.
		     */
		    spki->subjectPublicKey.len <<= 3;
		    /*
		     * We got a good one; return it.
		     */
		    return spki;
		}
	    }
	    break;
	  case dsaKey:
	    /* DER encode the params. */
	    prepare_pqg_params_for_asn1(&pubk->u.dsa.params);
	    rv_item = SEC_ASN1EncodeItem(arena, &params, &pubk->u.dsa.params,
					 SECKEY_PQGParamsTemplate);
	    if (rv_item != NULL) {
		rv = SECOID_SetAlgorithmID(arena, &spki->algorithm,
					   SEC_OID_ANSIX9_DSA_SIGNATURE,
					   &params);
		if (rv == SECSuccess) {
		    /*
		     * DER encode the public key into the subjectPublicKeyInfo.
		     */
		    prepare_dsa_pub_key_for_asn1(pubk);
		    rv_item = SEC_ASN1EncodeItem(arena, &spki->subjectPublicKey,
						 pubk,
						 SECKEY_DSAPublicKeyTemplate);
		    if (rv_item != NULL) {
			/*
			 * The stored value is supposed to be a BIT_STRING,
			 * so convert the length.
			 */
			spki->subjectPublicKey.len <<= 3;
			/*
			 * We got a good one; return it.
			 */
			return spki;
		    }
		}
	    }
	    SECITEM_FreeItem(&params, PR_FALSE);
	    break;
#ifdef NSS_ENABLE_ECC
	  case ecKey:
	    rv = SECITEM_CopyItem(arena, &params, 
				  &pubk->u.ec.DEREncodedParams);
	    if (rv != SECSuccess) break;

	    rv = SECOID_SetAlgorithmID(arena, &spki->algorithm,
				       SEC_OID_ANSIX962_EC_PUBLIC_KEY,
				       &params);
	    if (rv != SECSuccess) break;

	    rv = SECITEM_CopyItem(arena, &spki->subjectPublicKey,
				  &pubk->u.ec.publicValue);

	    if (rv == SECSuccess) {
	        /*
		 * The stored value is supposed to be a BIT_STRING,
		 * so convert the length.
		 */
	        spki->subjectPublicKey.len <<= 3;
		/*
		 * We got a good one; return it.
		 */
		return spki;
	    }
	    break;
#endif /* NSS_ENABLE_ECC */
	  case keaKey:
	  case dhKey: /* later... */

	  break;  
	  case fortezzaKey:
#ifdef notdef
	    /* encode the DSS parameters (PQG) */
	    rv = FortezzaBuildParams(&params,pubk);
	    if (rv != SECSuccess) break;

	    /* set the algorithm */
	    rv = SECOID_SetAlgorithmID(arena, &spki->algorithm,
				       SEC_OID_MISSI_KEA_DSS, &params);
	    PORT_Free(params.data);
	    if (rv == SECSuccess) {
		/*
		 * Encode the public key into the subjectPublicKeyInfo.
		 * Fortezza key material is not standard DER
		 */
		rv = FortezzaEncodeCertKey(arena,&spki->subjectPublicKey,pubk);
		if (rv == SECSuccess) {
		    /*
		     * The stored value is supposed to be a BIT_STRING,
		     * so convert the length.
		     */
		    spki->subjectPublicKey.len <<= 3;

		    /*
		     * We got a good one; return it.
		     */
		    return spki;
		}
	    }
#endif
	    break;
	  default:
	    break;
	}
    } else {
	PORT_SetError(SEC_ERROR_NO_MEMORY);
    }

    PORT_FreeArena(arena, PR_FALSE);
    return NULL;
}

void
SECKEY_DestroySubjectPublicKeyInfo(CERTSubjectPublicKeyInfo *spki)
{
    if (spki && spki->arena) {
	PORT_FreeArena(spki->arena, PR_FALSE);
    }
}

/*
 * this only works for RSA keys... need to do something
 * similiar to CERT_ExtractPublicKey for other key times.
 */
SECKEYPublicKey *
SECKEY_DecodeDERPublicKey(SECItem *pubkder)
{
    PRArenaPool *arena;
    SECKEYPublicKey *pubk;
    SECStatus rv;
    SECItem newPubkder;

    arena = PORT_NewArena (DER_DEFAULT_CHUNKSIZE);
    if (arena == NULL) {
	PORT_SetError (SEC_ERROR_NO_MEMORY);
	return NULL;
    }

    pubk = (SECKEYPublicKey *) PORT_ArenaZAlloc (arena, sizeof (SECKEYPublicKey));
    if (pubk != NULL) {
	pubk->arena = arena;
	pubk->pkcs11Slot = NULL;
	pubk->pkcs11ID = 0;
	prepare_rsa_pub_key_for_asn1(pubk);
        /* copy the DER into the arena, since Quick DER returns data that points
           into the DER input, which may get freed by the caller */
        rv = SECITEM_CopyItem(arena, &newPubkder, pubkder);
        if ( rv == SECSuccess ) {
	    rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_RSAPublicKeyTemplate,
				&newPubkder);
        }
	if (rv == SECSuccess)
	    return pubk;
	SECKEY_DestroyPublicKey (pubk);
    } else {
	PORT_SetError (SEC_ERROR_NO_MEMORY);
    }

    PORT_FreeArena (arena, PR_FALSE);
    return NULL;
}

/*
 * Decode a base64 ascii encoded DER encoded public key.
 */
SECKEYPublicKey *
SECKEY_ConvertAndDecodePublicKey(char *pubkstr)
{
    SECKEYPublicKey *pubk;
    SECStatus rv;
    SECItem der;

    rv = ATOB_ConvertAsciiToItem (&der, pubkstr);
    if (rv != SECSuccess)
	return NULL;

    pubk = SECKEY_DecodeDERPublicKey (&der);

    PORT_Free (der.data);
    return pubk;
}

SECItem *
SECKEY_EncodeDERSubjectPublicKeyInfo(SECKEYPublicKey *pubk)
{
    CERTSubjectPublicKeyInfo *spki=NULL;
    SECItem *spkiDER=NULL;

    /* get the subjectpublickeyinfo */
    spki = SECKEY_CreateSubjectPublicKeyInfo(pubk);
    if( spki == NULL ) {
	goto finish;
    }

    /* DER-encode the subjectpublickeyinfo */
    spkiDER = SEC_ASN1EncodeItem(NULL /*arena*/, NULL/*dest*/, spki,
					CERT_SubjectPublicKeyInfoTemplate);
finish:
    if (spki!=NULL) {
	SECKEY_DestroySubjectPublicKeyInfo(spki);
    }
    return spkiDER;
}


CERTSubjectPublicKeyInfo *
SECKEY_DecodeDERSubjectPublicKeyInfo(SECItem *spkider)
{
    PRArenaPool *arena;
    CERTSubjectPublicKeyInfo *spki;
    SECStatus rv;
    SECItem newSpkider;

    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    if (arena == NULL) {
	PORT_SetError(SEC_ERROR_NO_MEMORY);
	return NULL;
    }

    spki = (CERTSubjectPublicKeyInfo *)
		PORT_ArenaZAlloc(arena, sizeof (CERTSubjectPublicKeyInfo));
    if (spki != NULL) {
	spki->arena = arena;

        /* copy the DER into the arena, since Quick DER returns data that points
           into the DER input, which may get freed by the caller */
        rv = SECITEM_CopyItem(arena, &newSpkider, spkider);
        if ( rv == SECSuccess ) {
            rv = SEC_QuickDERDecodeItem(arena,spki,
				    CERT_SubjectPublicKeyInfoTemplate, &newSpkider);
        }
	if (rv == SECSuccess)
	    return spki;
	SECKEY_DestroySubjectPublicKeyInfo(spki);
    } else {
	PORT_SetError(SEC_ERROR_NO_MEMORY);
    }

    PORT_FreeArena(arena, PR_FALSE);
    return NULL;
}

/*
 * Decode a base64 ascii encoded DER encoded subject public key info.
 */
CERTSubjectPublicKeyInfo *
SECKEY_ConvertAndDecodeSubjectPublicKeyInfo(char *spkistr)
{
    CERTSubjectPublicKeyInfo *spki;
    SECStatus rv;
    SECItem der;

    rv = ATOB_ConvertAsciiToItem(&der, spkistr);
    if (rv != SECSuccess)
	return NULL;

    spki = SECKEY_DecodeDERSubjectPublicKeyInfo(&der);

    PORT_Free(der.data);
    return spki;
}

/*
 * Decode a base64 ascii encoded DER encoded public key and challenge
 * Verify digital signature and make sure challenge matches
 */
CERTSubjectPublicKeyInfo *
SECKEY_ConvertAndDecodePublicKeyAndChallenge(char *pkacstr, char *challenge,
								void *wincx)
{
    CERTSubjectPublicKeyInfo *spki = NULL;
    CERTPublicKeyAndChallenge pkac;
    SECStatus rv;
    SECItem signedItem;
    PRArenaPool *arena = NULL;
    CERTSignedData sd;
    SECItem sig;
    SECKEYPublicKey *pubKey = NULL;
    unsigned int len;
    
    signedItem.data = NULL;
    
    /* convert the base64 encoded data to binary */
    rv = ATOB_ConvertAsciiToItem(&signedItem, pkacstr);
    if (rv != SECSuccess) {
	goto loser;
    }

    /* create an arena */
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    if (arena == NULL) {
	goto loser;
    }

    /* decode the outer wrapping of signed data */
    PORT_Memset(&sd, 0, sizeof(CERTSignedData));
    rv = SEC_QuickDERDecodeItem(arena, &sd, CERT_SignedDataTemplate, &signedItem );
    if ( rv ) {
	goto loser;
    }

    /* decode the public key and challenge wrapper */
    PORT_Memset(&pkac, 0, sizeof(CERTPublicKeyAndChallenge));
    rv = SEC_QuickDERDecodeItem(arena, &pkac, CERT_PublicKeyAndChallengeTemplate, 
			    &sd.data);
    if ( rv ) {
	goto loser;
    }

    /* decode the subject public key info */
    spki = SECKEY_DecodeDERSubjectPublicKeyInfo(&pkac.spki);
    if ( spki == NULL ) {
	goto loser;
    }
    
    /* get the public key */
    pubKey = seckey_ExtractPublicKey(spki);
    if ( pubKey == NULL ) {
	goto loser;
    }

    /* check the signature */
    sig = sd.signature;
    DER_ConvertBitString(&sig);
    rv = VFY_VerifyData(sd.data.data, sd.data.len, pubKey, &sig,
			SECOID_GetAlgorithmTag(&(sd.signatureAlgorithm)), wincx);
    if ( rv != SECSuccess ) {
	goto loser;
    }
    
    /* check the challenge */
    if ( challenge ) {
	len = PORT_Strlen(challenge);
	/* length is right */
	if ( len != pkac.challenge.len ) {
	    goto loser;
	}
	/* actual data is right */
	if ( PORT_Memcmp(challenge, pkac.challenge.data, len) != 0 ) {
	    goto loser;
	}
    }
    goto done;

loser:
    /* make sure that we return null if we got an error */
    if ( spki ) {
	SECKEY_DestroySubjectPublicKeyInfo(spki);
    }
    spki = NULL;
    
done:
    if ( signedItem.data ) {
	PORT_Free(signedItem.data);
    }
    if ( arena ) {
	PORT_FreeArena(arena, PR_FALSE);
    }
    if ( pubKey ) {
	SECKEY_DestroyPublicKey(pubKey);
    }
    
    return spki;
}

void
SECKEY_DestroyPrivateKeyInfo(SECKEYPrivateKeyInfo *pvk,
			     PRBool freeit)
{
    PRArenaPool *poolp;

    if(pvk != NULL) {
	if(pvk->arena) {
	    poolp = pvk->arena;
	    /* zero structure since PORT_FreeArena does not support
	     * this yet.
	     */
	    PORT_Memset(pvk->privateKey.data, 0, pvk->privateKey.len);
	    PORT_Memset((char *)pvk, 0, sizeof(*pvk));
	    if(freeit == PR_TRUE) {
		PORT_FreeArena(poolp, PR_TRUE);
	    } else {
		pvk->arena = poolp;
	    }
	} else {
	    SECITEM_ZfreeItem(&pvk->version, PR_FALSE);
	    SECITEM_ZfreeItem(&pvk->privateKey, PR_FALSE);
	    SECOID_DestroyAlgorithmID(&pvk->algorithm, PR_FALSE);
	    PORT_Memset((char *)pvk, 0, sizeof(pvk));
	    if(freeit == PR_TRUE) {
		PORT_Free(pvk);
	    }
	}
    }
}

void
SECKEY_DestroyEncryptedPrivateKeyInfo(SECKEYEncryptedPrivateKeyInfo *epki,
				      PRBool freeit)
{
    PRArenaPool *poolp;

    if(epki != NULL) {
	if(epki->arena) {
	    poolp = epki->arena;
	    /* zero structure since PORT_FreeArena does not support
	     * this yet.
	     */
	    PORT_Memset(epki->encryptedData.data, 0, epki->encryptedData.len);
	    PORT_Memset((char *)epki, 0, sizeof(*epki));
	    if(freeit == PR_TRUE) {
		PORT_FreeArena(poolp, PR_TRUE);
	    } else {
		epki->arena = poolp;
	    }
	} else {
	    SECITEM_ZfreeItem(&epki->encryptedData, PR_FALSE);
	    SECOID_DestroyAlgorithmID(&epki->algorithm, PR_FALSE);
	    PORT_Memset((char *)epki, 0, sizeof(epki));
	    if(freeit == PR_TRUE) {
		PORT_Free(epki);
	    }
	}
    }
}

SECStatus
SECKEY_CopyPrivateKeyInfo(PRArenaPool *poolp,
			  SECKEYPrivateKeyInfo *to,
			  SECKEYPrivateKeyInfo *from)
{
    SECStatus rv = SECFailure;

    if((to == NULL) || (from == NULL)) {
	return SECFailure;
    }

    rv = SECOID_CopyAlgorithmID(poolp, &to->algorithm, &from->algorithm);
    if(rv != SECSuccess) {
	return SECFailure;
    }
    rv = SECITEM_CopyItem(poolp, &to->privateKey, &from->privateKey);
    if(rv != SECSuccess) {
	return SECFailure;
    }
    rv = SECITEM_CopyItem(poolp, &to->version, &from->version);

    return rv;
}

SECStatus
SECKEY_CopyEncryptedPrivateKeyInfo(PRArenaPool *poolp, 
				   SECKEYEncryptedPrivateKeyInfo *to,
				   SECKEYEncryptedPrivateKeyInfo *from)
{
    SECStatus rv = SECFailure;

    if((to == NULL) || (from == NULL)) {
	return SECFailure;
    }

    rv = SECOID_CopyAlgorithmID(poolp, &to->algorithm, &from->algorithm);
    if(rv != SECSuccess) {
	return SECFailure;
    }
    rv = SECITEM_CopyItem(poolp, &to->encryptedData, &from->encryptedData);

    return rv;
}

KeyType
SECKEY_GetPrivateKeyType(SECKEYPrivateKey *privKey)
{
   return privKey->keyType;
}

KeyType
SECKEY_GetPublicKeyType(SECKEYPublicKey *pubKey)
{
   return pubKey->keyType;
}

SECKEYPublicKey*
SECKEY_ImportDERPublicKey(SECItem *derKey, CK_KEY_TYPE type)
{
    SECKEYPublicKey *pubk = NULL;
    SECStatus rv = SECFailure;
    SECItem newDerKey;

    if (!derKey) {
        return NULL;
    } 

    pubk = PORT_ZNew(SECKEYPublicKey);
    if(pubk == NULL) {
        goto finish;
    }
    pubk->arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    if (NULL == pubk->arena) {
        goto finish;
    }
    rv = SECITEM_CopyItem(pubk->arena, &newDerKey, derKey);
    if (SECSuccess != rv) {
        goto finish;
    }

    pubk->pkcs11Slot = NULL;
    pubk->pkcs11ID = CK_INVALID_HANDLE;

    switch( type ) {
      case CKK_RSA:
	prepare_rsa_pub_key_for_asn1(pubk);
        rv = SEC_QuickDERDecodeItem(pubk->arena, pubk, SECKEY_RSAPublicKeyTemplate, &newDerKey);
        pubk->keyType = rsaKey;
        break;
      case CKK_DSA:
	prepare_dsa_pub_key_for_asn1(pubk);
        rv = SEC_QuickDERDecodeItem(pubk->arena, pubk, SECKEY_DSAPublicKeyTemplate, &newDerKey);
        pubk->keyType = dsaKey;
        break;
      case CKK_DH:
	prepare_dh_pub_key_for_asn1(pubk);
        rv = SEC_QuickDERDecodeItem(pubk->arena, pubk, SECKEY_DHPublicKeyTemplate, &newDerKey);
        pubk->keyType = dhKey;
        break;
      default:
        rv = SECFailure;
        break;
    }

finish:
    if( rv != SECSuccess && pubk != NULL) {
        if (pubk->arena) {
            PORT_FreeArena(pubk->arena, PR_TRUE);
        }
        PORT_Free(pubk);
        pubk = NULL;
    }
    return pubk;
}

SECKEYPrivateKeyList*
SECKEY_NewPrivateKeyList(void)
{
    PRArenaPool *arena = NULL;
    SECKEYPrivateKeyList *ret = NULL;

    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    if ( arena == NULL ) {
        goto loser;
    }

    ret = (SECKEYPrivateKeyList *)PORT_ArenaZAlloc(arena,
                sizeof(SECKEYPrivateKeyList));
    if ( ret == NULL ) {
        goto loser;
    }

    ret->arena = arena;

    PR_INIT_CLIST(&ret->list);

    return(ret);

loser:
    if ( arena != NULL ) {
        PORT_FreeArena(arena, PR_FALSE);
    }

    return(NULL);
}

void
SECKEY_DestroyPrivateKeyList(SECKEYPrivateKeyList *keys)
{
    while( !PR_CLIST_IS_EMPTY(&keys->list) ) {
        SECKEY_RemovePrivateKeyListNode(
            (SECKEYPrivateKeyListNode*)(PR_LIST_HEAD(&keys->list)) );
    }

    PORT_FreeArena(keys->arena, PR_FALSE);

    return;
}


void
SECKEY_RemovePrivateKeyListNode(SECKEYPrivateKeyListNode *node)
{
    PR_ASSERT(node->key);
    SECKEY_DestroyPrivateKey(node->key);
    node->key = NULL;
    PR_REMOVE_LINK(&node->links);
    return;

}

SECStatus
SECKEY_AddPrivateKeyToListTail( SECKEYPrivateKeyList *list,
                                SECKEYPrivateKey *key)
{
    SECKEYPrivateKeyListNode *node;

    node = (SECKEYPrivateKeyListNode *)PORT_ArenaZAlloc(list->arena,
                sizeof(SECKEYPrivateKeyListNode));
    if ( node == NULL ) {
        goto loser;
    }

    PR_INSERT_BEFORE(&node->links, &list->list);
    node->key = key;
    return(SECSuccess);

loser:
    return(SECFailure);
}


SECKEYPublicKeyList*
SECKEY_NewPublicKeyList(void)
{
    PRArenaPool *arena = NULL;
    SECKEYPublicKeyList *ret = NULL;

    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    if ( arena == NULL ) {
        goto loser;
    }

    ret = (SECKEYPublicKeyList *)PORT_ArenaZAlloc(arena,
                sizeof(SECKEYPublicKeyList));
    if ( ret == NULL ) {
        goto loser;
    }

    ret->arena = arena;

    PR_INIT_CLIST(&ret->list);

    return(ret);

loser:
    if ( arena != NULL ) {
        PORT_FreeArena(arena, PR_FALSE);
    }

    return(NULL);
}

void
SECKEY_DestroyPublicKeyList(SECKEYPublicKeyList *keys)
{
    while( !PR_CLIST_IS_EMPTY(&keys->list) ) {
        SECKEY_RemovePublicKeyListNode(
            (SECKEYPublicKeyListNode*)(PR_LIST_HEAD(&keys->list)) );
    }

    PORT_FreeArena(keys->arena, PR_FALSE);

    return;
}


void
SECKEY_RemovePublicKeyListNode(SECKEYPublicKeyListNode *node)
{
    PR_ASSERT(node->key);
    SECKEY_DestroyPublicKey(node->key);
    node->key = NULL;
    PR_REMOVE_LINK(&node->links);
    return;

}

SECStatus
SECKEY_AddPublicKeyToListTail( SECKEYPublicKeyList *list,
                                SECKEYPublicKey *key)
{
    SECKEYPublicKeyListNode *node;

    node = (SECKEYPublicKeyListNode *)PORT_ArenaZAlloc(list->arena,
                sizeof(SECKEYPublicKeyListNode));
    if ( node == NULL ) {
        goto loser;
    }

    PR_INSERT_BEFORE(&node->links, &list->list);
    node->key = key;
    return(SECSuccess);

loser:
    return(SECFailure);
}