Welcome to mirror list, hosted at ThFree Co, Russian Federation.

X509CertSelector.java « cert « security « java « jdk1.1 « main « src « core - gitlab.com/quite/humla-spongycastle.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0ac127f6b710d564ee6543a1e8e367c27e79068a (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
package java.security.cert;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.ASN1GeneralizedTime;
import org.bouncycastle.asn1.DERGeneralizedTime;
import org.bouncycastle.asn1.DEROutputStream;
import org.bouncycastle.asn1.util.ASN1Dump;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.jce.PrincipalUtil;
import org.bouncycastle.util.Integers;

/**
 * A <code>CertSelector</code> that selects
 * <code>X509Certificates that match all
 * specified criteria. This class is particularly useful when
 * selecting certificates from a CertStore to build a PKIX-compliant
 * certification path.<br />
 * <br />
 * When first constructed, an <code>X509CertSelector</code> has no criteria enabled
 * and each of the get methods return a default value (<code>null</code>, or -1 for
 * the {@link #getBasicConstraints} method). Therefore, the {@link #match} method would
 * return true for any <code>X509Certificate</code>. Typically, several criteria
 * are enabled (by calling {@link #setIssuer} or {@link #setKeyUsage}, for instance) and
 * then the <code>X509CertSelector</code> is passed to {@link CertStore#getCertificates} or
 * some similar method.<br />
 * <br />
 * Several criteria can be enabled (by calling {@link #setIssuer} and
 * {@link #setSerialNumber}, for example) such that the match method usually
 * uniquely matches a single <code>X509Certificate</code>. We say usually, since it
 * is possible for two issuing CAs to have the same distinguished name
 * and each issue a certificate with the same serial number. Other
 * unique combinations include the issuer, subject,
 * subjectKeyIdentifier and/or the subjectPublicKey criteria.<br />
 * <br />
 * Please refer to RFC 2459 for definitions of the X.509 certificate
 * extensions mentioned below.<br />
 * <br />
 * <b>Concurrent Access</b><br />
 * <br />
 * Unless otherwise specified, the methods defined in this class are
 * not thread-safe. Multiple threads that need to access a single
 * object concurrently should synchronize amongst themselves and
 * provide the necessary locking. Multiple threads each manipulating
 * separate objects need not synchronize.<br />
 * <br />
 * <b>TODO: implement name constraints</b>
 * <b>TODO: implement match check for path to names</b><br />
 * <br />
 * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream},
 * {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence},
 * {@link org.bouncycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier},
 * {@link org.bouncycastle.asn1.DEROutputStream DEROutputStream},
 * {@link org.bouncycastle.asn1.ASN1Object ASN1Object},
 * {@link org.bouncycastle.asn1.OIDTokenizer OIDTokenizer},
 * {@link org.bouncycastle.asn1.x509.X509Name X509Name},
 * {@link org.bouncycastle.asn1.x509.X509Extensions X509Extensions},
 * {@link org.bouncycastle.asn1.x509.ExtendedKeyUsage ExtendedKeyUsage},
 * {@link org.bouncycastle.asn1.x509.KeyPurposeId KeyPurposeId},
 * {@link org.bouncycastle.asn1.x509.SubjectPublicKeyInfo SubjectPublicKeyInfo},
 * {@link org.bouncycastle.asn1.x509.AlgorithmIdentifier AlgorithmIdentifier}
 */
public class X509CertSelector implements CertSelector
{
    private static final Hashtable keyPurposeIdMap = new Hashtable();
    static
    {
        keyPurposeIdMap.put(KeyPurposeId.id_kp_serverAuth.getId(),
                KeyPurposeId.id_kp_serverAuth);
        keyPurposeIdMap.put(KeyPurposeId.id_kp_clientAuth.getId(),
                KeyPurposeId.id_kp_clientAuth);
        keyPurposeIdMap.put(KeyPurposeId.id_kp_codeSigning.getId(),
                KeyPurposeId.id_kp_codeSigning);
        keyPurposeIdMap.put(KeyPurposeId.id_kp_emailProtection.getId(),
                KeyPurposeId.id_kp_emailProtection);
        keyPurposeIdMap.put(KeyPurposeId.id_kp_ipsecEndSystem.getId(),
                KeyPurposeId.id_kp_ipsecEndSystem);
        keyPurposeIdMap.put(KeyPurposeId.id_kp_ipsecTunnel.getId(),
                KeyPurposeId.id_kp_ipsecTunnel);
        keyPurposeIdMap.put(KeyPurposeId.id_kp_ipsecUser.getId(),
                KeyPurposeId.id_kp_ipsecUser);
        keyPurposeIdMap.put(KeyPurposeId.id_kp_timeStamping.getId(),
                KeyPurposeId.id_kp_timeStamping);
    }

    private X509Certificate x509Cert = null;

    private BigInteger serialNumber = null;

    private Object issuerDN = null;

    private X509Name issuerDNX509 = null;

    private Object subjectDN = null;

    private X509Name subjectDNX509 = null;

    private byte[] subjectKeyID = null;

    private byte[] authorityKeyID = null;

    private Date certValid = null;

    private Date privateKeyValid = null;

    private ASN1ObjectIdentifier subjectKeyAlgID = null;

    private PublicKey subjectPublicKey = null;

    private byte[] subjectPublicKeyByte = null;

    private boolean[] keyUsage = null;

    private Set keyPurposeSet = null;

    private boolean matchAllSubjectAltNames = true;

    private Set subjectAltNames = null;

    private Set subjectAltNamesByte = null;

    private int minMaxPathLen = -1;

    private Set policy = null;

    private Set policyOID = null;

    private Set pathToNames = null;

    private Set pathToNamesByte = null;

    /**
     * Creates an <code>X509CertSelector</code>. Initially, no criteria are
     * set so any <code>X509Certificate</code> will match.
     */
    public X509CertSelector()
    {
    }

    /**
     * Sets the certificateEquals criterion. The specified
     * <code>X509Certificate</code> must be equal to the
     * <code>X509Certificate</code> passed to the match method. If
     * <code>null</code>, then this check is not applied.<br />
     * <br />
     * This method is particularly useful when it is necessary to match a single
     * certificate. Although other criteria can be specified in conjunction with
     * the certificateEquals criterion, it is usually not practical or
     * necessary.
     * 
     * @param cert
     *            the X509Certificate to match (or <code>null</code>)
     * 
     * @see #getCertificate()
     */
    public void setCertificate(X509Certificate cert)
    {
        x509Cert = cert;
    }

    /**
     * Sets the serialNumber criterion. The specified serial number must match
     * the certificate serial number in the <code>X509Certificate</code>. If
     * <code>null</code>, any certificate serial number will do.
     * 
     * @param serial
     *            the certificate serial number to match (or <code>null</code>)
     * 
     * @see #getSerialNumber()
     */
    public void setSerialNumber(BigInteger serial)
    {
        serialNumber = serial;
    }

    /**
     * Sets the issuer criterion. The specified distinguished name must match
     * the issuer distinguished name in the <code>X509Certificate</code>. If
     * <code>null</code>, any issuer distinguished name will do.<br />
     * <br />
     * If <code>issuerDN</code> is not <code>null</code>, it should contain
     * a distinguished name, in RFC 2253 format.<br />
     * <br />
     * Uses {@link org.bouncycastle.asn1.x509.X509Name X509Name} for parsing the
     * issuerDN.
     * 
     * @param issuerDN
     *            a distinguished name in RFC 2253 format (or <code>null</code>)
     * 
     * @exception IOException
     *                if a parsing error occurs (incorrect form for DN)
     */
    public void setIssuer(String issuerDN) throws IOException
    {
        if (issuerDN == null)
        {
            this.issuerDN = null;
            this.issuerDNX509 = null;
        }
        else
        {
            X509Name nameX509;
            try
            {
                nameX509 = new X509Name(issuerDN);
            }
            catch (IllegalArgumentException ex)
            {
                throw new IOException(ex.getMessage());
            }
            this.issuerDNX509 = nameX509;
            this.issuerDN = issuerDN;
        }
    }

    /**
     * Sets the issuer criterion. The specified distinguished name must match
     * the issuer distinguished name in the <code>X509Certificate</code>. If
     * null is specified, the issuer criterion is disabled and any issuer
     * distinguished name will do.<br />
     * <br />
     * If <code>issuerDN</code> is not <code>null</code>, it should contain
     * a single DER encoded distinguished name, as defined in X.501. The ASN.1
     * notation for this structure is as follows.<br />
     * <br />
     * 
     * <pre>
     *    Name ::= CHOICE {
     *      RDNSequence }
     * 
     *    RDNSequence ::= SEQUENCE OF RDN
     * 
     *    RDN ::=
     *      SET SIZE (1 .. MAX) OF AttributeTypeAndValue
     * 
     *    AttributeTypeAndValue ::= SEQUENCE {
     *      type     AttributeType,
     *      value    AttributeValue }
     * 
     *    AttributeType ::= OBJECT IDENTIFIER
     * 
     *    AttributeValue ::= ANY DEFINED BY AttributeType
     *    ....
     *    DirectoryString ::= CHOICE {
     *      teletexString           TeletexString (SIZE (1..MAX)),
     *      printableString         PrintableString (SIZE (1..MAX)),
     *      universalString         UniversalString (SIZE (1..MAX)),
     *      utf8String              UTF8String (SIZE (1.. MAX)),
     *      bmpString               BMPString (SIZE (1..MAX)) }
     * </pre>
     * 
     * <br />
     * <br />
     * Note that the byte array specified here is cloned to protect against
     * subsequent modifications.<br />
     * <br />
     * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream},
     * {@link org.bouncycastle.asn1.ASN1Object ASN1Object},
     * {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence},
     * {@link org.bouncycastle.asn1.x509.X509Name X509Name}
     * 
     * @param issuerDN -
     *            a byte array containing the distinguished name in ASN.1 DER
     *            encoded form (or <code>null</code>)
     * 
     * @exception IOException
     *                if an encoding error occurs (incorrect form for DN)
     */
    public void setIssuer(byte[] issuerDN) throws IOException
    {
        if (issuerDN == null)
        {
            this.issuerDN = null;
            this.issuerDNX509 = null;
        }
        else
        {
            ByteArrayInputStream inStream = new ByteArrayInputStream(issuerDN);
            ASN1InputStream derInStream = new ASN1InputStream(inStream);
            ASN1Object obj = derInStream.readObject();
            if (obj instanceof ASN1Sequence)
            {
                this.issuerDNX509 = new X509Name((ASN1Sequence)obj);
            }
            else
            {
                throw new IOException("parsing error");
            }
            this.issuerDN = (byte[])issuerDN.clone();
        }
    }

    /**
     * Sets the subject criterion. The specified distinguished name must match
     * the subject distinguished name in the <code>X509Certificate</code>. If
     * null, any subject distinguished name will do.<br />
     * <br />
     * If <code>subjectDN</code> is not <code>null</code>, it should
     * contain a distinguished name, in RFC 2253 format.<br />
     * <br />
     * Uses {@link org.bouncycastle.asn1.x509.X509Name X509Name} for parsing the
     * subjectDN.
     * 
     * @param subjectDN
     *            a distinguished name in RFC 2253 format (or <code>null</code>)
     * 
     * @exception IOException
     *                if a parsing error occurs (incorrect form for DN)
     */
    public void setSubject(String subjectDN) throws IOException
    {
        if (subjectDN == null)
        {
            this.subjectDN = null;
            this.subjectDNX509 = null;
        }
        else
        {
            X509Name nameX509;
            try
            {
                nameX509 = new X509Name(subjectDN);
            }
            catch (IllegalArgumentException ex)
            {
                throw new IOException(ex.getMessage());
            }

            this.subjectDNX509 = nameX509;
            this.subjectDN = subjectDN;
        }
    }

    /**
     * Sets the subject criterion. The specified distinguished name must match
     * the subject distinguished name in the <code>X509Certificate</code>. If
     * null, any subject distinguished name will do.<br />
     * <br />
     * If <code>subjectDN</code> is not <code>null</code>, it should
     * contain a single DER encoded distinguished name, as defined in X.501. For
     * the ASN.1 notation for this structure, see
     * {@link #setIssuer(byte []) setIssuer(byte [] issuerDN)}.<br />
     * <br />
     * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream},
     * {@link org.bouncycastle.asn1.ASN1Object ASN1Object},
     * {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence},
     * {@link org.bouncycastle.asn1.x509.X509Name X509Name}
     * 
     * @param subjectDN
     *            a byte array containing the distinguished name in ASN.1 DER
     *            format (or <code>null</code>)
     * 
     * @exception IOException
     *                if an encoding error occurs (incorrect form for DN)
     */
    public void setSubject(byte[] subjectDN) throws IOException
    {
        if (subjectDN == null)
        {
            this.subjectDN = null;
            this.subjectDNX509 = null;
        }
        else
        {
            ByteArrayInputStream inStream = new ByteArrayInputStream(subjectDN);
            ASN1InputStream derInStream = new ASN1InputStream(inStream);
            ASN1Object obj = derInStream.readObject();

            if (obj instanceof ASN1Sequence)
            {
                this.subjectDNX509 = new X509Name((ASN1Sequence)obj);
            }
            else
            {
                throw new IOException("parsing error");
            }
            this.subjectDN = (byte[])subjectDN.clone();
        }
    }

    /**
     * Sets the subjectKeyIdentifier criterion. The <code>X509Certificate</code>
     * must contain a SubjectKeyIdentifier extension for which the contents of
     * the extension matches the specified criterion value. If the criterion
     * value is null, no subjectKeyIdentifier check will be done.<br />
     * <br />
     * If <code>subjectKeyID</code> is not <code>null</code>, it should
     * contain a single DER encoded value corresponding to the contents of the
     * extension value (not including the object identifier, criticality
     * setting, and encapsulating OCTET STRING) for a SubjectKeyIdentifier
     * extension. The ASN.1 notation for this structure follows.<br />
     * <br />
     * 
     * <pre>
     *    SubjectKeyIdentifier ::= KeyIdentifier
     * 
     *    KeyIdentifier ::= OCTET STRING
     * </pre>
     * 
     * <br />
     * <br />
     * Since the format of subject key identifiers is not mandated by any
     * standard, subject key identifiers are not parsed by the
     * <code>X509CertSelector</code>. Instead, the values are compared using
     * a byte-by-byte comparison.<br />
     * <br />
     * Note that the byte array supplied here is cloned to protect against
     * subsequent modifications.
     * 
     * @param subjectKeyID -
     *            the subject key identifier (or <code>null</code>)
     * 
     * @see #getSubjectKeyIdentifier()
     */
    public void setSubjectKeyIdentifier(byte[] subjectKeyID)
    {
        if (subjectKeyID == null)
        {
            this.subjectKeyID = null;
        }
        else
        {
            this.subjectKeyID = (byte[])subjectKeyID.clone();
        }
    }

    /**
     * Sets the authorityKeyIdentifier criterion. The
     * <code>X509Certificate</code> must contain an AuthorityKeyIdentifier
     * extension for which the contents of the extension value matches the
     * specified criterion value. If the criterion value is <code>null</code>,
     * no authorityKeyIdentifier check will be done.<br />
     * <br />
     * If <code>authorityKeyID</code> is not <code>null</code>, it should
     * contain a single DER encoded value corresponding to the contents of the
     * extension value (not including the object identifier, criticality
     * setting, and encapsulating OCTET STRING) for an AuthorityKeyIdentifier
     * extension. The ASN.1 notation for this structure follows.<br />
     * <br />
     * 
     * <pre>
     *    AuthorityKeyIdentifier ::= SEQUENCE {
     *      keyIdentifier             [0] KeyIdentifier           OPTIONAL,
     *      authorityCertIssuer       [1] GeneralNames            OPTIONAL,
     *      authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL  }
     * 
     *    KeyIdentifier ::= OCTET STRING
     * </pre>
     * 
     * <br />
     * <br />
     * Authority key identifiers are not parsed by the
     * <code>X509CertSelector</code>. Instead, the values are compared using
     * a byte-by-byte comparison.<br />
     * <br />
     * When the <code>keyIdentifier</code> field of
     * <code>AuthorityKeyIdentifier</code> is populated, the value is usually
     * taken from the SubjectKeyIdentifier extension in the issuer's
     * certificate. Note, however, that the result of
     * X509Certificate.getExtensionValue(<SubjectKeyIdentifier Object
     * Identifier>) on the issuer's certificate may NOT be used directly as the
     * input to setAuthorityKeyIdentifier. This is because the
     * SubjectKeyIdentifier contains only a KeyIdentifier OCTET STRING, and not
     * a SEQUENCE of KeyIdentifier, GeneralNames, and CertificateSerialNumber.
     * In order to use the extension value of the issuer certificate's
     * SubjectKeyIdentifier extension, it will be necessary to extract the value
     * of the embedded KeyIdentifier OCTET STRING, then DER encode this OCTET
     * STRING inside a SEQUENCE. For more details on SubjectKeyIdentifier, see
     * {@link #setSubjectKeyIdentifier(byte[])  setSubjectKeyIdentifier(byte[] subjectKeyID }).<br />
     * <br />
     * Note also that the byte array supplied here is cloned to protect against
     * subsequent modifications.
     * 
     * @param authorityKeyID
     *            the authority key identifier (or <code>null</code>)
     * 
     * @see #getAuthorityKeyIdentifier()
     */
    public void setAuthorityKeyIdentifier(byte[] authorityKeyID)
    {
        if (authorityKeyID == null)
        {
            this.authorityKeyID = null;
        }
        else
        {
            this.authorityKeyID = (byte[])authorityKeyID.clone();
        }
    }

    /**
     * Sets the certificateValid criterion. The specified date must fall within
     * the certificate validity period for the X509Certificate. If
     * <code>null</code>, no certificateValid check will be done.<br />
     * <br />
     * Note that the Date supplied here is cloned to protect against subsequent
     * modifications.
     * 
     * @param certValid
     *            the Date to check (or <code>null</code>)
     * 
     * @see #getCertificateValid()
     */
    public void setCertificateValid(Date certValid)
    {
        if (certValid == null)
        {
            this.certValid = null;
        }
        else
        {
            this.certValid = new Date(certValid.getTime());
        }
    }

    /**
     * Sets the privateKeyValid criterion. The specified date must fall within
     * the private key validity period for the X509Certificate. If
     * <code>null</code>, no privateKeyValid check will be done.<br />
     * <br />
     * Note that the Date supplied here is cloned to protect against subsequent
     * modifications.
     * 
     * @param privateKeyValid
     *            the Date to check (or <code>null</code>)
     * 
     * @see #getPrivateKeyValid()
     */
    public void setPrivateKeyValid(Date privateKeyValid)
    {
        if (privateKeyValid == null)
        {
            this.privateKeyValid = null;
        }
        else
        {
            this.privateKeyValid = new Date(privateKeyValid.getTime());
        }
    }

    /**
     * Sets the subjectPublicKeyAlgID criterion. The X509Certificate must
     * contain a subject public key with the specified algorithm. If
     * <code>null</code>, no subjectPublicKeyAlgID check will be done.
     * 
     * @param oid
     *            The object identifier (OID) of the algorithm to check for (or
     *            <code>null</code>). An OID is represented by a set of
     *            nonnegative integers separated by periods.
     * 
     * @exception IOException
     *                if the OID is invalid, such as the first component being
     *                not 0, 1 or 2 or the second component being greater than
     *                39.
     * 
     * @see #getSubjectPublicKeyAlgID()
     */
    public void setSubjectPublicKeyAlgID(String oid) throws IOException
    {
        CertUtil.parseOID(oid);
        subjectKeyAlgID = new ASN1ObjectIdentifier(oid);
    }

    /**
     * Sets the subjectPublicKey criterion. The X509Certificate must contain the
     * specified subject public key. If null, no subjectPublicKey check will be
     * done.
     * 
     * @param key
     *            the subject public key to check for (or null)
     * 
     * @see #getSubjectPublicKey()
     */
    public void setSubjectPublicKey(PublicKey key)
    {
        if (key == null)
        {
            subjectPublicKey = null;
            subjectPublicKeyByte = null;
        }
        else
        {
            subjectPublicKey = key;
            subjectPublicKeyByte = key.getEncoded();
        }
    }

    /**
     * Sets the subjectPublicKey criterion. The <code>X509Certificate</code>
     * must contain the specified subject public key. If <code>null</code>,
     * no subjectPublicKey check will be done.<br />
     * <br />
     * Because this method allows the public key to be specified as a byte
     * array, it may be used for unknown key types.<br />
     * <br />
     * If key is not <code>null</code>, it should contain a single DER
     * encoded SubjectPublicKeyInfo structure, as defined in X.509. The ASN.1
     * notation for this structure is as follows.<br />
     * <br />
     * 
     * <pre>
     *    SubjectPublicKeyInfo  ::=  SEQUENCE  {
     *      algorithm            AlgorithmIdentifier,
     *      subjectPublicKey     BIT STRING  }
     * 
     *    AlgorithmIdentifier  ::=  SEQUENCE  {
     *      algorithm               OBJECT IDENTIFIER,
     *      parameters              ANY DEFINED BY algorithm OPTIONAL  }
     *                                -- contains a value of the type
     *                                -- registered for use with the
     *                                -- algorithm object identifier value
     * </pre>
     * 
     * <br />
     * <br />
     * Note that the byte array supplied here is cloned to protect against
     * subsequent modifications.
     * 
     * @param key
     *            a byte array containing the subject public key in ASN.1 DER
     *            form (or <code>null</code>)
     * 
     * @exception IOException
     *                if an encoding error occurs (incorrect form for subject
     *                public key)
     * 
     * @see #getSubjectPublicKey()
     */
    public void setSubjectPublicKey(byte[] key) throws IOException
    {
        if (key == null)
        {
            subjectPublicKey = null;
            subjectPublicKeyByte = null;
        }
        else
        {
            subjectPublicKey = null;
            subjectPublicKeyByte = (byte[])key.clone();
            // TODO
            // try to generyte PublicKey Object from subjectPublicKeyByte
        }
    }

    /**
     * Sets the keyUsage criterion. The X509Certificate must allow the specified
     * keyUsage values. If null, no keyUsage check will be done. Note that an
     * X509Certificate that has no keyUsage extension implicitly allows all
     * keyUsage values.<br />
     * <br />
     * Note that the boolean array supplied here is cloned to protect against
     * subsequent modifications.
     * 
     * @param keyUsage
     *            a boolean array in the same format as the boolean array
     *            returned by X509Certificate.getKeyUsage(). Or
     *            <code>null</code>.
     * 
     * @see #getKeyUsage()
     */
    public void setKeyUsage(boolean[] keyUsage)
    {
        if (keyUsage == null)
        {
            this.keyUsage = null;
        }
        else
        {
            this.keyUsage = (boolean[])keyUsage.clone();
        }
    }

    /**
     * Sets the extendedKeyUsage criterion. The <code>X509Certificate</code>
     * must allow the specified key purposes in its extended key usage
     * extension. If <code>keyPurposeSet</code> is empty or <code>null</code>,
     * no extendedKeyUsage check will be done. Note that an
     * <code>X509Certificate</code> that has no extendedKeyUsage extension
     * implicitly allows all key purposes.<br />
     * <br />
     * Note that the Set is cloned to protect against subsequent modifications.<br />
     * <br />
     * Uses {@link org.bouncycastle.asn1.x509.KeyPurposeId KeyPurposeId}
     * 
     * @param keyPurposeSet
     *            a <code>Set</code> of key purpose OIDs in string format (or
     *            <code>null</code>). Each OID is represented by a set of
     *            nonnegative integers separated by periods.
     * 
     * @exception IOException
     *                if the OID is invalid, such as the first component being
     *                not 0, 1 or 2 or the second component being greater than
     *                39.
     * 
     * @see #getExtendedKeyUsage()
     */
    public void setExtendedKeyUsage(Set keyPurposeSet) throws IOException
    {
        if (keyPurposeSet == null || keyPurposeSet.isEmpty())
        {
            this.keyPurposeSet = keyPurposeSet;
        }
        else
        {
            this.keyPurposeSet = new HashSet();
            Iterator iter = keyPurposeSet.iterator();
            Object obj;
            KeyPurposeId purposeID;
            while (iter.hasNext())
            {
                obj = iter.next();
                if (obj instanceof String)
                {
                    purposeID = (KeyPurposeId)keyPurposeIdMap.get((String)obj);
                    if (purposeID == null)
                    {
                        throw new IOException("unknown purposeID "
                                + (String)obj);
                    }
                    this.keyPurposeSet.add(purposeID);
                }
            }
        }
    }

    /**
     * Enables/disables matching all of the subjectAlternativeNames specified in
     * the {@link #setSubjectAlternativeNames setSubjectAlternativeNames} or
     * {@link #addSubjectAlternativeName addSubjectAlternativeName} methods. If
     * enabled, the <code>X509Certificate</code> must contain all of the
     * specified subject alternative names. If disabled, the X509Certificate
     * must contain at least one of the specified subject alternative names.<br />
     * <br />
     * The matchAllNames flag is <code>true</code> by default.
     * 
     * @param matchAllNames
     *            if <code>true</code>, the flag is enabled; if
     *            <code>false</code>, the flag is disabled.
     * 
     * @see #getMatchAllSubjectAltNames()
     */
    public void setMatchAllSubjectAltNames(boolean matchAllNames)
    {
        matchAllSubjectAltNames = matchAllNames;
    }

    /**
     * Sets the subjectAlternativeNames criterion. The
     * <code>X509Certificate</code> must contain all or at least one of the
     * specified subjectAlternativeNames, depending on the value of the
     * matchAllNames flag (see {@link #setMatchAllSubjectAltNames}).<br />
     * <br />
     * This method allows the caller to specify, with a single method call, the
     * complete set of subject alternative names for the subjectAlternativeNames
     * criterion. The specified value replaces the previous value for the
     * subjectAlternativeNames criterion.<br />
     * <br />
     * The <code>names</code> parameter (if not <code>null</code>) is a
     * <code>Collection</code> with one entry for each name to be included in
     * the subject alternative name criterion. Each entry is a <code>List</code>
     * whose first entry is an <code>Integer</code> (the name type, 0-8) and
     * whose second entry is a <code>String</code> or a byte array (the name,
     * in string or ASN.1 DER encoded form, respectively). There can be multiple
     * names of the same type. If <code>null</code> is supplied as the value
     * for this argument, no subjectAlternativeNames check will be performed.<br />
     * <br />
     * Each subject alternative name in the <code>Collection</code> may be
     * specified either as a <code>String</code> or as an ASN.1 encoded byte
     * array. For more details about the formats used, see
     * {@link #addSubjectAlternativeName(int, String) addSubjectAlternativeName(int type, String name)}
     * and
     * {@link #addSubjectAlternativeName(int, byte[]) addSubjectAlternativeName(int type, byte [] name}).<br />
     * <br />
     * Note that the <code>names</code> parameter can contain duplicate names
     * (same name and name type), but they may be removed from the
     * <code>Collection</code> of names returned by the
     * {@link #getSubjectAlternativeNames} method.<br />
     * <br />
     * Note that a deep copy is performed on the Collection to protect against
     * subsequent modifications.
     * 
     * @param names -
     *            a Collection of names (or null)
     * 
     * @exception IOException
     *                if a parsing error occurs
     * 
     * @see #getSubjectAlternativeNames()
     */
    public void setSubjectAlternativeNames(Collection names) throws IOException
    {
        try
        {
            if (names == null || names.isEmpty())
            {
                subjectAltNames = null;
                subjectAltNamesByte = null;
            }
            else
            {
                subjectAltNames = new HashSet();
                subjectAltNamesByte = new HashSet();
                Iterator iter = names.iterator();
                List item;
                int type;
                Object data;
                while (iter.hasNext())
                {
                    item = (List)iter.next();
                    type = ((Integer)item.get(0)).intValue();
                    data = item.get(1);
                    if (data instanceof String)
                    {
                        addSubjectAlternativeName(type, (String)data);
                    }
                    else if (data instanceof byte[])
                    {
                        addSubjectAlternativeName(type, (byte[])data);
                    }
                    else
                    {
                        throw new IOException(
                                "parsing error: unknown data type");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw new IOException("parsing exception:\n" + ex.toString());
        }
    }

    /**
     * Adds a name to the subjectAlternativeNames criterion. The
     * <code>X509Certificate</code> must contain all or at least one of the
     * specified subjectAlternativeNames, depending on the value of the
     * matchAllNames flag (see {@link #setMatchAllSubjectAltNames}).<br />
     * <br />
     * This method allows the caller to add a name to the set of subject
     * alternative names. The specified name is added to any previous value for
     * the subjectAlternativeNames criterion. If the specified name is a
     * duplicate, it may be ignored.<br />
     * <br />
     * The name is provided in string format. RFC 822, DNS, and URI names use
     * the well-established string formats for those types (subject to the
     * restrictions included in RFC 2459). IPv4 address names are supplied using
     * dotted quad notation. OID address names are represented as a series of
     * nonnegative integers separated by periods. And directory names
     * (distinguished names) are supplied in RFC 2253 format. No standard string
     * format is defined for otherNames, X.400 names, EDI party names, IPv6
     * address names, or any other type of names. They should be specified using
     * the
     * {@link #addSubjectAlternativeName(int, byte[]) addSubjectAlternativeName(int type, byte [] name)}
     * method.
     * 
     * @param type
     *            the name type (0-8, as specified in RFC 2459, section 4.2.1.7)
     * @param name -
     *            the name in string form (not null)
     * 
     * @exception IOException
     *                if a parsing error occurs
     */
    public void addSubjectAlternativeName(int type, String name)
            throws IOException
    {
        // TODO full implementation of CertUtil.parseGeneralName
        byte[] encoded = CertUtil.parseGeneralName(type, name);
        List tmpList = new ArrayList();
        tmpList.add(Integers.valueOf(type));
        tmpList.add(name);
        subjectAltNames.add(tmpList);
        tmpList.set(1, encoded);
        subjectAltNamesByte.add(tmpList);
    }

    /**
     * Adds a name to the subjectAlternativeNames criterion. The
     * <code>X509Certificate</code> must contain all or at least one of the
     * specified subjectAlternativeNames, depending on the value of the
     * matchAllNames flag (see {@link #setMatchAllSubjectAltNames}).<br />
     * <br />
     * This method allows the caller to add a name to the set of subject
     * alternative names. The specified name is added to any previous value for
     * the subjectAlternativeNames criterion. If the specified name is a
     * duplicate, it may be ignored.<br />
     * <br />
     * The name is provided as a byte array. This byte array should contain the
     * DER encoded name, as it would appear in the GeneralName structure defined
     * in RFC 2459 and X.509. The encoded byte array should only contain the
     * encoded value of the name, and should not include the tag associated with
     * the name in the GeneralName structure. The ASN.1 definition of this
     * structure appears below.<br />
     * <br />
     * 
     * <pre>
     *    GeneralName ::= CHOICE {
     *        otherName                       [0]     OtherName,
     *        rfc822Name                      [1]     IA5String,
     *        dNSName                         [2]     IA5String,
     *        x400Address                     [3]     ORAddress,
     *        directoryName                   [4]     Name,
     *        ediPartyName                    [5]     EDIPartyName,
     *        uniformResourceIdentifier       [6]     IA5String,
     *        iPAddress                       [7]     OCTET STRING,
     *        registeredID                    [8]     OBJECT IDENTIFIER}
     * </pre>
     * 
     * <br />
     * <br />
     * Note that the byte array supplied here is cloned to protect against
     * subsequent modifications.<br />
     * <br />
     * <b>TODO: check encoded format</b>
     * 
     * @param type
     *            the name type (0-8, as listed above)
     * @param name
     *            a byte array containing the name in ASN.1 DER encoded form
     * 
     * @exception IOException
     *                if a parsing error occurs
     */
    public void addSubjectAlternativeName(int type, byte[] name)
            throws IOException
    {
        // TODO check encoded format
        List tmpList = new ArrayList();
        tmpList.add(Integers.valueOf(type));
        tmpList.add(name.clone());
        subjectAltNames.add(tmpList);
        subjectAltNamesByte.add(tmpList);
    }

    /**
     * Sets the name constraints criterion. The <code>X509Certificate</code>
     * must have subject and subject alternative names that meet the specified
     * name constraints.<br />
     * <br />
     * The name constraints are specified as a byte array. This byte array
     * should contain the DER encoded form of the name constraints, as they
     * would appear in the NameConstraints structure defined in RFC 2459 and
     * X.509. The ASN.1 definition of this structure appears below.<br />
     * <br />
     * 
     * <pre>
     *   NameConstraints ::= SEQUENCE {
     *        permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
     *        excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
     * 
     *   GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
     * 
     *   GeneralSubtree ::= SEQUENCE {
     *        base                    GeneralName,
     *        minimum         [0]     BaseDistance DEFAULT 0,
     *        maximum         [1]     BaseDistance OPTIONAL }
     * 
     *   BaseDistance ::= INTEGER (0..MAX)
     * 
     *   GeneralName ::= CHOICE {
     *        otherName                       [0]     OtherName,
     *        rfc822Name                      [1]     IA5String,
     *        dNSName                         [2]     IA5String,
     *        x400Address                     [3]     ORAddress,
     *        directoryName                   [4]     Name,
     *        ediPartyName                    [5]     EDIPartyName,
     *        uniformResourceIdentifier       [6]     IA5String,
     *        iPAddress                       [7]     OCTET STRING,
     *        registeredID                    [8]     OBJECT IDENTIFIER}
     * </pre>
     * 
     * <br />
     * <br />
     * Note that the byte array supplied here is cloned to protect against
     * subsequent modifications.<br />
     * <br />
     * <b>TODO: implement this</b>
     * 
     * @param bytes
     *            a byte array containing the ASN.1 DER encoding of a
     *            NameConstraints extension to be used for checking name
     *            constraints. Only the value of the extension is included, not
     *            the OID or criticality flag. Can be <code>null</code>, in
     *            which case no name constraints check will be performed
     * 
     * @exception IOException
     *                if a parsing error occurs
     * @exception UnsupportedOperationException
     *                because this method is not supported
     * @see #getNameConstraints()
     */
    public void setNameConstraints(byte[] bytes) throws IOException
    {
        throw new UnsupportedOperationException();
    }

    /**
     * Sets the basic constraints constraint. If the value is greater than or
     * equal to zero, <code>X509Certificates</code> must include a
     * basicConstraints extension with a pathLen of at least this value. If the
     * value is -2, only end-entity certificates are accepted. If the value is
     * -1, no check is done.<br />
     * <br />
     * This constraint is useful when building a certification path forward
     * (from the target toward the trust anchor. If a partial path has been
     * built, any candidate certificate must have a maxPathLen value greater
     * than or equal to the number of certificates in the partial path.
     * 
     * @param minMaxPathLen
     *            the value for the basic constraints constraint
     * 
     * @exception IllegalArgumentException
     *                if the value is less than -2
     * 
     * @see #getBasicConstraints()
     */
    public void setBasicConstraints(int minMaxPathLen)
    {
        if (minMaxPathLen < -2)
        {
            throw new IllegalArgumentException("minMaxPathLen must be >= -2");
        }

        this.minMaxPathLen = minMaxPathLen;
    }

    /**
     * Sets the policy constraint. The X509Certificate must include at least one
     * of the specified policies in its certificate policies extension. If
     * certPolicySet is empty, then the X509Certificate must include at least
     * some specified policy in its certificate policies extension. If
     * certPolicySet is null, no policy check will be performed.<br />
     * <br />
     * Note that the Set is cloned to protect against subsequent modifications.<br />
     * <br />
     * <b>TODO: implement match check for this</b>
     * 
     * @param certPolicySet
     *            a Set of certificate policy OIDs in string format (or null).
     *            Each OID is represented by a set of nonnegative integers
     *            separated by periods.
     * 
     * @exception IOException
     *                if a parsing error occurs on the OID such as the first
     *                component is not 0, 1 or 2 or the second component is
     *                greater than 39.
     * 
     * @see #getPolicy()
     */
    public void setPolicy(Set certPolicySet) throws IOException
    {
        if (certPolicySet == null)
        {
            policy = null;
            policyOID = null;
        }
        else
        {
            policyOID = new HashSet();
            Iterator iter = certPolicySet.iterator();
            Object item;
            while (iter.hasNext())
            {
                item = iter.next();
                if (item instanceof String)
                {
                    CertUtil.parseOID((String)item);
                    policyOID.add(new ASN1ObjectIdentifier((String)item));
                }
                else
                {
                    throw new IOException(
                            "certPolicySet contains null values or non String objects");
                }
            }
            policy = new HashSet(certPolicySet);
        }
    }

    /**
     * Sets the pathToNames criterion. The <code>X509Certificate</code> must
     * not include name constraints that would prohibit building a path to the
     * specified names.<br />
     * <br />
     * This method allows the caller to specify, with a single method call, the
     * complete set of names which the <code>X509Certificates</code>'s name
     * constraints must permit. The specified value replaces the previous value
     * for the pathToNames criterion.<br />
     * <br />
     * This constraint is useful when building a certification path forward
     * (from the target toward the trust anchor. If a partial path has been
     * built, any candidate certificate must not include name constraints that
     * would prohibit building a path to any of the names in the partial path.<br />
     * <br />
     * The names parameter (if not <code>null</code>) is a
     * <code>Collection</code> with one entry for each name to be included in
     * the pathToNames criterion. Each entry is a <code>List</code> whose
     * first entry is an Integer (the name type, 0-8) and whose second entry is
     * a <code>String</code> or a byte array (the name, in string or ASN.1 DER
     * encoded form, respectively). There can be multiple names of the same
     * type. If <code>null</code> is supplied as the value for this argument,
     * no pathToNames check will be performed.<br />
     * <br />
     * Each name in the Collection may be specified either as a String or as an
     * ASN.1 encoded byte array. For more details about the formats used, see
     * {@link #addPathToName(int, String) addPathToName(int type, String name)}
     * and
     * {@link #addPathToName(int, byte[]) addPathToName(int type, byte [] name)}.<br />
     * <br />
     * Note that the names parameter can contain duplicate names (same name and
     * name type), but they may be removed from the Collection of names returned
     * by the {@link #getPathToNames} method.<br />
     * <br />
     * Note that a deep copy is performed on the Collection to protect against
     * subsequent modifications.<br />
     * <br />
     * <b>TODO: implement this match check for this</b>
     * 
     * @param names
     *            a Collection with one entry per name (or <code>null</code>)
     * 
     * @exception IOException
     *                if a parsing error occurs
     * @exception UnsupportedOperationException
     *                because this method is not supported
     * 
     * @see #getPathToNames()
     */
    public void setPathToNames(Collection names) throws IOException
    {
        try
        {
            if (names == null || names.isEmpty())
            {
                pathToNames = null;
                pathToNamesByte = null;
            }
            else
            {
                pathToNames = new HashSet();
                pathToNamesByte = new HashSet();
                Iterator iter = names.iterator();
                List item;
                int type;
                Object data;

                while (iter.hasNext())
                {
                    item = (List)iter.next();
                    type = ((Integer)item.get(0)).intValue();
                    data = item.get(1);
                    if (data instanceof String)
                    {
                        addPathToName(type, (String)data);
                    }
                    else if (data instanceof byte[])
                    {
                        addPathToName(type, (byte[])data);
                    }
                    else
                    {
                        throw new IOException(
                                "parsing error: unknown data type");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw new IOException("parsing exception:\n" + ex.toString());
        }
    }

    /**
     * Adds a name to the pathToNames criterion. The
     * <code>X509Certificate</code> must not include name constraints that
     * would prohibit building a path to the specified name.<br />
     * <br />
     * This method allows the caller to add a name to the set of names which the
     * <code>X509Certificates</code>'s name constraints must permit. The
     * specified name is added to any previous value for the pathToNames
     * criterion. If the name is a duplicate, it may be ignored.<br />
     * <br />
     * The name is provided in string format. RFC 822, DNS, and URI names use
     * the well-established string formats for those types (subject to the
     * restrictions included in RFC 2459). IPv4 address names are supplied using
     * dotted quad notation. OID address names are represented as a series of
     * nonnegative integers separated by periods. And directory names
     * (distinguished names) are supplied in RFC 2253 format. No standard string
     * format is defined for otherNames, X.400 names, EDI party names, IPv6
     * address names, or any other type of names. They should be specified using
     * the
     * {@link #addPathToName(int, byte[]) addPathToName(int type, byte [] name)}
     * method.<br />
     * <br />
     * <b>TODO: implement this match check for this</b>
     * 
     * @param type
     *            the name type (0-8, as specified in RFC 2459, section 4.2.1.7)
     * @param name
     *            the name in string form
     * 
     * @exceptrion IOException if a parsing error occurs
     */
    public void addPathToName(int type, String name) throws IOException
    {
        // TODO full implementation of CertUtil.parseGeneralName
        byte[] encoded = CertUtil.parseGeneralName(type, name);
        List tmpList = new ArrayList();
        tmpList.add(Integers.valueOf(type));
        tmpList.add(name);
        pathToNames.add(tmpList);
        tmpList.set(1, encoded);
        pathToNamesByte.add(tmpList);
        throw new UnsupportedOperationException();
    }

    /**
     * Adds a name to the pathToNames criterion. The
     * <code>X509Certificate</code> must not include name constraints that
     * would prohibit building a path to the specified name.<br />
     * <br />
     * This method allows the caller to add a name to the set of names which the
     * <code>X509Certificates</code>'s name constraints must permit. The
     * specified name is added to any previous value for the pathToNames
     * criterion. If the name is a duplicate, it may be ignored.<br />
     * <br />
     * The name is provided as a byte array. This byte array should contain the
     * DER encoded name, as it would appear in the GeneralName structure defined
     * in RFC 2459 and X.509. The ASN.1 definition of this structure appears in
     * the documentation for
     * {@link #addSubjectAlternativeName(int,byte[]) addSubjectAlternativeName(int type, byte[] name)}.<br />
     * <br />
     * Note that the byte array supplied here is cloned to protect against
     * subsequent modifications.<br />
     * <br />
     * <b>TODO: implement this match check for this</b>
     * 
     * @param type
     *            the name type (0-8, as specified in RFC 2459, section 4.2.1.7)
     * @param name
     *            a byte array containing the name in ASN.1 DER encoded form
     * 
     * @exception IOException
     *                if a parsing error occurs
     */
    public void addPathToName(int type, byte[] name) throws IOException
    {
        // TODO check encoded format
        List tmpList = new ArrayList();
        tmpList.add(Integers.valueOf(type));
        tmpList.add(name.clone());
        pathToNames.add(tmpList);
        pathToNamesByte.add(tmpList);
    }

    /**
     * Returns the certificateEquals criterion. The specified
     * <code>X509Certificate</code> must be equal to the
     * <code>X509Certificate</code> passed to the match method. If
     * <code>null</code>, this check is not applied.
     * 
     * @retrun the <code>X509Certificate</code> to match (or <code>null</code>)
     * 
     * @see #setCertificate(java.security.cert.X509Certificate)
     */
    public X509Certificate getCertificate()
    {
        return x509Cert;
    }

    /**
     * Returns the serialNumber criterion. The specified serial number must
     * match the certificate serial number in the <code>X509Certificate</code>.
     * If <code>null</code>, any certificate serial number will do.
     * 
     * @return the certificate serial number to match (or <code>null</code>)
     * 
     * @see #setSerialNumber(java.math.BigInteger)
     */
    public BigInteger getSerialNumber()
    {
        return serialNumber;
    }

    /**
     * Returns the issuer criterion as a String. This distinguished name must
     * match the issuer distinguished name in the <code>X509Certificate</code>.
     * If <code>null</code>, the issuer criterion is disabled and any issuer
     * distinguished name will do.<br />
     * <br />
     * If the value returned is not <code>null</code>, it is a distinguished
     * name, in RFC 2253 format.<br />
     * <br />
     * Uses {@link org.bouncycastle.asn1.x509.X509Name X509Name} for formatiing
     * byte[] issuerDN to String.
     * 
     * @return the required issuer distinguished name in RFC 2253 format (or
     *         <code>null</code>)
     */
    public String getIssuerAsString()
    {
        if (issuerDN instanceof String)
        {
            return new String((String)issuerDN);
        }
        else if (issuerDNX509 != null)
        {
            return issuerDNX509.toString();
        }

        return null;
    }

    /**
     * Returns the issuer criterion as a byte array. This distinguished name
     * must match the issuer distinguished name in the
     * <code>X509Certificate</code>. If <code>null</code>, the issuer
     * criterion is disabled and any issuer distinguished name will do.<br />
     * <br />
     * If the value returned is not <code>null</code>, it is a byte array
     * containing a single DER encoded distinguished name, as defined in X.501.
     * The ASN.1 notation for this structure is supplied in the documentation
     * for {@link #setIssuer(byte[]) setIssuer(byte [] issuerDN)}.<br />
     * <br />
     * Note that the byte array returned is cloned to protect against subsequent
     * modifications.<br />
     * <br />
     * Uses {@link org.bouncycastle.asn1.DEROutputStream DEROutputStream},
     * {@link org.bouncycastle.asn1.x509.X509Name X509Name} to gnerate byte[]
     * output for String issuerDN.
     * 
     * @return a byte array containing the required issuer distinguished name in
     *         ASN.1 DER format (or <code>null</code>)
     * 
     * @exception IOException
     *                if an encoding error occurs
     */
    public byte[] getIssuerAsBytes() throws IOException
    {
        if (issuerDN instanceof byte[])
        {
            return (byte[])((byte[])issuerDN).clone();
        }
        else if (issuerDNX509 != null)
        {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            DEROutputStream derOutStream = new DEROutputStream(outStream);

            derOutStream.writeObject(issuerDNX509.toASN1Primitive());
            derOutStream.close();

            return outStream.toByteArray();
        }

        return null;
    }

    /**
     * Returns the subject criterion as a String. This distinguished name must
     * match the subject distinguished name in the <code>X509Certificate</code>.
     * If <code>null</code>, the subject criterion is disabled and any
     * subject distinguished name will do.<br />
     * <br />
     * If the value returned is not <code>null</code>, it is a distinguished
     * name, in RFC 2253 format.<br />
     * <br />
     * Uses {@link org.bouncycastle.asn1.x509.X509Name X509Name} for formatiing
     * byte[] subjectDN to String.
     * 
     * @return the required subject distinguished name in RFC 2253 format (or
     *         <code>null</code>)
     */
    public String getSubjectAsString()
    {
        if (subjectDN instanceof String)
        {
            return new String((String)subjectDN);
        }
        else if (subjectDNX509 != null)
        {
            return subjectDNX509.toString();
        }

        return null;
    }

    /**
     * Returns the subject criterion as a byte array. This distinguished name
     * must match the subject distinguished name in the
     * <code>X509Certificate</code>. If <code>null</code>, the subject
     * criterion is disabled and any subject distinguished name will do.<br />
     * <br />
     * If the value returned is not <code>null</code>, it is a byte array
     * containing a single DER encoded distinguished name, as defined in X.501.
     * The ASN.1 notation for this structure is supplied in the documentation
     * for {@link #setSubject(byte [] subjectDN) setSubject(byte [] subjectDN)}.<br />
     * <br />
     * Note that the byte array returned is cloned to protect against subsequent
     * modifications.<br />
     * <br />
     * Uses {@link org.bouncycastle.asn1.DEROutputStream DEROutputStream},
     * {@link org.bouncycastle.asn1.x509.X509Name X509Name} to gnerate byte[]
     * output for String subjectDN.
     * 
     * @return a byte array containing the required subject distinguished name
     *         in ASN.1 DER format (or <code>null</code>)
     * 
     * @exception IOException
     *                if an encoding error occurs
     */
    public byte[] getSubjectAsBytes() throws IOException
    {
        if (subjectDN instanceof byte[])
        {
            return (byte[])((byte[])subjectDN).clone();
        }
        else if (subjectDNX509 != null)
        {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            DEROutputStream derOutStream = new DEROutputStream(outStream);

            derOutStream.writeObject(subjectDNX509.toASN1Primitive());
            derOutStream.close();

            return outStream.toByteArray();
        }

        return null;
    }

    /**
     * Returns the subjectKeyIdentifier criterion. The
     * <code>X509Certificate</code> must contain a SubjectKeyIdentifier
     * extension with the specified value. If <code>null</code>, no
     * subjectKeyIdentifier check will be done.<br />
     * <br />
     * Note that the byte array returned is cloned to protect against subsequent
     * modifications.
     * 
     * @return the key identifier (or <code>null</code>)
     * 
     * @see #setSubjectKeyIdentifier
     */
    public byte[] getSubjectKeyIdentifier()
    {
        if (subjectKeyID != null)
        {
            return (byte[])subjectKeyID.clone();
        }

        return null;
    }

    /**
     * Returns the authorityKeyIdentifier criterion. The
     * <code>X509Certificate</code> must contain a AuthorityKeyIdentifier
     * extension with the specified value. If <code>null</code>, no
     * authorityKeyIdentifier check will be done.<br />
     * <br />
     * Note that the byte array returned is cloned to protect against subsequent
     * modifications.
     * 
     * @return the key identifier (or <code>null</code>)
     * 
     * @see #setAuthorityKeyIdentifier
     */
    public byte[] getAuthorityKeyIdentifier()
    {
        if (authorityKeyID != null)
        {
            return (byte[])authorityKeyID.clone();
        }

        return null;
    }

    /**
     * Returns the certificateValid criterion. The specified date must fall
     * within the certificate validity period for the
     * <code>X509Certificate</code>. If <code>null</code>, no
     * certificateValid check will be done.<br />
     * <br />
     * Note that the <code>Date</code> returned is cloned to protect against
     * subsequent modifications.
     * 
     * @return the <code>Date</code> to check (or <code>null</code>)
     * 
     * @see #setCertificateValid
     */
    public Date getCertificateValid()
    {
        if (certValid != null)
        {
            return new Date(certValid.getTime());
        }

        return null;
    }

    /**
     * Returns the privateKeyValid criterion. The specified date must fall
     * within the private key validity period for the
     * <code>X509Certificate</code>. If <code>null</code>, no
     * privateKeyValid check will be done.<br />
     * <br />
     * Note that the <code>Date</code> returned is cloned to protect against
     * subsequent modifications.
     * 
     * @return the <code>Date</code> to check (or <code>null</code>)
     * 
     * @see #setPrivateKeyValid
     */
    public Date getPrivateKeyValid()
    {
        if (privateKeyValid != null)
        {
            return new Date(privateKeyValid.getTime());
        }

        return null;
    }

    /**
     * Returns the subjectPublicKeyAlgID criterion. The
     * <code>X509Certificate</code> must contain a subject public key with the
     * specified algorithm. If <code>null</code>, no subjectPublicKeyAlgID
     * check will be done.
     * 
     * @return the object identifier (OID) of the signature algorithm to check
     *         for (or <code>null</code>). An OID is represented by a set of
     *         nonnegative integers separated by periods.
     * 
     * @see #setSubjectPublicKeyAlgID
     */
    public String getSubjectPublicKeyAlgID()
    {
        if (subjectKeyAlgID != null)
        {
            return subjectKeyAlgID.toString();
        }

        return null;
    }

    /**
     * Returns the subjectPublicKey criterion. The <code>X509Certificate</code>
     * must contain the specified subject public key. If <code>null</code>,
     * no subjectPublicKey check will be done.
     * 
     * @return the subject public key to check for (or <code>null</code>)
     * 
     * @see #setSubjectPublicKey
     */
    public PublicKey getSubjectPublicKey()
    {
        return subjectPublicKey;
    }

    /**
     * Returns the keyUsage criterion. The <code>X509Certificate</code> must
     * allow the specified keyUsage values. If null, no keyUsage check will be
     * done.<br />
     * <br />
     * Note that the boolean array returned is cloned to protect against
     * subsequent modifications.
     * 
     * @return a boolean array in the same format as the boolean array returned
     *         by
     *         {@link X509Certificate#getKeyUsage() X509Certificate.getKeyUsage()}.
     *         Or <code>null</code>.
     * 
     * @see #setKeyUsage
     */
    public boolean[] getKeyUsage()
    {
        if (keyUsage != null)
        {
            return (boolean[])keyUsage.clone();
        }

        return null;
    }

    /**
     * Returns the extendedKeyUsage criterion. The <code>X509Certificate</code>
     * must allow the specified key purposes in its extended key usage
     * extension. If the <code>keyPurposeSet</code> returned is empty or
     * <code>null</code>, no extendedKeyUsage check will be done. Note that
     * an <code>X509Certificate</code> that has no extendedKeyUsage extension
     * implicitly allows all key purposes.
     * 
     * @return an immutable <code>Set</code> of key purpose OIDs in string
     *         format (or <code>null</code>)
     * @see #setExtendedKeyUsage
     */
    public Set getExtendedKeyUsage()
    {
        if (keyPurposeSet == null || keyPurposeSet.isEmpty())
        {
            return keyPurposeSet;
        }

        Set returnSet = new HashSet();
        Iterator iter = keyPurposeSet.iterator();
        while (iter.hasNext())
        {
            returnSet.add(iter.next().toString());
        }

        return Collections.unmodifiableSet(returnSet);
    }

    /**
     * Indicates if the <code>X509Certificate</code> must contain all or at
     * least one of the subjectAlternativeNames specified in the
     * {@link #setSubjectAlternativeNames setSubjectAlternativeNames} or
     * {@link #addSubjectAlternativeName addSubjectAlternativeName} methods. If
     * <code>true</code>, the <code>X509Certificate</code> must contain all
     * of the specified subject alternative names. If <code>false</code>, the
     * <code>X509Certificate</code> must contain at least one of the specified
     * subject alternative names.
     * 
     * @return <code>true</code> if the flag is enabled; <code>false</code>
     *         if the flag is disabled. The flag is <code>true</code> by
     *         default.
     * 
     * @see #setMatchAllSubjectAltNames
     */
    public boolean getMatchAllSubjectAltNames()
    {
        return matchAllSubjectAltNames;
    }

    /**
     * Returns a copy of the subjectAlternativeNames criterion. The
     * <code>X509Certificate</code> must contain all or at least one of the
     * specified subjectAlternativeNames, depending on the value of the
     * matchAllNames flag (see {@link #getMatchAllSubjectAltNames
     * getMatchAllSubjectAltNames}). If the value returned is <code>null</code>,
     * no subjectAlternativeNames check will be performed.<br />
     * <br />
     * If the value returned is not <code>null</code>, it is a
     * <code>Collection</code> with one entry for each name to be included in
     * the subject alternative name criterion. Each entry is a <code>List</code>
     * whose first entry is an <code>Integer</code> (the name type, 0-8) and
     * whose second entry is a <code>String</code> or a byte array (the name,
     * in string or ASN.1 DER encoded form, respectively). There can be multiple
     * names of the same type. Note that the <code>Collection</code> returned
     * may contain duplicate names (same name and name type).<br />
     * <br />
     * Each subject alternative name in the <code>Collection</code> may be
     * specified either as a <code>String</code> or as an ASN.1 encoded byte
     * array. For more details about the formats used, see
     * {@link #addSubjectAlternativeName(int type, String name) 
     * addSubjectAlternativeName(int type, String name)} and
     * {@link #addSubjectAlternativeName(int type, byte [] name) 
     * addSubjectAlternativeName(int type, byte [] name)}.<br />
     * <br />
     * Note that a deep copy is performed on the <code>Collection</code> to
     * protect against subsequent modifications.
     * 
     * @return a <code>Collection</code> of names (or <code>null</code>)
     * 
     * @see #setSubjectAlternativeNames
     */
    public Collection getSubjectAlternativeNames()
    {
        if (subjectAltNames != null)
        {
            return null;
        }

        Set returnAltNames = new HashSet();
        List returnList;
        Iterator iter = subjectAltNames.iterator();
        List obj;
        while (iter.hasNext())
        {
            obj = (List)iter.next();
            returnList = new ArrayList();
            returnList.add(obj.get(0));
            if (obj.get(1) instanceof byte[])
            {
                returnList.add(((byte[])obj.get(1)).clone());
            }
            else
            {
                returnList.add(obj.get(1));
            }
            returnAltNames.add(returnList);
        }

        return returnAltNames;
    }

    /**
     * Returns the name constraints criterion. The <code>X509Certificate</code>
     * must have subject and subject alternative names that meet the specified
     * name constraints.<br />
     * <br />
     * The name constraints are returned as a byte array. This byte array
     * contains the DER encoded form of the name constraints, as they would
     * appear in the NameConstraints structure defined in RFC 2459 and X.509.
     * The ASN.1 notation for this structure is supplied in the documentation
     * for
     * {@link #setNameConstraints(byte [] bytes) setNameConstraints(byte [] bytes)}.<br />
     * <br />
     * Note that the byte array returned is cloned to protect against subsequent
     * modifications.<br />
     * <br />
     * <b>TODO: implement this</b>
     * 
     * @return a byte array containing the ASN.1 DER encoding of a
     *         NameConstraints extension used for checking name constraints.
     *         <code>null</code> if no name constraints check will be
     *         performed.
     * 
     * @exception UnsupportedOperationException
     *                because this method is not supported
     * 
     * @see #setNameConstraints
     */
    public byte[] getNameConstraints()
    {
        throw new UnsupportedOperationException();
    }

    /**
     * Returns the basic constraints constraint. If the value is greater than or
     * equal to zero, the <code>X509Certificates</code> must include a
     * basicConstraints extension with a pathLen of at least this value. If the
     * value is -2, only end-entity certificates are accepted. If the value is
     * -1, no basicConstraints check is done.
     * 
     * @return the value for the basic constraints constraint
     * 
     * @see #setBasicConstraints
     */
    public int getBasicConstraints()
    {
        return minMaxPathLen;
    }

    /**
     * Returns the policy criterion. The <code>X509Certificate</code> must
     * include at least one of the specified policies in its certificate
     * policies extension. If the <code>Set</code> returned is empty, then the
     * <code>X509Certificate</code> must include at least some specified
     * policy in its certificate policies extension. If the <code>Set</code>
     * returned is <code>null</code>, no policy check will be performed.
     * 
     * @return an immutable <code>Set</code> of certificate policy OIDs in
     *         string format (or <code>null</code>)
     * 
     * @see #setPolicy
     */
    public Set getPolicy()
    {
        if (policy == null)
        {
            return null;
        }

        return Collections.unmodifiableSet(policy);
    }

    /**
     * Returns a copy of the pathToNames criterion. The
     * <code>X509Certificate</code> must not include name constraints that
     * would prohibit building a path to the specified names. If the value
     * returned is <code>null</code>, no pathToNames check will be performed.<br />
     * <br />
     * If the value returned is not <code>null</code>, it is a
     * <code>Collection</code> with one entry for each name to be included in
     * the pathToNames criterion. Each entry is a <code>List</code> whose
     * first entry is an <code>Integer</code> (the name type, 0-8) and whose
     * second entry is a <code>String</code> or a byte array (the name, in
     * string or ASN.1 DER encoded form, respectively). There can be multiple
     * names of the same type. Note that the <code>Collection</code> returned
     * may contain duplicate names (same name and name type).<br />
     * <br />
     * Each name in the <code>Collection</code> may be specified either as a
     * <code>String</code> or as an ASN.1 encoded byte array. For more details
     * about the formats used, see {@link #addPathToName(int type, String name) 
     * addPathToName(int type, String name)} and
     * {@link #addPathToName(int type, byte [] name)  addPathToName(int type,
     * byte [] name)}.<br />
     * <br />
     * Note that a deep copy is performed on the <code>Collection</code> to
     * protect against subsequent modifications.
     * 
     * @return a <code>Collection</code> of names (or <code>null</code>)
     * 
     * @see #setPathToNames
     */
    public Collection getPathToNames()
    {
        if (pathToNames == null)
        {
            return null;
        }

        Set returnPathToNames = new HashSet();
        List returnList;
        Iterator iter = pathToNames.iterator();
        List obj;

        while (iter.hasNext())
        {
            obj = (List)iter.next();
            returnList = new ArrayList();
            returnList.add(obj.get(0));
            if (obj.get(1) instanceof byte[])
            {
                returnList.add(((byte[])obj.get(1)).clone());
            }
            else
            {
                returnList.add(obj.get(1));
            }
            returnPathToNames.add(returnList);
        }

        return returnPathToNames;
    }

    /**
     * Return a printable representation of the <code>CertSelector</code>.<br />
     * <br />
     * <b>TODO: implement output for currently unsupported options(name
     * constraints)</b><br />
     * <br />
     * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream},
     * {@link org.bouncycastle.asn1.ASN1Object ASN1Object},
     * {@link org.bouncycastle.asn1.x509.KeyPurposeId KeyPurposeId}
     * 
     * @return a <code>String</code> describing the contents of the
     *         <code>CertSelector</code>
     */
    public String toString()
    {
        StringBuffer sb = new StringBuffer();
        sb.append("X509CertSelector: [\n");
        if (x509Cert != null)
        {
            sb.append("  Certificate: ").append(x509Cert).append('\n');
        }
        if (serialNumber != null)
        {
            sb.append("  Serial Number: ").append(serialNumber).append('\n');
        }
        if (issuerDN != null)
        {
            sb.append("  Issuer: ").append(getIssuerAsString()).append('\n');
        }
        if (subjectDN != null)
        {
            sb.append("  Subject: ").append(getSubjectAsString()).append('\n');
        }
        try
        {
            if (subjectKeyID != null)
            {
                ByteArrayInputStream inStream = new ByteArrayInputStream(
                        subjectKeyID);
                ASN1InputStream derInStream = new ASN1InputStream(inStream);
                ASN1Object derObject = derInStream.readObject();
                sb.append("  Subject Key Identifier: ")
                       .append(ASN1Dump.dumpAsString(derObject)).append('\n');
            }
            if (authorityKeyID != null)
            {
                ByteArrayInputStream inStream = new ByteArrayInputStream(
                        authorityKeyID);
                ASN1InputStream derInStream = new ASN1InputStream(inStream);
                ASN1Object derObject = derInStream.readObject();
                sb.append("  Authority Key Identifier: ")
                       .append(ASN1Dump.dumpAsString(derObject)).append('\n');
            }
        }
        catch (IOException ex)
        {
            sb.append(ex.getMessage()).append('\n');
        }
        if (certValid != null)
        {
            sb.append("  Certificate Valid: ").append(certValid).append('\n');
        }
        if (privateKeyValid != null)
        {
            sb.append("  Private Key Valid: ").append(privateKeyValid)
                   .append('\n');
        }
        if (subjectKeyAlgID != null)
        {
            sb.append("  Subject Public Key AlgID: ")
                   .append(subjectKeyAlgID).append('\n');
        }
        if (subjectPublicKey != null)
        {
            sb.append("  Subject Public Key: ").append(subjectPublicKey)
                   .append('\n');
        }
        if (keyUsage != null)
        {
            sb.append("  Key Usage: ").append(keyUsage).append('\n');
        }
        if (keyPurposeSet != null)
        {
            sb.append("  Extended Key Usage: ").append(keyPurposeSet)
                   .append('\n');
        }
        if (policy != null)
        {
            sb.append("  Policy: ").append(policy).append('\n');
        }
        sb.append("  matchAllSubjectAltNames flag: ")
               .append(matchAllSubjectAltNames).append('\n');
        if (subjectAltNamesByte != null)
        {
            sb.append("   SubjectAlternativNames: \n[");
            Iterator iter = subjectAltNamesByte.iterator();
            List obj;
            try
            {
                while (iter.hasNext())
                {
                    obj = (List)iter.next();
                    ByteArrayInputStream inStream = new ByteArrayInputStream(
                            (byte[])obj.get(1));
                    ASN1InputStream derInStream = new ASN1InputStream(inStream);
                    ASN1Object derObject = derInStream.readObject();
                    sb.append("  Type: ").append(obj.get(0)).append(" Data: ")
                           .append(ASN1Dump.dumpAsString(derObject)).append('\n');
                }
            }
            catch (IOException ex)
            {
                sb.append(ex.getMessage()).append('\n');
            }
            sb.append("]\n");
        }
        if (pathToNamesByte != null)
        {
            sb.append("   PathToNamesNames: \n[");
            Iterator iter = pathToNamesByte.iterator();
            List obj;
            try
            {
                while (iter.hasNext())
                {
                    obj = (List)iter.next();
                    ByteArrayInputStream inStream = new ByteArrayInputStream(
                            (byte[])obj.get(1));
                    ASN1InputStream derInStream = new ASN1InputStream(inStream);
                    ASN1Object derObject = derInStream.readObject();
                    sb.append("  Type: ").append(obj.get(0)).append(" Data: ")
                           .append(ASN1Dump.dumpAsString(derObject)).append('\n');
                }
            }
            catch (IOException ex)
            {
                sb.append(ex.getMessage()).append('\n');
            }
            sb.append("]\n");
        }
        sb.append(']');
        return sb.toString();
    }

    /**
     * Decides whether a <code>Certificate</code> should be selected.<br />
     * <br />
     * <b>TODO: implement missing tests (name constraints and path to names)</b><br />
     * <br />
     * Uses {@link org.bouncycastle.asn1.ASN1InputStream ASN1InputStream},
     * {@link org.bouncycastle.asn1.ASN1Sequence ASN1Sequence},
     * {@link org.bouncycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier},
     * {@link org.bouncycastle.asn1.ASN1Object ASN1Object},
     * {@link org.bouncycastle.asn1.DERGeneralizedTime DERGeneralizedTime},
     * {@link org.bouncycastle.asn1.x509.X509Name X509Name},
     * {@link org.bouncycastle.asn1.x509.X509Extensions X509Extensions},
     * {@link org.bouncycastle.asn1.x509.ExtendedKeyUsage ExtendedKeyUsage},
     * {@link org.bouncycastle.asn1.x509.KeyPurposeId KeyPurposeId},
     * {@link org.bouncycastle.asn1.x509.SubjectPublicKeyInfo SubjectPublicKeyInfo},
     * {@link org.bouncycastle.asn1.x509.AlgorithmIdentifier AlgorithmIdentifier}
     * to access X509 extensions
     * 
     * @param cert
     *            the <code>Certificate</code> to be checked
     * 
     * @return <code>true</code> if the <code>Certificate</code> should be
     *         selected, <code>false</code> otherwise
     */
    public boolean match(Certificate cert)
    {
        boolean[] booleanArray;
        List tempList;
        Iterator tempIter;

        if (!(cert instanceof X509Certificate))
        {
            return false;
        }
        X509Certificate certX509 = (X509Certificate)cert;

        if (x509Cert != null && !x509Cert.equals(certX509))
        {
            return false;
        }
        if (serialNumber != null
                && !serialNumber.equals(certX509.getSerialNumber()))
        {
            return false;
        }
        try
        {
            if (issuerDNX509 != null)
            {
                if (!issuerDNX509.equals(PrincipalUtil
                        .getIssuerX509Principal(certX509), true))
                {
                    return false;
                }
            }
            if (subjectDNX509 != null)
            {
                if (!subjectDNX509.equals(PrincipalUtil
                        .getSubjectX509Principal(certX509), true))
                {
                    return false;
                }
            }
        }
        catch (Exception ex)
        {
            return false;
        }
        if (subjectKeyID != null)
        {
            byte[] data = certX509
                    .getExtensionValue(X509Extensions.SubjectKeyIdentifier
                            .getId());
            if (data == null)
            {
                return false;
            }
            try
            {
                ByteArrayInputStream inStream = new ByteArrayInputStream(data);
                ASN1InputStream derInputStream = new ASN1InputStream(inStream);
                byte[] testData = ((ASN1OctetString)derInputStream.readObject())
                        .getOctets();
                if (!Arrays.equals(subjectKeyID, testData))
                {
                    return false;
                }
            }
            catch (IOException ex)
            {
                return false;
            }
        }
        if (authorityKeyID != null)
        {
            byte[] data = certX509
                    .getExtensionValue(X509Extensions.AuthorityKeyIdentifier
                            .getId());
            if (data == null)
            {
                return false;
            }
            try
            {
                ByteArrayInputStream inStream = new ByteArrayInputStream(data);
                ASN1InputStream derInputStream = new ASN1InputStream(inStream);
                byte[] testData = ((ASN1OctetString)derInputStream.readObject())
                        .getOctets();
                if (!Arrays.equals(authorityKeyID, testData))
                {
                    return false;
                }
            }
            catch (IOException ex)
            {
                return false;
            }
        }
        if (certValid != null)
        {
            if (certX509.getNotAfter() != null
                    && certValid.after(certX509.getNotAfter()))
            {
                return false;
            }
            if (certX509.getNotBefore() != null
                    && certValid.before(certX509.getNotBefore()))
            {
                return false;
            }
        }
        if (privateKeyValid != null)
        {
            try
            {
                byte[] data = certX509
                        .getExtensionValue(X509Extensions.PrivateKeyUsagePeriod
                                .getId());
                if (data != null)
                {
                    ByteArrayInputStream inStream = new ByteArrayInputStream(
                            data);
                    ASN1InputStream derInputStream = new ASN1InputStream(inStream);
                    inStream = new ByteArrayInputStream(
                            ((ASN1OctetString)derInputStream.readObject())
                                    .getOctets());
                    derInputStream = new ASN1InputStream(inStream);
                    // TODO fix this, Sequence contains tagged objects
                    ASN1Sequence derObject = (ASN1Sequence)derInputStream
                            .readObject();
                    ASN1GeneralizedTime derDate = DERGeneralizedTime
                            .getInstance(derObject.getObjectAt(0));
                    SimpleDateFormat dateF = new SimpleDateFormat(
                            "yyyyMMddHHmmssZ");
                    if (privateKeyValid.before(dateF.parse(derDate.getTime())))
                    {
                        return false;
                    }
                    derDate = DERGeneralizedTime.getInstance(derObject
                            .getObjectAt(1));
                    if (privateKeyValid.after(dateF.parse(derDate.getTime())))
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        if (subjectKeyAlgID != null)
        {
            try
            {
                ByteArrayInputStream inStream = new ByteArrayInputStream(
                        certX509.getPublicKey().getEncoded());
                ASN1InputStream derInputStream = new ASN1InputStream(inStream);
                SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo(
                        (ASN1Sequence)derInputStream.readObject());
                AlgorithmIdentifier algInfo = publicKeyInfo.getAlgorithmId();
                if (!algInfo.getObjectId().equals(subjectKeyAlgID))
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        if (subjectPublicKeyByte != null)
        {
            if (!Arrays.equals(subjectPublicKeyByte, certX509.getPublicKey()
                    .getEncoded()))
            {
                return false;
            }
        }
        if (subjectPublicKey != null)
        {
            if (!subjectPublicKey.equals(certX509.getPublicKey()))
            {
                return false;
            }
        }
        if (keyUsage != null)
        {
            booleanArray = certX509.getKeyUsage();
            if (booleanArray != null)
            {
                for (int i = 0; i < keyUsage.length; i++)
                {
                    if (keyUsage[i]
                            && (booleanArray.length <= i || !booleanArray[i]))
                    {
                        return false;
                    }
                }
            }
        }
        if (keyPurposeSet != null && !keyPurposeSet.isEmpty())
        {
            try
            {
                byte[] data = certX509
                        .getExtensionValue(X509Extensions.ExtendedKeyUsage
                                .getId());
                if (data != null)
                {
                    ByteArrayInputStream inStream = new ByteArrayInputStream(
                            data);
                    ASN1InputStream derInputStream = new ASN1InputStream(inStream);
                    ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.getInstance(
                            (ASN1Sequence)derInputStream.readObject());
                    tempIter = keyPurposeSet.iterator();
                    while (tempIter.hasNext())
                    {
                        if (!extendedKeyUsage
                                .hasKeyPurposeId((KeyPurposeId)tempIter.next()))
                        {
                            return false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        if (minMaxPathLen != -1)
        {
            if (minMaxPathLen == -2 && certX509.getBasicConstraints() != -1)
            {
                return false;
            }
            if (minMaxPathLen >= 0
                    && certX509.getBasicConstraints() < minMaxPathLen)
            {
                return false;
            }
        }
        if (policyOID != null)
        {
            try
            {
                byte[] data = certX509
                        .getExtensionValue(X509Extensions.CertificatePolicies
                                .getId());
                if (data == null)
                {
                    return false;
                }
                if (!policyOID.isEmpty())
                {
                    ByteArrayInputStream inStream = new ByteArrayInputStream(
                            data);
                    ASN1InputStream derInputStream = new ASN1InputStream(inStream);
                    inStream = new ByteArrayInputStream(
                            ((ASN1OctetString)derInputStream.readObject())
                                    .getOctets());
                    derInputStream = new ASN1InputStream(inStream);
                    Enumeration policySequence = ((ASN1Sequence)derInputStream
                            .readObject()).getObjects();
                    ASN1Sequence policyObject;
                    boolean test = false;
                    while (policySequence.hasMoreElements() && !test)
                    {
                        policyObject = (ASN1Sequence)policySequence
                                .nextElement();
                        if (policyOID.contains(policyObject.getObjectAt(0)))
                        {
                            test = true;
                        }
                    }
                    if (!test)
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
                return false;
            }
        }
        if (subjectAltNamesByte != null)
        {
            try
            {
                byte[] data = certX509
                        .getExtensionValue(X509Extensions.SubjectAlternativeName
                                .getId());
                if (data == null)
                {
                    return false;
                }
                ByteArrayInputStream inStream = new ByteArrayInputStream(data);
                ASN1InputStream derInputStream = new ASN1InputStream(inStream);
                inStream = new ByteArrayInputStream(
                        ((ASN1OctetString)derInputStream.readObject())
                                .getOctets());
                derInputStream = new ASN1InputStream(inStream);
                Enumeration altNamesSequence = ((ASN1Sequence)derInputStream
                        .readObject()).getObjects();
                ASN1TaggedObject altNameObject;
                boolean test = false;
                Set testSet = new HashSet(subjectAltNamesByte);
                List testList;
                ASN1Object derData;
                ByteArrayOutputStream outStream;
                DEROutputStream derOutStream;
                while (altNamesSequence.hasMoreElements() && !test)
                {
                    altNameObject = (ASN1TaggedObject)altNamesSequence
                            .nextElement();
                    testList = new ArrayList(2);
                    testList.add(Integers.valueOf(altNameObject.getTagNo()));
                    derData = altNameObject.getObject();
                    outStream = new ByteArrayOutputStream();
                    derOutStream = new DEROutputStream(outStream);
                    derOutStream.writeObject(derData);
                    derOutStream.close();
                    testList.add(outStream.toByteArray());

                    if (testSet.remove(testList))
                    {
                        test = true;
                    }

                    if (matchAllSubjectAltNames && !testSet.isEmpty())
                    {
                        test = false;
                    }
                }
                if (!test)
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
                return false;
            }
        }

        return true;
    }

    /**
     * Returns a copy of this object.
     * 
     * @return the copy
     */
    public Object clone()
    {
        try
        {
            X509CertSelector copy = (X509CertSelector)super.clone();
            if (issuerDN instanceof byte[])
            {
                copy.issuerDN = ((byte[])issuerDN).clone();
            }
            if (subjectDN instanceof byte[])
            {
                copy.subjectDN = ((byte[])subjectDN).clone();
            }
            if (subjectKeyID != null)
            {
                copy.subjectKeyID = (byte[])subjectKeyID.clone();
            }
            if (authorityKeyID != null)
            {
                copy.authorityKeyID = (byte[])authorityKeyID.clone();
            }
            if (subjectPublicKeyByte != null)
            {
                copy.subjectPublicKeyByte = (byte[])subjectPublicKeyByte
                        .clone();
            }
            if (keyUsage != null)
            {
                copy.keyUsage = (boolean[])keyUsage.clone();
            }
            if (keyPurposeSet != null)
            {
                copy.keyPurposeSet = new HashSet(keyPurposeSet);
            }
            if (policy != null)
            {
                copy.policy = new HashSet(policy);
                copy.policyOID = new HashSet();
                Iterator iter = policyOID.iterator();
                while (iter.hasNext())
                {
                    copy.policyOID.add(new ASN1ObjectIdentifier(
                            ((ASN1ObjectIdentifier)iter.next()).getId()));
                }
            }
            if (subjectAltNames != null)
            {
                copy.subjectAltNames = new HashSet(getSubjectAlternativeNames());
                Iterator iter = subjectAltNamesByte.iterator();
                List obj;
                List cloneObj;
                while (iter.hasNext())
                {
                    obj = (List)iter.next();
                    cloneObj = new ArrayList();
                    cloneObj.add(obj.get(0));
                    cloneObj.add(((byte[])obj.get(1)).clone());
                    copy.subjectAltNamesByte.add(cloneObj);
                }
            }
            if (pathToNames != null)
            {
                copy.pathToNames = new HashSet(getPathToNames());
                Iterator iter = pathToNamesByte.iterator();
                List obj;
                List cloneObj;
                while (iter.hasNext())
                {
                    obj = (List)iter.next();
                    cloneObj = new ArrayList();
                    cloneObj.add(obj.get(0));
                    cloneObj.add(((byte[])obj.get(1)).clone());
                    copy.pathToNamesByte.add(cloneObj);
                }
            }
            return copy;
        }
        catch (CloneNotSupportedException e)
        {
            /* Cannot happen */
            throw new InternalError(e.toString());
        }
    }
}