aboutsummaryrefslogtreecommitdiff
path: root/src/share/classes/sun/security/pkcs11/P11KeyStore.java
blob: aee9542537d175f82da74f8d9dc1544cbec4fa8d (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
/*
 * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code 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
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package sun.security.pkcs11;

import java.math.BigInteger;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;

import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Set;

import java.security.*;
import java.security.KeyStore.*;

import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateException;

import java.security.interfaces.*;
import java.security.spec.*;

import javax.crypto.SecretKey;
import javax.crypto.interfaces.*;

import javax.security.auth.x500.X500Principal;
import javax.security.auth.login.LoginException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import sun.security.util.Debug;
import sun.security.util.DerValue;
import sun.security.util.ECUtil;

import sun.security.ec.ECParameters;

import sun.security.pkcs11.Secmod.*;
import static sun.security.pkcs11.P11Util.*;

import sun.security.pkcs11.wrapper.*;
import static sun.security.pkcs11.wrapper.PKCS11Constants.*;

import sun.security.rsa.RSAKeyFactory;

final class P11KeyStore extends KeyStoreSpi {

    private static final CK_ATTRIBUTE ATTR_CLASS_CERT =
                        new CK_ATTRIBUTE(CKA_CLASS, CKO_CERTIFICATE);
    private static final CK_ATTRIBUTE ATTR_CLASS_PKEY =
                        new CK_ATTRIBUTE(CKA_CLASS, CKO_PRIVATE_KEY);
    private static final CK_ATTRIBUTE ATTR_CLASS_SKEY =
                        new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY);

    private static final CK_ATTRIBUTE ATTR_X509_CERT_TYPE =
                        new CK_ATTRIBUTE(CKA_CERTIFICATE_TYPE, CKC_X_509);

    private static final CK_ATTRIBUTE ATTR_TOKEN_TRUE =
                        new CK_ATTRIBUTE(CKA_TOKEN, true);

    // XXX for testing purposes only
    //  - NSS doesn't support persistent secret keys
    //    (key type gets mangled if secret key is a token key)
    //  - if debug is turned on, then this is set to false
    private static CK_ATTRIBUTE ATTR_SKEY_TOKEN_TRUE = ATTR_TOKEN_TRUE;

    private static final CK_ATTRIBUTE ATTR_TRUSTED_TRUE =
                        new CK_ATTRIBUTE(CKA_TRUSTED, true);
    private static final CK_ATTRIBUTE ATTR_PRIVATE_TRUE =
                        new CK_ATTRIBUTE(CKA_PRIVATE, true);

    private static final long NO_HANDLE = -1;
    private static final long FINDOBJECTS_MAX = 100;
    private static final String ALIAS_SEP = "/";

    private static final boolean NSS_TEST = false;
    private static final Debug debug =
                        Debug.getInstance("pkcs11keystore");
    private static boolean CKA_TRUSTED_SUPPORTED = true;

    private final Token token;

    // If multiple certs are found to share the same CKA_LABEL
    // at load time (NSS-style keystore), then the keystore is read
    // and the unique keystore aliases are mapped to the entries.
    // However, write capabilities are disabled.
    private boolean writeDisabled = false;

    // Map of unique keystore aliases to entries in the token
    private HashMap<String, AliasInfo> aliasMap;

    // whether to use NSS Secmod info for trust attributes
    private final boolean useSecmodTrust;

    // if useSecmodTrust == true, which type of trust we are interested in
    private Secmod.TrustType nssTrustType;

    /**
     * The underlying token may contain multiple certs belonging to the
     * same "personality" (for example, a signing cert and encryption cert),
     * all sharing the same CKA_LABEL.  These must be resolved
     * into unique keystore aliases.
     *
     * In addition, private keys and certs may not have a CKA_LABEL.
     * It is assumed that a private key and corresponding certificate
     * share the same CKA_ID, and that the CKA_ID is unique across the token.
     * The CKA_ID may not be human-readable.
     * These pairs must be resolved into unique keystore aliases.
     *
     * Furthermore, secret keys are assumed to have a CKA_LABEL
     * unique across the entire token.
     *
     * When the KeyStore is loaded, instances of this class are
     * created to represent the private keys/secret keys/certs
     * that reside on the token.
     */
    private static class AliasInfo {

        // CKA_CLASS - entry type
        private CK_ATTRIBUTE type = null;

        // CKA_LABEL of cert and secret key
        private String label = null;

        // CKA_ID of the private key/cert pair
        private byte[] id = null;

        // CKA_TRUSTED - true if cert is trusted
        private boolean trusted = false;

        // either end-entity cert or trusted cert depending on 'type'
        private X509Certificate cert = null;

        // chain
        private X509Certificate chain[] = null;

        // true if CKA_ID for private key and cert match up
        private boolean matched = false;

        // SecretKeyEntry
        public AliasInfo(String label) {
            this.type = ATTR_CLASS_SKEY;
            this.label = label;
        }

        // PrivateKeyEntry
        public AliasInfo(String label,
                        byte[] id,
                        boolean trusted,
                        X509Certificate cert) {
            this.type = ATTR_CLASS_PKEY;
            this.label = label;
            this.id = id;
            this.trusted = trusted;
            this.cert = cert;
        }

        public String toString() {
            StringBuilder sb = new StringBuilder();
            if (type == ATTR_CLASS_PKEY) {
                sb.append("\ttype=[private key]\n");
            } else if (type == ATTR_CLASS_SKEY) {
                sb.append("\ttype=[secret key]\n");
            } else if (type == ATTR_CLASS_CERT) {
                sb.append("\ttype=[trusted cert]\n");
            }
            sb.append("\tlabel=[" + label + "]\n");
            if (id == null) {
                sb.append("\tid=[null]\n");
            } else {
                sb.append("\tid=" + P11KeyStore.getID(id) + "\n");
            }
            sb.append("\ttrusted=[" + trusted + "]\n");
            sb.append("\tmatched=[" + matched + "]\n");
            if (cert == null) {
                sb.append("\tcert=[null]\n");
            } else {
                sb.append("\tcert=[\tsubject: " +
                        cert.getSubjectX500Principal() +
                        "\n\t\tissuer: " +
                        cert.getIssuerX500Principal() +
                        "\n\t\tserialNum: " +
                        cert.getSerialNumber().toString() +
                        "]");
            }
            return sb.toString();
        }
    }

    /**
     * callback handler for passing password to Provider.login method
     */
    private static class PasswordCallbackHandler implements CallbackHandler {

        private char[] password;

        private PasswordCallbackHandler(char[] password) {
            if (password != null) {
                this.password = password.clone();
            }
        }

        public void handle(Callback[] callbacks)
                throws IOException, UnsupportedCallbackException {
            if (!(callbacks[0] instanceof PasswordCallback)) {
                throw new UnsupportedCallbackException(callbacks[0]);
            }
            PasswordCallback pc = (PasswordCallback)callbacks[0];
            pc.setPassword(password);  // this clones the password if not null
        }

        protected void finalize() throws Throwable {
            if (password != null) {
                Arrays.fill(password, ' ');
            }
            super.finalize();
        }
    }

    /**
     * getTokenObject return value.
     *
     * if object is not found, type is set to null.
     * otherwise, type is set to the requested type.
     */
    private static class THandle {
        private final long handle;              // token object handle
        private final CK_ATTRIBUTE type;        // CKA_CLASS

        private THandle(long handle, CK_ATTRIBUTE type) {
            this.handle = handle;
            this.type = type;
        }
    }

    P11KeyStore(Token token) {
        this.token = token;
        this.useSecmodTrust = token.provider.nssUseSecmodTrust;
    }

    /**
     * Returns the key associated with the given alias.
     * The key must have been associated with
     * the alias by a call to <code>setKeyEntry</code>,
     * or by a call to <code>setEntry</code> with a
     * <code>PrivateKeyEntry</code> or <code>SecretKeyEntry</code>.
     *
     * @param alias the alias name
     * @param password the password, which must be <code>null</code>
     *
     * @return the requested key, or null if the given alias does not exist
     * or does not identify a key-related entry.
     *
     * @exception NoSuchAlgorithmException if the algorithm for recovering the
     * key cannot be found
     * @exception UnrecoverableKeyException if the key cannot be recovered
     */
    public synchronized Key engineGetKey(String alias, char[] password)
                throws NoSuchAlgorithmException, UnrecoverableKeyException {

        token.ensureValid();
        if (password != null && !token.config.getKeyStoreCompatibilityMode()) {
            throw new NoSuchAlgorithmException("password must be null");
        }

        AliasInfo aliasInfo = aliasMap.get(alias);
        if (aliasInfo == null || aliasInfo.type == ATTR_CLASS_CERT) {
            return null;
        }

        Session session = null;
        try {
            session = token.getOpSession();

            if (aliasInfo.type == ATTR_CLASS_PKEY) {
                THandle h = getTokenObject(session,
                                        aliasInfo.type,
                                        aliasInfo.id,
                                        null);
                if (h.type == ATTR_CLASS_PKEY) {
                    return loadPkey(session, h.handle);
                }
            } else {
                THandle h = getTokenObject(session,
                                        ATTR_CLASS_SKEY,
                                        null,
                                        alias);
                if (h.type == ATTR_CLASS_SKEY) {
                    return loadSkey(session, h.handle);
                }
            }

            // did not find anything
            return null;
        } catch (PKCS11Exception | KeyStoreException e) {
            throw new ProviderException(e);
        } finally {
            token.releaseSession(session);
        }
    }

    /**
     * Returns the certificate chain associated with the given alias.
     * The certificate chain must have been associated with the alias
     * by a call to <code>setKeyEntry</code>,
     * or by a call to <code>setEntry</code> with a
     * <code>PrivateKeyEntry</code>.
     *
     * @param alias the alias name
     *
     * @return the certificate chain (ordered with the user's certificate first
     * and the root certificate authority last), or null if the given alias
     * does not exist or does not contain a certificate chain
     */
    public synchronized Certificate[] engineGetCertificateChain(String alias) {

        token.ensureValid();

        AliasInfo aliasInfo = aliasMap.get(alias);
        if (aliasInfo == null || aliasInfo.type != ATTR_CLASS_PKEY) {
            return null;
        }
        return aliasInfo.chain;
    }

    /**
     * Returns the certificate associated with the given alias.
     *
     * <p> If the given alias name identifies an entry
     * created by a call to <code>setCertificateEntry</code>,
     * or created by a call to <code>setEntry</code> with a
     * <code>TrustedCertificateEntry</code>,
     * then the trusted certificate contained in that entry is returned.
     *
     * <p> If the given alias name identifies an entry
     * created by a call to <code>setKeyEntry</code>,
     * or created by a call to <code>setEntry</code> with a
     * <code>PrivateKeyEntry</code>,
     * then the first element of the certificate chain in that entry
     * (if a chain exists) is returned.
     *
     * @param alias the alias name
     *
     * @return the certificate, or null if the given alias does not exist or
     * does not contain a certificate.
     */
    public synchronized Certificate engineGetCertificate(String alias) {
        token.ensureValid();

        AliasInfo aliasInfo = aliasMap.get(alias);
        if (aliasInfo == null) {
            return null;
        }
        return aliasInfo.cert;
    }

    /**
     * Returns the creation date of the entry identified by the given alias.
     *
     * @param alias the alias name
     *
     * @return the creation date of this entry, or null if the given alias does
     * not exist
     */
    public Date engineGetCreationDate(String alias) {
        token.ensureValid();
        throw new ProviderException(new UnsupportedOperationException());
    }

    /**
     * Assigns the given key to the given alias, protecting it with the given
     * password.
     *
     * <p>If the given key is of type <code>java.security.PrivateKey</code>,
     * it must be accompanied by a certificate chain certifying the
     * corresponding public key.
     *
     * <p>If the given alias already exists, the keystore information
     * associated with it is overridden by the given key (and possibly
     * certificate chain).
     *
     * @param alias the alias name
     * @param key the key to be associated with the alias
     * @param password the password to protect the key
     * @param chain the certificate chain for the corresponding public
     * key (only required if the given key is of type
     * <code>java.security.PrivateKey</code>).
     *
     * @exception KeyStoreException if the given key cannot be protected, or
     * this operation fails for some other reason
     */
    public synchronized void engineSetKeyEntry(String alias, Key key,
                                   char[] password,
                                   Certificate[] chain)
                throws KeyStoreException {

        token.ensureValid();
        checkWrite();

        if (!(key instanceof PrivateKey) && !(key instanceof SecretKey)) {
            throw new KeyStoreException("key must be PrivateKey or SecretKey");
        } else if (key instanceof PrivateKey && chain == null) {
            throw new KeyStoreException
                ("PrivateKey must be accompanied by non-null chain");
        } else if (key instanceof SecretKey && chain != null) {
            throw new KeyStoreException
                ("SecretKey must be accompanied by null chain");
        } else if (password != null &&
                    !token.config.getKeyStoreCompatibilityMode()) {
            throw new KeyStoreException("Password must be null");
        }

        KeyStore.Entry entry = null;
        try {
            if (key instanceof PrivateKey) {
                entry = new KeyStore.PrivateKeyEntry((PrivateKey)key, chain);
            } else if (key instanceof SecretKey) {
                entry = new KeyStore.SecretKeyEntry((SecretKey)key);
            }
        } catch (NullPointerException | IllegalArgumentException e) {
            throw new KeyStoreException(e);
        }
        engineSetEntry(alias, entry, new KeyStore.PasswordProtection(password));
    }

    /**
     * Assigns the given key (that has already been protected) to the given
     * alias.
     *
     * <p>If the protected key is of type
     * <code>java.security.PrivateKey</code>,
     * it must be accompanied by a certificate chain certifying the
     * corresponding public key.
     *
     * <p>If the given alias already exists, the keystore information
     * associated with it is overridden by the given key (and possibly
     * certificate chain).
     *
     * @param alias the alias name
     * @param key the key (in protected format) to be associated with the alias
     * @param chain the certificate chain for the corresponding public
     * key (only useful if the protected key is of type
     * <code>java.security.PrivateKey</code>).
     *
     * @exception KeyStoreException if this operation fails.
     */
    public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain)
                throws KeyStoreException {
        token.ensureValid();
        throw new ProviderException(new UnsupportedOperationException());
    }

    /**
     * Assigns the given certificate to the given alias.
     *
     * <p> If the given alias identifies an existing entry
     * created by a call to <code>setCertificateEntry</code>,
     * or created by a call to <code>setEntry</code> with a
     * <code>TrustedCertificateEntry</code>,
     * the trusted certificate in the existing entry
     * is overridden by the given certificate.
     *
     * @param alias the alias name
     * @param cert the certificate
     *
     * @exception KeyStoreException if the given alias already exists and does
     * not identify an entry containing a trusted certificate,
     * or this operation fails for some other reason.
     */
    public synchronized void engineSetCertificateEntry
        (String alias, Certificate cert) throws KeyStoreException {

        token.ensureValid();
        checkWrite();

        if (cert == null) {
            throw new KeyStoreException("invalid null certificate");
        }

        KeyStore.Entry entry = null;
        entry = new KeyStore.TrustedCertificateEntry(cert);
        engineSetEntry(alias, entry, null);
    }

    /**
     * Deletes the entry identified by the given alias from this keystore.
     *
     * @param alias the alias name
     *
     * @exception KeyStoreException if the entry cannot be removed.
     */
    public synchronized void engineDeleteEntry(String alias)
                throws KeyStoreException {
        token.ensureValid();

        if (token.isWriteProtected()) {
            throw new KeyStoreException("token write-protected");
        }
        checkWrite();
        deleteEntry(alias);
    }

    /**
     * XXX - not sure whether to keep this
     */
    private boolean deleteEntry(String alias) throws KeyStoreException {
        AliasInfo aliasInfo = aliasMap.get(alias);
        if (aliasInfo != null) {

            aliasMap.remove(alias);

            try {
                if (aliasInfo.type == ATTR_CLASS_CERT) {
                    // trusted certificate entry
                    return destroyCert(aliasInfo.id);
                } else if (aliasInfo.type == ATTR_CLASS_PKEY) {
                    // private key entry
                    return destroyPkey(aliasInfo.id) &&
                                destroyChain(aliasInfo.id);
                } else if (aliasInfo.type == ATTR_CLASS_SKEY) {
                    // secret key entry
                    return destroySkey(alias);
                } else {
                    throw new KeyStoreException("unexpected entry type");
                }
            } catch (PKCS11Exception | CertificateException e) {
                throw new KeyStoreException(e);
            }
        }
        return false;
    }

    /**
     * Lists all the alias names of this keystore.
     *
     * @return enumeration of the alias names
     */
    public synchronized Enumeration<String> engineAliases() {
        token.ensureValid();

        // don't want returned enumeration to iterate off actual keySet -
        // otherwise applications that iterate and modify the keystore
        // may run into concurrent modification problems
        return Collections.enumeration(new HashSet<String>(aliasMap.keySet()));
    }

    /**
     * Checks if the given alias exists in this keystore.
     *
     * @param alias the alias name
     *
     * @return true if the alias exists, false otherwise
     */
    public synchronized boolean engineContainsAlias(String alias) {
        token.ensureValid();
        return aliasMap.containsKey(alias);
    }

    /**
     * Retrieves the number of entries in this keystore.
     *
     * @return the number of entries in this keystore
     */
    public synchronized int engineSize() {
        token.ensureValid();
        return aliasMap.size();
    }

    /**
     * Returns true if the entry identified by the given alias
     * was created by a call to <code>setKeyEntry</code>,
     * or created by a call to <code>setEntry</code> with a
     * <code>PrivateKeyEntry</code> or a <code>SecretKeyEntry</code>.
     *
     * @param alias the alias for the keystore entry to be checked
     *
     * @return true if the entry identified by the given alias is a
     * key-related, false otherwise.
     */
    public synchronized boolean engineIsKeyEntry(String alias) {
        token.ensureValid();

        AliasInfo aliasInfo = aliasMap.get(alias);
        if (aliasInfo == null || aliasInfo.type == ATTR_CLASS_CERT) {
            return false;
        }
        return true;
    }

    /**
     * Returns true if the entry identified by the given alias
     * was created by a call to <code>setCertificateEntry</code>,
     * or created by a call to <code>setEntry</code> with a
     * <code>TrustedCertificateEntry</code>.
     *
     * @param alias the alias for the keystore entry to be checked
     *
     * @return true if the entry identified by the given alias contains a
     * trusted certificate, false otherwise.
     */
    public synchronized boolean engineIsCertificateEntry(String alias) {
        token.ensureValid();

        AliasInfo aliasInfo = aliasMap.get(alias);
        if (aliasInfo == null || aliasInfo.type != ATTR_CLASS_CERT) {
            return false;
        }
        return true;
    }

    /**
     * Returns the (alias) name of the first keystore entry whose certificate
     * matches the given certificate.
     *
     * <p>This method attempts to match the given certificate with each
     * keystore entry. If the entry being considered was
     * created by a call to <code>setCertificateEntry</code>,
     * or created by a call to <code>setEntry</code> with a
     * <code>TrustedCertificateEntry</code>,
     * then the given certificate is compared to that entry's certificate.
     *
     * <p> If the entry being considered was
     * created by a call to <code>setKeyEntry</code>,
     * or created by a call to <code>setEntry</code> with a
     * <code>PrivateKeyEntry</code>,
     * then the given certificate is compared to the first
     * element of that entry's certificate chain.
     *
     * @param cert the certificate to match with.
     *
     * @return the alias name of the first entry with matching certificate,
     * or null if no such entry exists in this keystore.
     */
    public synchronized String engineGetCertificateAlias(Certificate cert) {
        token.ensureValid();
        Enumeration<String> e = engineAliases();
        while (e.hasMoreElements()) {
            String alias = e.nextElement();
            Certificate tokenCert = engineGetCertificate(alias);
            if (tokenCert != null && tokenCert.equals(cert)) {
                return alias;
            }
        }
        return null;
    }

    /**
     * engineStore currently is a No-op.
     * Entries are stored to the token during engineSetEntry
     *
     * @param stream this must be <code>null</code>
     * @param password this must be <code>null</code>
     */
    public synchronized void engineStore(OutputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException {
        token.ensureValid();
        if (stream != null && !token.config.getKeyStoreCompatibilityMode()) {
            throw new IOException("output stream must be null");
        }

        if (password != null && !token.config.getKeyStoreCompatibilityMode()) {
            throw new IOException("password must be null");
        }
    }

    /**
     * engineStore currently is a No-op.
     * Entries are stored to the token during engineSetEntry
     *
     * @param param this must be <code>null</code>
     *
     * @exception IllegalArgumentException if the given
     *          <code>KeyStore.LoadStoreParameter</code>
     *          input is not <code>null</code>
     */
    public synchronized void engineStore(KeyStore.LoadStoreParameter param)
        throws IOException, NoSuchAlgorithmException, CertificateException {
        token.ensureValid();
        if (param != null) {
            throw new IllegalArgumentException
                ("LoadStoreParameter must be null");
        }
    }

    /**
     * Loads the keystore.
     *
     * @param stream the input stream, which must be <code>null</code>
     * @param password the password used to unlock the keystore,
     *          or <code>null</code> if the token supports a
     *          CKF_PROTECTED_AUTHENTICATION_PATH
     *
     * @exception IOException if the given <code>stream</code> is not
     *          <code>null</code>, if the token supports a
     *          CKF_PROTECTED_AUTHENTICATION_PATH and a non-null
     *          password is given, of if the token login operation failed
     */
    public synchronized void engineLoad(InputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException {

        token.ensureValid();

        if (NSS_TEST) {
            ATTR_SKEY_TOKEN_TRUE = new CK_ATTRIBUTE(CKA_TOKEN, false);
        }

        if (stream != null && !token.config.getKeyStoreCompatibilityMode()) {
            throw new IOException("input stream must be null");
        }

        if (useSecmodTrust) {
            nssTrustType = Secmod.TrustType.ALL;
        }

        try {
            if (password == null) {
                login(null);
            } else {
                login(new PasswordCallbackHandler(password));
            }
        } catch(LoginException e) {
            Throwable cause = e.getCause();
            if (cause instanceof PKCS11Exception) {
                PKCS11Exception pe = (PKCS11Exception) cause;
                if (pe.getErrorCode() == CKR_PIN_INCORRECT) {
                    // if password is wrong, the cause of the IOException
                    // should be an UnrecoverableKeyException
                    throw new IOException("load failed",
                            new UnrecoverableKeyException().initCause(e));
                }
            }
            throw new IOException("load failed", e);
        }

        try {
            if (mapLabels() == true) {
                // CKA_LABELs are shared by multiple certs
                writeDisabled = true;
            }
            if (debug != null) {
                dumpTokenMap();
            }
        } catch (KeyStoreException | PKCS11Exception e) {
            throw new IOException("load failed", e);
        }
    }

    /**
     * Loads the keystore using the given
     * <code>KeyStore.LoadStoreParameter</code>.
     *
     * <p> The <code>LoadStoreParameter.getProtectionParameter()</code>
     * method is expected to return a <code>KeyStore.PasswordProtection</code>
     * object.  The password is retrieved from that object and used
     * to unlock the PKCS#11 token.
     *
     * <p> If the token supports a CKF_PROTECTED_AUTHENTICATION_PATH
     * then the provided password must be <code>null</code>.
     *
     * @param param the <code>KeyStore.LoadStoreParameter</code>
     *
     * @exception IllegalArgumentException if the given
     *          <code>KeyStore.LoadStoreParameter</code> is <code>null</code>,
     *          or if that parameter returns a <code>null</code>
     *          <code>ProtectionParameter</code> object.
     *          input is not recognized
     * @exception IOException if the token supports a
     *          CKF_PROTECTED_AUTHENTICATION_PATH and the provided password
     *          is non-null, or if the token login operation fails
     */
    public synchronized void engineLoad(KeyStore.LoadStoreParameter param)
                throws IOException, NoSuchAlgorithmException,
                CertificateException {

        token.ensureValid();

        if (NSS_TEST) {
            ATTR_SKEY_TOKEN_TRUE = new CK_ATTRIBUTE(CKA_TOKEN, false);
        }

        // if caller wants to pass a NULL password,
        // force it to pass a non-NULL PasswordProtection that returns
        // a NULL password

        if (param == null) {
            throw new IllegalArgumentException
                        ("invalid null LoadStoreParameter");
        }
        if (useSecmodTrust) {
            if (param instanceof Secmod.KeyStoreLoadParameter) {
                nssTrustType = ((Secmod.KeyStoreLoadParameter)param).getTrustType();
            } else {
                nssTrustType = Secmod.TrustType.ALL;
            }
        }

        CallbackHandler handler;
        KeyStore.ProtectionParameter pp = param.getProtectionParameter();
        if (pp instanceof PasswordProtection) {
            char[] password = ((PasswordProtection)pp).getPassword();
            if (password == null) {
                handler = null;
            } else {
                handler = new PasswordCallbackHandler(password);
            }
        } else if (pp instanceof CallbackHandlerProtection) {
            handler = ((CallbackHandlerProtection)pp).getCallbackHandler();
        } else {
            throw new IllegalArgumentException
                        ("ProtectionParameter must be either " +
                        "PasswordProtection or CallbackHandlerProtection");
        }

        try {
            login(handler);
            if (mapLabels() == true) {
                // CKA_LABELs are shared by multiple certs
                writeDisabled = true;
            }
            if (debug != null) {
                dumpTokenMap();
            }
        } catch (LoginException | KeyStoreException | PKCS11Exception e) {
            throw new IOException("load failed", e);
        }
    }

    private void login(CallbackHandler handler) throws LoginException {
        if ((token.tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) == 0) {
            token.provider.login(null, handler);
        } else {
            // token supports protected authentication path
            // (external pin-pad, for example)
            if (handler != null &&
                !token.config.getKeyStoreCompatibilityMode()) {
                throw new LoginException("can not specify password if token " +
                                "supports protected authentication path");
            }

            // must rely on application-set or default handler
            // if one is necessary
            token.provider.login(null, null);
        }
    }

    /**
     * Get a <code>KeyStore.Entry</code> for the specified alias
     *
     * @param alias get the <code>KeyStore.Entry</code> for this alias
     * @param protParam this must be <code>null</code>
     *
     * @return the <code>KeyStore.Entry</code> for the specified alias,
     *          or <code>null</code> if there is no such entry
     *
     * @exception KeyStoreException if the operation failed
     * @exception NoSuchAlgorithmException if the algorithm for recovering the
     *          entry cannot be found
     * @exception UnrecoverableEntryException if the specified
     *          <code>protParam</code> were insufficient or invalid
     *
     * @since 1.5
     */
    public synchronized KeyStore.Entry engineGetEntry(String alias,
                        KeyStore.ProtectionParameter protParam)
                throws KeyStoreException, NoSuchAlgorithmException,
                UnrecoverableEntryException {

        token.ensureValid();

        if (protParam != null &&
            protParam instanceof KeyStore.PasswordProtection &&
            ((KeyStore.PasswordProtection)protParam).getPassword() != null &&
            !token.config.getKeyStoreCompatibilityMode()) {
            throw new KeyStoreException("ProtectionParameter must be null");
        }

        AliasInfo aliasInfo = aliasMap.get(alias);
        if (aliasInfo == null) {
            if (debug != null) {
                debug.println("engineGetEntry did not find alias [" +
                        alias +
                        "] in map");
            }
            return null;
        }

        Session session = null;
        try {
            session = token.getOpSession();

            if (aliasInfo.type == ATTR_CLASS_CERT) {
                // trusted certificate entry
                if (debug != null) {
                    debug.println("engineGetEntry found trusted cert entry");
                }
                return new KeyStore.TrustedCertificateEntry(aliasInfo.cert);
            } else if (aliasInfo.type == ATTR_CLASS_SKEY) {
                // secret key entry
                if (debug != null) {
                    debug.println("engineGetEntry found secret key entry");
                }

                THandle h = getTokenObject
                        (session, ATTR_CLASS_SKEY, null, aliasInfo.label);
                if (h.type != ATTR_CLASS_SKEY) {
                    throw new KeyStoreException
                        ("expected but could not find secret key");
                } else {
                    SecretKey skey = loadSkey(session, h.handle);
                    return new KeyStore.SecretKeyEntry(skey);
                }
            } else {
                // private key entry
                if (debug != null) {
                    debug.println("engineGetEntry found private key entry");
                }

                THandle h = getTokenObject
                        (session, ATTR_CLASS_PKEY, aliasInfo.id, null);
                if (h.type != ATTR_CLASS_PKEY) {
                    throw new KeyStoreException
                        ("expected but could not find private key");
                } else {
                    PrivateKey pkey = loadPkey(session, h.handle);
                    Certificate[] chain = aliasInfo.chain;
                    if ((pkey != null) && (chain != null)) {
                        return new KeyStore.PrivateKeyEntry(pkey, chain);
                    } else {
                        if (debug != null) {
                            debug.println
                                ("engineGetEntry got null cert chain or private key");
                        }
                    }
                }
            }
            return null;
        } catch (PKCS11Exception pe) {
            throw new KeyStoreException(pe);
        } finally {
            token.releaseSession(session);
        }
    }

    /**
     * Save a <code>KeyStore.Entry</code> under the specified alias.
     *
     * <p> If an entry already exists for the specified alias,
     * it is overridden.
     *
     * <p> This KeyStore implementation only supports the standard
     * entry types, and only supports X509Certificates in
     * TrustedCertificateEntries.  Also, this implementation does not support
     * protecting entries using a different password
     * from the one used for token login.
     *
     * <p> Entries are immediately stored on the token.
     *
     * @param alias save the <code>KeyStore.Entry</code> under this alias
     * @param entry the <code>Entry</code> to save
     * @param protParam this must be <code>null</code>
     *
     * @exception KeyStoreException if this operation fails
     *
     * @since 1.5
     */
    public synchronized void engineSetEntry(String alias, KeyStore.Entry entry,
                        KeyStore.ProtectionParameter protParam)
                throws KeyStoreException {

        token.ensureValid();
        checkWrite();

        if (protParam != null &&
            protParam instanceof KeyStore.PasswordProtection &&
            ((KeyStore.PasswordProtection)protParam).getPassword() != null &&
            !token.config.getKeyStoreCompatibilityMode()) {
            throw new KeyStoreException(new UnsupportedOperationException
                                ("ProtectionParameter must be null"));
        }

        if (token.isWriteProtected()) {
            throw new KeyStoreException("token write-protected");
        }

        if (entry instanceof KeyStore.TrustedCertificateEntry) {

            if (useSecmodTrust == false) {
                // PKCS #11 does not allow app to modify trusted certs -
                throw new KeyStoreException(new UnsupportedOperationException
                                    ("trusted certificates may only be set by " +
                                    "token initialization application"));
            }
            Module module = token.provider.nssModule;
            if ((module.type != ModuleType.KEYSTORE) && (module.type != ModuleType.FIPS)) {
                // XXX allow TRUSTANCHOR module
                throw new KeyStoreException("Trusted certificates can only be "
                    + "added to the NSS KeyStore module");
            }
            Certificate cert = ((TrustedCertificateEntry)entry).getTrustedCertificate();
            if (cert instanceof X509Certificate == false) {
                throw new KeyStoreException("Certificate must be an X509Certificate");
            }
            X509Certificate xcert = (X509Certificate)cert;
            AliasInfo info = aliasMap.get(alias);
            if (info != null) {
                // XXX try to update
                deleteEntry(alias);
            }
            try {
                storeCert(alias, xcert);
                module.setTrust(token, xcert);
                mapLabels();
            } catch (PKCS11Exception | CertificateException e) {
                throw new KeyStoreException(e);
            }

        } else {

            if (entry instanceof KeyStore.PrivateKeyEntry) {

                PrivateKey key =
                        ((KeyStore.PrivateKeyEntry)entry).getPrivateKey();
                if (!(key instanceof P11Key) &&
                    !(key instanceof RSAPrivateKey) &&
                    !(key instanceof DSAPrivateKey) &&
                    !(key instanceof DHPrivateKey) &&
                    !(key instanceof ECPrivateKey)) {
                    throw new KeyStoreException("unsupported key type: " +
                                                key.getClass().getName());
                }

                // only support X509Certificate chains
                Certificate[] chain =
                    ((KeyStore.PrivateKeyEntry)entry).getCertificateChain();
                if (!(chain instanceof X509Certificate[])) {
                    throw new KeyStoreException
                        (new UnsupportedOperationException
                                ("unsupported certificate array type: " +
                                chain.getClass().getName()));
                }

                try {
                    boolean updatedAlias = false;
                    Set<String> aliases = aliasMap.keySet();
                    for (String oldAlias : aliases) {

                        // see if there's an existing entry with the same info

                        AliasInfo aliasInfo = aliasMap.get(oldAlias);
                        if (aliasInfo.type == ATTR_CLASS_PKEY &&
                            aliasInfo.cert.getPublicKey().equals
                                        (chain[0].getPublicKey())) {

                            // found existing entry -
                            // caller is renaming entry or updating cert chain
                            //
                            // set new CKA_LABEL/CKA_ID
                            // and update certs if necessary

                            updatePkey(alias,
                                        aliasInfo.id,
                                        (X509Certificate[])chain,
                                        !aliasInfo.cert.equals(chain[0]));
                            updatedAlias = true;
                            break;
                        }
                    }

                    if (!updatedAlias) {
                        // caller adding new entry
                        engineDeleteEntry(alias);
                        storePkey(alias, (KeyStore.PrivateKeyEntry)entry);
                    }

                } catch (PKCS11Exception | CertificateException pe) {
                    throw new KeyStoreException(pe);
                }

            } else if (entry instanceof KeyStore.SecretKeyEntry) {

                KeyStore.SecretKeyEntry ske = (KeyStore.SecretKeyEntry)entry;
                SecretKey skey = ske.getSecretKey();

                try {
                    // first check if the key already exists
                    AliasInfo aliasInfo = aliasMap.get(alias);

                    if (aliasInfo != null) {
                        engineDeleteEntry(alias);
                    }
                    storeSkey(alias, ske);

                } catch (PKCS11Exception pe) {
                    throw new KeyStoreException(pe);
                }

            } else {
                throw new KeyStoreException(new UnsupportedOperationException
                    ("unsupported entry type: " + entry.getClass().getName()));
            }

            try {

                // XXX  NSS does not write out the CKA_ID we pass to them
                //
                // therefore we must re-map labels
                // (can not simply update aliasMap)

                mapLabels();
                if (debug != null) {
                    dumpTokenMap();
                }
            } catch (PKCS11Exception | CertificateException pe) {
                throw new KeyStoreException(pe);
            }
        }

        if (debug != null) {
            debug.println
                ("engineSetEntry added new entry for [" +
                alias +
                "] to token");
        }
    }

    /**
     * Determines if the keystore <code>Entry</code> for the specified
     * <code>alias</code> is an instance or subclass of the specified
     * <code>entryClass</code>.
     *
     * @param alias the alias name
     * @param entryClass the entry class
     *
     * @return true if the keystore <code>Entry</code> for the specified
     *          <code>alias</code> is an instance or subclass of the
     *          specified <code>entryClass</code>, false otherwise
     */
    public synchronized boolean engineEntryInstanceOf
                (String alias, Class<? extends KeyStore.Entry> entryClass) {
        token.ensureValid();
        return super.engineEntryInstanceOf(alias, entryClass);
    }

    private X509Certificate loadCert(Session session, long oHandle)
                throws PKCS11Exception, CertificateException {

        CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[]
                        { new CK_ATTRIBUTE(CKA_VALUE) };
        token.p11.C_GetAttributeValue(session.id(), oHandle, attrs);

        byte[] bytes = attrs[0].getByteArray();
        if (bytes == null) {
            throw new CertificateException
                        ("unexpectedly retrieved null byte array");
        }
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        return (X509Certificate)cf.generateCertificate
                        (new ByteArrayInputStream(bytes));
    }

    private X509Certificate[] loadChain(Session session,
                                        X509Certificate endCert)
                throws PKCS11Exception, CertificateException {

        ArrayList<X509Certificate> lChain = null;

        if (endCert.getSubjectX500Principal().equals
            (endCert.getIssuerX500Principal())) {
            // self signed
            return new X509Certificate[] { endCert };
        } else {
            lChain = new ArrayList<X509Certificate>();
            lChain.add(endCert);
        }

        // try loading remaining certs in chain by following
        // issuer->subject links

        X509Certificate next = endCert;
        while (true) {
            CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {
                        ATTR_TOKEN_TRUE,
                        ATTR_CLASS_CERT,
                        new CK_ATTRIBUTE(CKA_SUBJECT,
                                next.getIssuerX500Principal().getEncoded()) };
            long[] ch = findObjects(session, attrs);

            if (ch == null || ch.length == 0) {
                // done
                break;
            } else {
                // if more than one found, use first
                if (debug != null && ch.length > 1) {
                    debug.println("engineGetEntry found " +
                                ch.length +
                                " certificate entries for subject [" +
                                next.getIssuerX500Principal().toString() +
                                "] in token - using first entry");
                }

                next = loadCert(session, ch[0]);
                lChain.add(next);
                if (next.getSubjectX500Principal().equals
                    (next.getIssuerX500Principal())) {
                    // self signed
                    break;
                }
            }
        }

        return lChain.toArray(new X509Certificate[lChain.size()]);
    }

    private SecretKey loadSkey(Session session, long oHandle)
                throws PKCS11Exception {

        CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {
                        new CK_ATTRIBUTE(CKA_KEY_TYPE) };
        token.p11.C_GetAttributeValue(session.id(), oHandle, attrs);
        long kType = attrs[0].getLong();

        String keyType = null;
        int keyLength = -1;

        // XXX NSS mangles the stored key type for secret key token objects

        if (kType == CKK_DES || kType == CKK_DES3) {
            if (kType == CKK_DES) {
                keyType = "DES";
                keyLength = 64;
            } else if (kType == CKK_DES3) {
                keyType = "DESede";
                keyLength = 192;
            }
        } else {
            if (kType == CKK_AES) {
                keyType = "AES";
            } else if (kType == CKK_BLOWFISH) {
                keyType = "Blowfish";
            } else if (kType == CKK_RC4) {
                keyType = "ARCFOUR";
            } else {
                if (debug != null) {
                    debug.println("unknown key type [" +
                                kType +
                                "] - using 'Generic Secret'");
                }
                keyType = "Generic Secret";
            }

            // XXX NSS problem CKR_ATTRIBUTE_TYPE_INVALID?
            if (NSS_TEST) {
                keyLength = 128;
            } else {
                attrs = new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_VALUE_LEN) };
                token.p11.C_GetAttributeValue(session.id(), oHandle, attrs);
                keyLength = (int)attrs[0].getLong();
            }
        }

        return P11Key.secretKey(session, oHandle, keyType, keyLength, null);
    }

    private PrivateKey loadPkey(Session session, long oHandle)
        throws PKCS11Exception, KeyStoreException {

        CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {
                        new CK_ATTRIBUTE(CKA_KEY_TYPE) };
        token.p11.C_GetAttributeValue(session.id(), oHandle, attrs);
        long kType = attrs[0].getLong();
        String keyType = null;
        int keyLength = 0;

        if (kType == CKK_RSA) {

            keyType = "RSA";

            attrs = new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_MODULUS) };
            token.p11.C_GetAttributeValue(session.id(), oHandle, attrs);
            BigInteger modulus = attrs[0].getBigInteger();
            keyLength = modulus.bitLength();

            // This check will combine our "don't care" values here
            // with the system-wide min/max values.
            try {
                RSAKeyFactory.checkKeyLengths(keyLength, null,
                    -1, Integer.MAX_VALUE);
            } catch (InvalidKeyException e) {
                throw new KeyStoreException(e.getMessage());
            }

            return P11Key.privateKey(session,
                                oHandle,
                                keyType,
                                keyLength,
                                null);

        } else if (kType == CKK_DSA) {

            keyType = "DSA";

            attrs = new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_PRIME) };
            token.p11.C_GetAttributeValue(session.id(), oHandle, attrs);
            BigInteger prime = attrs[0].getBigInteger();
            keyLength = prime.bitLength();

            return P11Key.privateKey(session,
                                oHandle,
                                keyType,
                                keyLength,
                                null);

        } else if (kType == CKK_DH) {

            keyType = "DH";

            attrs = new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_PRIME) };
            token.p11.C_GetAttributeValue(session.id(), oHandle, attrs);
            BigInteger prime = attrs[0].getBigInteger();
            keyLength = prime.bitLength();

            return P11Key.privateKey(session,
                                oHandle,
                                keyType,
                                keyLength,
                                null);

        } else if (kType == CKK_EC) {

            attrs = new CK_ATTRIBUTE[] {
                new CK_ATTRIBUTE(CKA_EC_PARAMS),
            };
            token.p11.C_GetAttributeValue(session.id(), oHandle, attrs);
            byte[] encodedParams = attrs[0].getByteArray();
            try {
                ECParameterSpec params =
                    ECUtil.getECParameterSpec(null, encodedParams);
                keyLength = params.getCurve().getField().getFieldSize();
            } catch (IOException e) {
                // we do not want to accept key with unsupported parameters
                throw new KeyStoreException("Unsupported parameters", e);
            }

            return P11Key.privateKey(session, oHandle, "EC", keyLength, null);

        } else {
            if (debug != null) {
                debug.println("unknown key type [" + kType + "]");
            }
            throw new KeyStoreException("unknown key type");
        }
    }


    /**
     * XXX  On ibutton, when you C_SetAttribute(CKA_ID) for a private key
     *      it not only changes the CKA_ID of the private key,
     *      it changes the CKA_ID of the corresponding cert too.
     *      And vice versa.
     *
     * XXX  On ibutton, CKR_DEVICE_ERROR if you C_SetAttribute(CKA_ID)
     *      for a private key, and then try to delete the corresponding cert.
     *      So this code reverses the order.
     *      After the cert is first destroyed (if necessary),
     *      then the CKA_ID of the private key can be changed successfully.
     *
     * @param replaceCert if true, then caller is updating alias info for
     *                  existing cert (only update CKA_ID/CKA_LABEL).
     *                  if false, then caller is updating cert chain
     *                  (delete old end cert and add new chain).
     */
    private void updatePkey(String alias,
                        byte[] cka_id,
                        X509Certificate[] chain,
                        boolean replaceCert) throws
                KeyStoreException, CertificateException, PKCS11Exception {

        // XXX
        //
        // always set replaceCert to true
        //
        // NSS does not allow resetting of CKA_LABEL on an existing cert
        // (C_SetAttribute call succeeds, but is ignored)

        replaceCert = true;

        Session session = null;
        try {
            session = token.getOpSession();

            // first get private key object handle and hang onto it

            THandle h = getTokenObject(session, ATTR_CLASS_PKEY, cka_id, null);
            long pKeyHandle;
            if (h.type == ATTR_CLASS_PKEY) {
                pKeyHandle = h.handle;
            } else {
                throw new KeyStoreException
                        ("expected but could not find private key " +
                        "with CKA_ID " +
                        getID(cka_id));
            }

            // next find existing end entity cert

            h = getTokenObject(session, ATTR_CLASS_CERT, cka_id, null);
            if (h.type != ATTR_CLASS_CERT) {
                throw new KeyStoreException
                        ("expected but could not find certificate " +
                        "with CKA_ID " +
                        getID(cka_id));
            } else {
                if (replaceCert) {
                    // replacing existing cert and chain
                    destroyChain(cka_id);
                } else {
                    // renaming alias for existing cert
                    CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {
                        new CK_ATTRIBUTE(CKA_LABEL, alias),
                        new CK_ATTRIBUTE(CKA_ID, alias) };
                    token.p11.C_SetAttributeValue
                        (session.id(), h.handle, attrs);
                }
            }

            // add new chain

            if (replaceCert) {
                // add all certs in chain
                storeChain(alias, chain);
            } else {
                // already updated alias info for existing end cert -
                // just update CA certs
                storeCaCerts(chain, 1);
            }

            // finally update CKA_ID for private key
            //
            // ibutton may have already done this (that is ok)

            CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {
                                new CK_ATTRIBUTE(CKA_ID, alias) };
            token.p11.C_SetAttributeValue(session.id(), pKeyHandle, attrs);

            if (debug != null) {
                debug.println("updatePkey set new alias [" +
                                alias +
                                "] for private key entry");
            }
        } finally {
            token.releaseSession(session);
        }
    }

    // retrieves the native key handle and either update it directly or make a copy
    private void updateP11Pkey(String alias, CK_ATTRIBUTE attribute, P11Key key)
                throws PKCS11Exception {

        // if token key, update alias.
        // if session key, convert to token key.

        Session session = null;
        long keyID = key.getKeyID();
        try {
            session = token.getOpSession();
            if (key.tokenObject == true) {
                // token key - set new CKA_ID

                CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {
                                new CK_ATTRIBUTE(CKA_ID, alias) };
                token.p11.C_SetAttributeValue
                                (session.id(), keyID, attrs);
                if (debug != null) {
                    debug.println("updateP11Pkey set new alias [" +
                                alias +
                                "] for key entry");
                }
            } else {
                // session key - convert to token key and set CKA_ID

                CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {
                    ATTR_TOKEN_TRUE,
                    new CK_ATTRIBUTE(CKA_ID, alias),
                };
                if (attribute != null) {
                    attrs = addAttribute(attrs, attribute);
                }
                // creates a new token key with the desired CKA_ID
                token.p11.C_CopyObject(session.id(), keyID, attrs);
                if (debug != null) {
                    debug.println("updateP11Pkey copied private session key " +
                                "for [" +
                                alias +
                                "] to token entry");
                }
            }
        } finally {
            token.releaseSession(session);
            key.releaseKeyID();
        }
    }

    private void storeCert(String alias, X509Certificate cert)
                throws PKCS11Exception, CertificateException {

        ArrayList<CK_ATTRIBUTE> attrList = new ArrayList<CK_ATTRIBUTE>();
        attrList.add(ATTR_TOKEN_TRUE);
        attrList.add(ATTR_CLASS_CERT);
        attrList.add(ATTR_X509_CERT_TYPE);
        attrList.add(new CK_ATTRIBUTE(CKA_SUBJECT,
                                cert.getSubjectX500Principal().getEncoded()));
        attrList.add(new CK_ATTRIBUTE(CKA_ISSUER,
                                cert.getIssuerX500Principal().getEncoded()));
        attrList.add(new CK_ATTRIBUTE(CKA_SERIAL_NUMBER,
                                cert.getSerialNumber().toByteArray()));
        attrList.add(new CK_ATTRIBUTE(CKA_VALUE, cert.getEncoded()));

        if (alias != null) {
            attrList.add(new CK_ATTRIBUTE(CKA_LABEL, alias));
            attrList.add(new CK_ATTRIBUTE(CKA_ID, alias));
        } else {
            // ibutton requires something to be set
            // - alias must be unique
            attrList.add(new CK_ATTRIBUTE(CKA_ID,
                        getID(cert.getSubjectX500Principal().getName
                                        (X500Principal.CANONICAL), cert)));
        }

        Session session = null;
        try {
            session = token.getOpSession();
            token.p11.C_CreateObject(session.id(),
                        attrList.toArray(new CK_ATTRIBUTE[attrList.size()]));
        } finally {
            token.releaseSession(session);
        }
    }

    private void storeChain(String alias, X509Certificate[] chain)
                throws PKCS11Exception, CertificateException {

        // add new chain
        //
        // end cert has CKA_LABEL and CKA_ID set to alias.
        // other certs in chain have neither set.

        storeCert(alias, chain[0]);
        storeCaCerts(chain, 1);
    }

    private void storeCaCerts(X509Certificate[] chain, int start)
                throws PKCS11Exception, CertificateException {

        // do not add duplicate CA cert if already in token
        //
        // XXX   ibutton stores duplicate CA certs, NSS does not

        Session session = null;
        HashSet<X509Certificate> cacerts = new HashSet<X509Certificate>();
        try {
            session = token.getOpSession();
            CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {
                        ATTR_TOKEN_TRUE,
                        ATTR_CLASS_CERT };
            long[] handles = findObjects(session, attrs);

            // load certs currently on the token
            for (long handle : handles) {
                cacerts.add(loadCert(session, handle));
            }
        } finally {
            token.releaseSession(session);
        }

        for (int i = start; i < chain.length; i++) {
            if (!cacerts.contains(chain[i])) {
                storeCert(null, chain[i]);
            } else if (debug != null) {
                debug.println("ignoring duplicate CA cert for [" +
                        chain[i].getSubjectX500Principal() +
                        "]");
            }
        }
    }

    private void storeSkey(String alias, KeyStore.SecretKeyEntry ske)
                throws PKCS11Exception, KeyStoreException {

        SecretKey skey = ske.getSecretKey();
        // No need to specify CKA_CLASS, CKA_KEY_TYPE, CKA_VALUE since
        // they are handled in P11SecretKeyFactory.createKey() method.
        CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {
            ATTR_SKEY_TOKEN_TRUE,
            ATTR_PRIVATE_TRUE,
            new CK_ATTRIBUTE(CKA_LABEL, alias),
        };
        try {
            P11SecretKeyFactory.convertKey(token, skey, null, attrs);
        } catch (InvalidKeyException ike) {
            // re-throw KeyStoreException to match javadoc
            throw new KeyStoreException("Cannot convert to PKCS11 keys", ike);
        }

        // update global alias map
        aliasMap.put(alias, new AliasInfo(alias));

        if (debug != null) {
            debug.println("storeSkey created token secret key for [" +
                          alias + "]");
        }
    }

    private static CK_ATTRIBUTE[] addAttribute(CK_ATTRIBUTE[] attrs, CK_ATTRIBUTE attr) {
        int n = attrs.length;
        CK_ATTRIBUTE[] newAttrs = new CK_ATTRIBUTE[n + 1];
        System.arraycopy(attrs, 0, newAttrs, 0, n);
        newAttrs[n] = attr;
        return newAttrs;
    }

    private void storePkey(String alias, KeyStore.PrivateKeyEntry pke)
        throws PKCS11Exception, CertificateException, KeyStoreException  {

        PrivateKey key = pke.getPrivateKey();
        CK_ATTRIBUTE[] attrs = null;

        // If the key is a token object on this token, update it instead
        // of creating a duplicate key object.
        // Otherwise, treat a P11Key like any other key, if is is extractable.
        if (key instanceof P11Key) {
            P11Key p11Key = (P11Key)key;
            if (p11Key.tokenObject && (p11Key.token == this.token)) {
                updateP11Pkey(alias, null, p11Key);
                storeChain(alias, (X509Certificate[])pke.getCertificateChain());
                return;
            }
        }

        boolean useNDB = token.config.getNssNetscapeDbWorkaround();
        PublicKey publicKey = pke.getCertificate().getPublicKey();

        if (key instanceof RSAPrivateKey) {

            X509Certificate cert = (X509Certificate)pke.getCertificate();
            attrs = getRsaPrivKeyAttrs
                (alias, (RSAPrivateKey)key, cert.getSubjectX500Principal());

        } else if (key instanceof DSAPrivateKey) {

            DSAPrivateKey dsaKey = (DSAPrivateKey)key;

            CK_ATTRIBUTE[] idAttrs = getIdAttributes(key, publicKey, false, useNDB);
            if (idAttrs[0] == null) {
                idAttrs[0] = new CK_ATTRIBUTE(CKA_ID, alias);
            }

            attrs = new CK_ATTRIBUTE[] {
                ATTR_TOKEN_TRUE,
                ATTR_CLASS_PKEY,
                ATTR_PRIVATE_TRUE,
                new CK_ATTRIBUTE(CKA_KEY_TYPE, CKK_DSA),
                idAttrs[0],
                new CK_ATTRIBUTE(CKA_PRIME, dsaKey.getParams().getP()),
                new CK_ATTRIBUTE(CKA_SUBPRIME, dsaKey.getParams().getQ()),
                new CK_ATTRIBUTE(CKA_BASE, dsaKey.getParams().getG()),
                new CK_ATTRIBUTE(CKA_VALUE, dsaKey.getX()),
            };
            if (idAttrs[1] != null) {
                attrs = addAttribute(attrs, idAttrs[1]);
            }

            attrs = token.getAttributes
                (TemplateManager.O_IMPORT, CKO_PRIVATE_KEY, CKK_DSA, attrs);

            if (debug != null) {
                debug.println("storePkey created DSA template");
            }

        } else if (key instanceof DHPrivateKey) {

            DHPrivateKey dhKey = (DHPrivateKey)key;

            CK_ATTRIBUTE[] idAttrs = getIdAttributes(key, publicKey, false, useNDB);
            if (idAttrs[0] == null) {
                idAttrs[0] = new CK_ATTRIBUTE(CKA_ID, alias);
            }

            attrs = new CK_ATTRIBUTE[] {
                ATTR_TOKEN_TRUE,
                ATTR_CLASS_PKEY,
                ATTR_PRIVATE_TRUE,
                new CK_ATTRIBUTE(CKA_KEY_TYPE, CKK_DH),
                idAttrs[0],
                new CK_ATTRIBUTE(CKA_PRIME, dhKey.getParams().getP()),
                new CK_ATTRIBUTE(CKA_BASE, dhKey.getParams().getG()),
                new CK_ATTRIBUTE(CKA_VALUE, dhKey.getX()),
            };
            if (idAttrs[1] != null) {
                attrs = addAttribute(attrs, idAttrs[1]);
            }

            attrs = token.getAttributes
                (TemplateManager.O_IMPORT, CKO_PRIVATE_KEY, CKK_DH, attrs);

        } else if (key instanceof ECPrivateKey) {

            ECPrivateKey ecKey = (ECPrivateKey)key;

            CK_ATTRIBUTE[] idAttrs = getIdAttributes(key, publicKey, false, useNDB);
            if (idAttrs[0] == null) {
                idAttrs[0] = new CK_ATTRIBUTE(CKA_ID, alias);
            }

            byte[] encodedParams =
                ECUtil.encodeECParameterSpec(null, ecKey.getParams());
            attrs = new CK_ATTRIBUTE[] {
                ATTR_TOKEN_TRUE,
                ATTR_CLASS_PKEY,
                ATTR_PRIVATE_TRUE,
                new CK_ATTRIBUTE(CKA_KEY_TYPE, CKK_EC),
                idAttrs[0],
                new CK_ATTRIBUTE(CKA_VALUE, ecKey.getS()),
                new CK_ATTRIBUTE(CKA_EC_PARAMS, encodedParams),
            };
            if (idAttrs[1] != null) {
                attrs = addAttribute(attrs, idAttrs[1]);
            }

            attrs = token.getAttributes
                (TemplateManager.O_IMPORT, CKO_PRIVATE_KEY, CKK_EC, attrs);

            if (debug != null) {
                debug.println("storePkey created EC template");
            }

        } else if (key instanceof P11Key) {
            // sensitive/non-extractable P11Key
            P11Key p11Key = (P11Key)key;
            if (p11Key.token != this.token) {
                throw new KeyStoreException
                    ("Cannot move sensitive keys across tokens");
            }
            CK_ATTRIBUTE netscapeDB = null;
            if (useNDB) {
                // Note that this currently fails due to an NSS bug.
                // They do not allow the CKA_NETSCAPE_DB attribute to be
                // specified during C_CopyObject() and fail with
                // CKR_ATTRIBUTE_READ_ONLY.
                // But if we did not specify it, they would fail with
                // CKA_TEMPLATE_INCOMPLETE, so leave this code in here.
                CK_ATTRIBUTE[] idAttrs = getIdAttributes(key, publicKey, false, true);
                netscapeDB = idAttrs[1];
            }
            // Update the key object.
            updateP11Pkey(alias, netscapeDB, p11Key);
            storeChain(alias, (X509Certificate[])pke.getCertificateChain());
            return;

        } else {
            throw new KeyStoreException("unsupported key type: " + key);
        }

        Session session = null;
        try {
            session = token.getOpSession();

            // create private key entry
            token.p11.C_CreateObject(session.id(), attrs);
            if (debug != null) {
                debug.println("storePkey created token key for [" +
                                alias +
                                "]");
            }
        } finally {
            token.releaseSession(session);
        }

        storeChain(alias, (X509Certificate[])pke.getCertificateChain());
    }

    private CK_ATTRIBUTE[] getRsaPrivKeyAttrs(String alias,
                                RSAPrivateKey key,
                                X500Principal subject) throws PKCS11Exception {

        // subject is currently ignored - could be used to set CKA_SUBJECT

        CK_ATTRIBUTE[] attrs = null;
        if (key instanceof RSAPrivateCrtKey) {

            if (debug != null) {
                debug.println("creating RSAPrivateCrtKey attrs");
            }

            RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey)key;

            attrs = new CK_ATTRIBUTE[] {
                ATTR_TOKEN_TRUE,
                ATTR_CLASS_PKEY,
                ATTR_PRIVATE_TRUE,
                new CK_ATTRIBUTE(CKA_KEY_TYPE, CKK_RSA),
                new CK_ATTRIBUTE(CKA_ID, alias),
                new CK_ATTRIBUTE(CKA_MODULUS,
                                rsaKey.getModulus()),
                new CK_ATTRIBUTE(CKA_PRIVATE_EXPONENT,
                                rsaKey.getPrivateExponent()),
                new CK_ATTRIBUTE(CKA_PUBLIC_EXPONENT,
                                rsaKey.getPublicExponent()),
                new CK_ATTRIBUTE(CKA_PRIME_1,
                                rsaKey.getPrimeP()),
                new CK_ATTRIBUTE(CKA_PRIME_2,
                                rsaKey.getPrimeQ()),
                new CK_ATTRIBUTE(CKA_EXPONENT_1,
                                rsaKey.getPrimeExponentP()),
                new CK_ATTRIBUTE(CKA_EXPONENT_2,
                                rsaKey.getPrimeExponentQ()),
                new CK_ATTRIBUTE(CKA_COEFFICIENT,
                                rsaKey.getCrtCoefficient()) };
            attrs = token.getAttributes
                (TemplateManager.O_IMPORT, CKO_PRIVATE_KEY, CKK_RSA, attrs);

        } else {

            if (debug != null) {
                debug.println("creating RSAPrivateKey attrs");
            }

            RSAPrivateKey rsaKey = key;

            attrs = new CK_ATTRIBUTE[] {
                ATTR_TOKEN_TRUE,
                ATTR_CLASS_PKEY,
                ATTR_PRIVATE_TRUE,
                new CK_ATTRIBUTE(CKA_KEY_TYPE, CKK_RSA),
                new CK_ATTRIBUTE(CKA_ID, alias),
                new CK_ATTRIBUTE(CKA_MODULUS,
                                rsaKey.getModulus()),
                new CK_ATTRIBUTE(CKA_PRIVATE_EXPONENT,
                                rsaKey.getPrivateExponent()) };
            attrs = token.getAttributes
                (TemplateManager.O_IMPORT, CKO_PRIVATE_KEY, CKK_RSA, attrs);
        }

        return attrs;
    }

    /**
     * Compute the CKA_ID and/or CKA_NETSCAPE_DB attributes that should be
     * used for this private key. It uses the same algorithm to calculate the
     * values as NSS. The public and private keys MUST match for the result to
     * be correct.
     *
     * It returns a 2 element array with CKA_ID at index 0 and CKA_NETSCAPE_DB
     * at index 1. The boolean flags determine what is to be calculated.
     * If false or if we could not calculate the value, that element is null.
     *
     * NOTE that we currently do not use the CKA_ID value calculated by this
     * method.
     */
    private CK_ATTRIBUTE[] getIdAttributes(PrivateKey privateKey,
            PublicKey publicKey, boolean id, boolean netscapeDb) {
        CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[2];
        if ((id || netscapeDb) == false) {
            return attrs;
        }
        String alg = privateKey.getAlgorithm();
        if (alg.equals("RSA") && (publicKey instanceof RSAPublicKey)) {
            if (id) {
                BigInteger n = ((RSAPublicKey)publicKey).getModulus();
                attrs[0] = new CK_ATTRIBUTE(CKA_ID, sha1(getMagnitude(n)));
            }
            // CKA_NETSCAPE_DB not needed for RSA public keys
        } else if (alg.equals("DSA") && (publicKey instanceof DSAPublicKey)) {
            BigInteger y = ((DSAPublicKey)publicKey).getY();
            if (id) {
                attrs[0] = new CK_ATTRIBUTE(CKA_ID, sha1(getMagnitude(y)));
            }
            if (netscapeDb) {
                attrs[1] = new CK_ATTRIBUTE(CKA_NETSCAPE_DB, y);
            }
        } else if (alg.equals("DH") && (publicKey instanceof DHPublicKey)) {
            BigInteger y = ((DHPublicKey)publicKey).getY();
            if (id) {
                attrs[0] = new CK_ATTRIBUTE(CKA_ID, sha1(getMagnitude(y)));
            }
            if (netscapeDb) {
                attrs[1] = new CK_ATTRIBUTE(CKA_NETSCAPE_DB, y);
            }
        } else if (alg.equals("EC") && (publicKey instanceof ECPublicKey)) {
            ECPublicKey ecPub = (ECPublicKey)publicKey;
            ECPoint point = ecPub.getW();
            ECParameterSpec params = ecPub.getParams();
            byte[] encodedPoint = ECUtil.encodePoint(point, params.getCurve());
            if (id) {
                attrs[0] = new CK_ATTRIBUTE(CKA_ID, sha1(encodedPoint));
            }
            if (netscapeDb) {
                attrs[1] = new CK_ATTRIBUTE(CKA_NETSCAPE_DB, encodedPoint);
            }
        } else {
            throw new RuntimeException("Unknown key algorithm " + alg);
        }
        return attrs;
    }

    /**
     * return true if cert destroyed
     */
    private boolean destroyCert(byte[] cka_id)
                throws PKCS11Exception, KeyStoreException {
        Session session = null;
        try {
            session = token.getOpSession();
            THandle h = getTokenObject(session, ATTR_CLASS_CERT, cka_id, null);
            if (h.type != ATTR_CLASS_CERT) {
                return false;
            }

            token.p11.C_DestroyObject(session.id(), h.handle);
            if (debug != null) {
                debug.println("destroyCert destroyed cert with CKA_ID [" +
                                                getID(cka_id) +
                                                "]");
            }
            return true;
        } finally {
            token.releaseSession(session);
        }
    }

    /**
     * return true if chain destroyed
     */
    private boolean destroyChain(byte[] cka_id)
        throws PKCS11Exception, CertificateException, KeyStoreException {

        Session session = null;
        try {
            session = token.getOpSession();

            THandle h = getTokenObject(session, ATTR_CLASS_CERT, cka_id, null);
            if (h.type != ATTR_CLASS_CERT) {
                if (debug != null) {
                    debug.println("destroyChain could not find " +
                        "end entity cert with CKA_ID [0x" +
                        Functions.toHexString(cka_id) +
                        "]");
                }
                return false;
            }

            X509Certificate endCert = loadCert(session, h.handle);
            token.p11.C_DestroyObject(session.id(), h.handle);
            if (debug != null) {
                debug.println("destroyChain destroyed end entity cert " +
                        "with CKA_ID [" +
                        getID(cka_id) +
                        "]");
            }

            // build chain following issuer->subject links

            X509Certificate next = endCert;
            while (true) {

                if (next.getSubjectX500Principal().equals
                    (next.getIssuerX500Principal())) {
                    // self signed - done
                    break;
                }

                CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {
                        ATTR_TOKEN_TRUE,
                        ATTR_CLASS_CERT,
                        new CK_ATTRIBUTE(CKA_SUBJECT,
                                  next.getIssuerX500Principal().getEncoded()) };
                long[] ch = findObjects(session, attrs);

                if (ch == null || ch.length == 0) {
                    // done
                    break;
                } else {
                    // if more than one found, use first
                    if (debug != null && ch.length > 1) {
                        debug.println("destroyChain found " +
                                ch.length +
                                " certificate entries for subject [" +
                                next.getIssuerX500Principal() +
                                "] in token - using first entry");
                    }

                    next = loadCert(session, ch[0]);

                    // only delete if not part of any other chain

                    attrs = new CK_ATTRIBUTE[] {
                        ATTR_TOKEN_TRUE,
                        ATTR_CLASS_CERT,
                        new CK_ATTRIBUTE(CKA_ISSUER,
                                next.getSubjectX500Principal().getEncoded()) };
                    long[] issuers = findObjects(session, attrs);

                    boolean destroyIt = false;
                    if (issuers == null || issuers.length == 0) {
                        // no other certs with this issuer -
                        // destroy it
                        destroyIt = true;
                    } else if (issuers.length == 1) {
                        X509Certificate iCert = loadCert(session, issuers[0]);
                        if (next.equals(iCert)) {
                            // only cert with issuer is itself (self-signed) -
                            // destroy it
                            destroyIt = true;
                        }
                    }

                    if (destroyIt) {
                        token.p11.C_DestroyObject(session.id(), ch[0]);
                        if (debug != null) {
                            debug.println
                                ("destroyChain destroyed cert in chain " +
                                "with subject [" +
                                next.getSubjectX500Principal() + "]");
                        }
                    } else {
                        if (debug != null) {
                            debug.println("destroyChain did not destroy " +
                                "shared cert in chain with subject [" +
                                next.getSubjectX500Principal() + "]");
                        }
                    }
                }
            }

            return true;

        } finally {
            token.releaseSession(session);
        }
    }

    /**
     * return true if secret key destroyed
     */
    private boolean destroySkey(String alias)
                throws PKCS11Exception, KeyStoreException {
        Session session = null;
        try {
            session = token.getOpSession();

            THandle h = getTokenObject(session, ATTR_CLASS_SKEY, null, alias);
            if (h.type != ATTR_CLASS_SKEY) {
                if (debug != null) {
                    debug.println("destroySkey did not find secret key " +
                        "with CKA_LABEL [" +
                        alias +
                        "]");
                }
                return false;
            }
            token.p11.C_DestroyObject(session.id(), h.handle);
            return true;
        } finally {
            token.releaseSession(session);
        }
    }

    /**
     * return true if private key destroyed
     */
    private boolean destroyPkey(byte[] cka_id)
                throws PKCS11Exception, KeyStoreException {
        Session session = null;
        try {
            session = token.getOpSession();

            THandle h = getTokenObject(session, ATTR_CLASS_PKEY, cka_id, null);
            if (h.type != ATTR_CLASS_PKEY) {
                if (debug != null) {
                    debug.println
                        ("destroyPkey did not find private key with CKA_ID [" +
                        getID(cka_id) +
                        "]");
                }
                return false;
            }
            token.p11.C_DestroyObject(session.id(), h.handle);
            return true;
        } finally {
            token.releaseSession(session);
        }
    }

    /**
     * build [alias + issuer + serialNumber] string from a cert
     */
    private String getID(String alias, X509Certificate cert) {
        X500Principal issuer = cert.getIssuerX500Principal();
        BigInteger serialNum = cert.getSerialNumber();

        return alias +
                ALIAS_SEP +
                issuer.getName(X500Principal.CANONICAL) +
                ALIAS_SEP +
                serialNum.toString();
    }

    /**
     * build CKA_ID string from bytes
     */
    private static String getID(byte[] bytes) {
        boolean printable = true;
        for (int i = 0; i < bytes.length; i++) {
            if (!DerValue.isPrintableStringChar((char)bytes[i])) {
                printable = false;
                break;
            }
        }

        if (!printable) {
            return "0x" + Functions.toHexString(bytes);
        } else {
            try {
                return new String(bytes, "UTF-8");
            } catch (UnsupportedEncodingException uee) {
                return "0x" + Functions.toHexString(bytes);
            }
        }
    }

    /**
     * find an object on the token
     *
     * @param type either ATTR_CLASS_CERT, ATTR_CLASS_PKEY, or ATTR_CLASS_SKEY
     * @param cka_id the CKA_ID if type is ATTR_CLASS_CERT or ATTR_CLASS_PKEY
     * @param cka_label the CKA_LABEL if type is ATTR_CLASS_SKEY
     */
    private THandle getTokenObject(Session session,
                                CK_ATTRIBUTE type,
                                byte[] cka_id,
                                String cka_label)
                throws PKCS11Exception, KeyStoreException {

        CK_ATTRIBUTE[] attrs;
        if (type == ATTR_CLASS_SKEY) {
            attrs = new CK_ATTRIBUTE[] {
                        ATTR_SKEY_TOKEN_TRUE,
                        new CK_ATTRIBUTE(CKA_LABEL, cka_label),
                        type };
        } else {
            attrs = new CK_ATTRIBUTE[] {
                        ATTR_TOKEN_TRUE,
                        new CK_ATTRIBUTE(CKA_ID, cka_id),
                        type };
        }
        long[] h = findObjects(session, attrs);
        if (h.length == 0) {
            if (debug != null) {
                if (type == ATTR_CLASS_SKEY) {
                    debug.println("getTokenObject did not find secret key " +
                                "with CKA_LABEL [" +
                                cka_label +
                                "]");
                } else if (type == ATTR_CLASS_CERT) {
                    debug.println
                        ("getTokenObject did not find cert with CKA_ID [" +
                        getID(cka_id) +
                        "]");
                } else {
                    debug.println("getTokenObject did not find private key " +
                        "with CKA_ID [" +
                        getID(cka_id) +
                        "]");
                }
            }
        } else if (h.length == 1) {

            // found object handle - return it
            return new THandle(h[0], type);

        } else {

            // found multiple object handles -
            // see if token ignored CKA_LABEL during search (e.g. NSS)

            if (type == ATTR_CLASS_SKEY) {

                ArrayList<THandle> list = new ArrayList<THandle>(h.length);
                for (int i = 0; i < h.length; i++) {

                    CK_ATTRIBUTE[] label = new CK_ATTRIBUTE[]
                                        { new CK_ATTRIBUTE(CKA_LABEL) };
                    token.p11.C_GetAttributeValue(session.id(), h[i], label);
                    if (label[0].pValue != null &&
                        cka_label.equals(new String(label[0].getCharArray()))) {
                        list.add(new THandle(h[i], ATTR_CLASS_SKEY));
                    }
                }
                if (list.size() == 1) {
                    // yes, there was only one CKA_LABEL that matched
                    return list.get(0);
                } else {
                    throw new KeyStoreException("invalid KeyStore state: " +
                        "found " +
                        list.size() +
                        " secret keys sharing CKA_LABEL [" +
                        cka_label +
                        "]");
                }
            } else if (type == ATTR_CLASS_CERT) {
                throw new KeyStoreException("invalid KeyStore state: " +
                        "found " +
                        h.length +
                        " certificates sharing CKA_ID " +
                        getID(cka_id));
            } else {
                throw new KeyStoreException("invalid KeyStore state: " +
                        "found " +
                        h.length +
                        " private keys sharing CKA_ID " +
                        getID(cka_id));
            }
        }
        return new THandle(NO_HANDLE, null);
    }

    /**
     * Create a mapping of all key pairs, trusted certs, and secret keys
     * on the token into logical KeyStore entries unambiguously
     * accessible via an alias.
     *
     * If the token is removed, the map may contain stale values.
     * KeyStore.load should be called to re-create the map.
     *
     * Assume all private keys and matching certs share a unique CKA_ID.
     *
     * Assume all secret keys have a unique CKA_LABEL.
     *
     * @return true if multiple certs found sharing the same CKA_LABEL
     *          (if so, write capabilities are disabled)
     */
    private boolean mapLabels() throws
                PKCS11Exception, CertificateException, KeyStoreException {

        CK_ATTRIBUTE[] trustedAttr = new CK_ATTRIBUTE[] {
                                new CK_ATTRIBUTE(CKA_TRUSTED) };

        Session session = null;
        try {
            session = token.getOpSession();

            // get all private key CKA_IDs

            ArrayList<byte[]> pkeyIDs = new ArrayList<byte[]>();
            CK_ATTRIBUTE[] attrs = new CK_ATTRIBUTE[] {
                ATTR_TOKEN_TRUE,
                ATTR_CLASS_PKEY,
            };
            long[] handles = findObjects(session, attrs);

            for (long handle : handles) {
                attrs = new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_ID) };
                token.p11.C_GetAttributeValue(session.id(), handle, attrs);

                if (attrs[0].pValue != null) {
                    pkeyIDs.add(attrs[0].getByteArray());
                }
            }

            // Get all certificates
            //
            // If cert does not have a CKA_LABEL nor CKA_ID, it is ignored.
            //
            // Get the CKA_LABEL for each cert
            // (if the cert does not have a CKA_LABEL, use the CKA_ID).
            //
            // Map each cert to the its CKA_LABEL
            // (multiple certs may be mapped to a single CKA_LABEL)

            HashMap<String, HashSet<AliasInfo>> certMap =
                                new HashMap<String, HashSet<AliasInfo>>();

            attrs = new CK_ATTRIBUTE[] {
                ATTR_TOKEN_TRUE,
                ATTR_CLASS_CERT,
            };
            handles = findObjects(session, attrs);

            for (long handle : handles) {
                attrs = new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_LABEL) };

                String cka_label = null;
                byte[] cka_id = null;
                try {
                    token.p11.C_GetAttributeValue(session.id(), handle, attrs);
                    if (attrs[0].pValue != null) {
                        // there is a CKA_LABEL
                        cka_label = new String(attrs[0].getCharArray());
                    }
                } catch (PKCS11Exception pe) {
                    if (pe.getErrorCode() != CKR_ATTRIBUTE_TYPE_INVALID) {
                        throw pe;
                    }

                    // GetAttributeValue for CKA_LABEL not supported
                    //
                    // XXX SCA1000
                }

                // get CKA_ID

                attrs = new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_ID) };
                token.p11.C_GetAttributeValue(session.id(), handle, attrs);
                if (attrs[0].pValue == null) {
                    if (cka_label == null) {
                        // no cka_label nor cka_id - ignore
                        continue;
                    }
                } else {
                    if (cka_label == null) {
                        // use CKA_ID as CKA_LABEL
                        cka_label = getID(attrs[0].getByteArray());
                    }
                    cka_id = attrs[0].getByteArray();
                }

                X509Certificate cert = loadCert(session, handle);

                // get CKA_TRUSTED

                boolean cka_trusted = false;

                if (useSecmodTrust) {
                    cka_trusted = Secmod.getInstance().isTrusted(cert, nssTrustType);
                } else {
                    if (CKA_TRUSTED_SUPPORTED) {
                        try {
                            token.p11.C_GetAttributeValue
                                    (session.id(), handle, trustedAttr);
                            cka_trusted = trustedAttr[0].getBoolean();
                        } catch (PKCS11Exception pe) {
                            if (pe.getErrorCode() == CKR_ATTRIBUTE_TYPE_INVALID) {
                                // XXX  NSS, ibutton, sca1000
                                CKA_TRUSTED_SUPPORTED = false;
                                if (debug != null) {
                                    debug.println
                                            ("CKA_TRUSTED attribute not supported");
                                }
                            }
                        }
                    }
                }

                HashSet<AliasInfo> infoSet = certMap.get(cka_label);
                if (infoSet == null) {
                    infoSet = new HashSet<AliasInfo>(2);
                    certMap.put(cka_label, infoSet);
                }

                // initially create private key entry AliasInfo entries -
                // these entries will get resolved into their true
                // entry types later

                infoSet.add(new AliasInfo
                                (cka_label,
                                cka_id,
                                cka_trusted,
                                cert));
            }

            // create list secret key CKA_LABELS -
            // if there are duplicates (either between secret keys,
            // or between a secret key and another object),
            // throw an exception
            HashMap<String, AliasInfo> sKeyMap =
                    new HashMap<String, AliasInfo>();

            attrs = new CK_ATTRIBUTE[] {
                ATTR_SKEY_TOKEN_TRUE,
                ATTR_CLASS_SKEY,
            };
            handles = findObjects(session, attrs);

            for (long handle : handles) {
                attrs = new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_LABEL) };
                token.p11.C_GetAttributeValue(session.id(), handle, attrs);
                if (attrs[0].pValue != null) {

                    // there is a CKA_LABEL
                    String cka_label = new String(attrs[0].getCharArray());
                    if (sKeyMap.get(cka_label) == null) {
                        sKeyMap.put(cka_label, new AliasInfo(cka_label));
                    } else {
                        throw new KeyStoreException("invalid KeyStore state: " +
                                "found multiple secret keys sharing same " +
                                "CKA_LABEL [" +
                                cka_label +
                                "]");
                    }
                }
            }

            // update global aliasMap with alias mappings
            ArrayList<AliasInfo> matchedCerts =
                                mapPrivateKeys(pkeyIDs, certMap);
            boolean sharedLabel = mapCerts(matchedCerts, certMap);
            mapSecretKeys(sKeyMap);

            return sharedLabel;

        } finally {
            token.releaseSession(session);
        }
    }

    /**
     * for each private key CKA_ID, find corresponding cert with same CKA_ID.
     * if found cert, see if cert CKA_LABEL is unique.
     *     if CKA_LABEL unique, map private key/cert alias to that CKA_LABEL.
     *     if CKA_LABEL not unique, map private key/cert alias to:
     *                   CKA_LABEL + ALIAS_SEP + ISSUER + ALIAS_SEP + SERIAL
     * if cert not found, ignore private key
     * (don't support private key entries without a cert chain yet)
     *
     * @return a list of AliasInfo entries that represents all matches
     */
    private ArrayList<AliasInfo> mapPrivateKeys(ArrayList<byte[]> pkeyIDs,
                        HashMap<String, HashSet<AliasInfo>> certMap)
                throws PKCS11Exception, CertificateException {

        // reset global alias map
        aliasMap = new HashMap<String, AliasInfo>();

        // list of matched certs that we will return
        ArrayList<AliasInfo> matchedCerts = new ArrayList<AliasInfo>();

        for (byte[] pkeyID : pkeyIDs) {

            // try to find a matching CKA_ID in a certificate

            boolean foundMatch = false;
            Set<String> certLabels = certMap.keySet();
            for (String certLabel : certLabels) {

                // get cert CKA_IDs (if present) for each cert

                HashSet<AliasInfo> infoSet = certMap.get(certLabel);
                for (AliasInfo aliasInfo : infoSet) {
                    if (Arrays.equals(pkeyID, aliasInfo.id)) {

                        // found private key with matching cert

                        if (infoSet.size() == 1) {
                            // unique CKA_LABEL - use certLabel as alias
                            aliasInfo.matched = true;
                            aliasMap.put(certLabel, aliasInfo);
                        } else {
                            // create new alias
                            aliasInfo.matched = true;
                            aliasMap.put(getID(certLabel, aliasInfo.cert),
                                        aliasInfo);
                        }
                        matchedCerts.add(aliasInfo);
                        foundMatch = true;
                        break;
                    }
                }
                if (foundMatch) {
                    break;
                }
            }

            if (!foundMatch) {
                if (debug != null) {
                    debug.println
                        ("did not find match for private key with CKA_ID [" +
                        getID(pkeyID) +
                        "] (ignoring entry)");
                }
            }
        }

        return matchedCerts;
    }

    /**
     * for each cert not matched with a private key but is CKA_TRUSTED:
     *     if CKA_LABEL unique, map cert to CKA_LABEL.
     *     if CKA_LABEL not unique, map cert to [label+issuer+serialNum]
     *
     * if CKA_TRUSTED not supported, treat all certs not part of a chain
     * as trusted
     *
     * @return true if multiple certs found sharing the same CKA_LABEL
     */
    private boolean mapCerts(ArrayList<AliasInfo> matchedCerts,
                        HashMap<String, HashSet<AliasInfo>> certMap)
                throws PKCS11Exception, CertificateException {

        // load all cert chains
        for (AliasInfo aliasInfo : matchedCerts) {
            Session session = null;
            try {
                session = token.getOpSession();
                aliasInfo.chain = loadChain(session, aliasInfo.cert);
            } finally {
                token.releaseSession(session);
            }
        }

        // find all certs in certMap not part of a cert chain
        // - these are trusted

        boolean sharedLabel = false;

        Set<String> certLabels = certMap.keySet();
        for (String certLabel : certLabels) {
            HashSet<AliasInfo> infoSet = certMap.get(certLabel);
            for (AliasInfo aliasInfo : infoSet) {

                if (aliasInfo.matched == true) {
                    // already found a private key match for this cert -
                    // just continue
                    aliasInfo.trusted = false;
                    continue;
                }

                // cert in this aliasInfo is not matched yet
                //
                // if CKA_TRUSTED_SUPPORTED == true,
                // then check if cert is trusted

                if (CKA_TRUSTED_SUPPORTED) {
                    if (aliasInfo.trusted) {
                        // trusted certificate
                        if (mapTrustedCert
                                (certLabel, aliasInfo, infoSet) == true) {
                            sharedLabel = true;
                        }
                    }
                    continue;
                }

                // CKA_TRUSTED_SUPPORTED == false
                //
                // XXX treat all certs not part of a chain as trusted
                // XXX
                // XXX Unsupported
                //
                // boolean partOfChain = false;
                // for (AliasInfo matchedInfo : matchedCerts) {
                //     for (int i = 0; i < matchedInfo.chain.length; i++) {
                //      if (matchedInfo.chain[i].equals(aliasInfo.cert)) {
                //          partOfChain = true;
                //          break;
                //      }
                //     }
                //     if (partOfChain) {
                //      break;
                //     }
                // }
                //
                // if (!partOfChain) {
                //     if (mapTrustedCert(certLabel,aliasInfo,infoSet) == true){
                //      sharedLabel = true;
                //     }
                // } else {
                //    if (debug != null) {
                //      debug.println("ignoring unmatched/untrusted cert " +
                //          "that is part of cert chain - cert subject is [" +
                //          aliasInfo.cert.getSubjectX500Principal().getName
                //                              (X500Principal.CANONICAL) +
                //          "]");
                //     }
                // }
            }
        }

        return sharedLabel;
    }

    private boolean mapTrustedCert(String certLabel,
                                AliasInfo aliasInfo,
                                HashSet<AliasInfo> infoSet) {

        boolean sharedLabel = false;

        aliasInfo.type = ATTR_CLASS_CERT;
        aliasInfo.trusted = true;
        if (infoSet.size() == 1) {
            // unique CKA_LABEL - use certLabel as alias
            aliasMap.put(certLabel, aliasInfo);
        } else {
            // create new alias
            sharedLabel = true;
            aliasMap.put(getID(certLabel, aliasInfo.cert), aliasInfo);
        }

        return sharedLabel;
    }

    /**
     * If the secret key shares a CKA_LABEL with another entry,
     * throw an exception
     */
    private void mapSecretKeys(HashMap<String, AliasInfo> sKeyMap)
                throws KeyStoreException {
        for (String label : sKeyMap.keySet()) {
            if (aliasMap.containsKey(label)) {
                throw new KeyStoreException("invalid KeyStore state: " +
                        "found secret key sharing CKA_LABEL [" +
                        label +
                        "] with another token object");
            }
        }
        aliasMap.putAll(sKeyMap);
    }

    private void dumpTokenMap() {
        Set<String> aliases = aliasMap.keySet();
        System.out.println("Token Alias Map:");
        if (aliases.isEmpty()) {
            System.out.println("  [empty]");
        } else {
            for (String s : aliases) {
                System.out.println("  " + s + aliasMap.get(s));
            }
        }
    }

    private void checkWrite() throws KeyStoreException {
        if (writeDisabled) {
            throw new KeyStoreException
                ("This PKCS11KeyStore does not support write capabilities");
        }
    }

    private final static long[] LONG0 = new long[0];

    private static long[] findObjects(Session session, CK_ATTRIBUTE[] attrs)
            throws PKCS11Exception {
        Token token = session.token;
        long[] handles = LONG0;
        token.p11.C_FindObjectsInit(session.id(), attrs);
        while (true) {
            long[] h = token.p11.C_FindObjects(session.id(), FINDOBJECTS_MAX);
            if (h.length == 0) {
                break;
            }
            handles = P11Util.concat(handles, h);
        }
        token.p11.C_FindObjectsFinal(session.id());
        return handles;
    }

}