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
|
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.x509;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.*;
import java.security.cert.Certificate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import javax.security.auth.x500.X500Principal;
import sun.misc.HexDumpEncoder;
import sun.security.util.*;
import sun.security.provider.X509Factory;
/**
* The X509CertImpl class represents an X.509 certificate. These certificates
* are widely used to support authentication and other functionality in
* Internet security systems. Common applications include Privacy Enhanced
* Mail (PEM), Transport Layer Security (SSL), code signing for trusted
* software distribution, and Secure Electronic Transactions (SET). There
* is a commercial infrastructure ready to manage large scale deployments
* of X.509 identity certificates.
*
* <P>These certificates are managed and vouched for by <em>Certificate
* Authorities</em> (CAs). CAs are services which create certificates by
* placing data in the X.509 standard format and then digitally signing
* that data. Such signatures are quite difficult to forge. CAs act as
* trusted third parties, making introductions between agents who have no
* direct knowledge of each other. CA certificates are either signed by
* themselves, or by some other CA such as a "root" CA.
*
* <P>RFC 1422 is very informative, though it does not describe much
* of the recent work being done with X.509 certificates. That includes
* a 1996 version (X.509v3) and a variety of enhancements being made to
* facilitate an explosion of personal certificates used as "Internet
* Drivers' Licences", or with SET for credit card transactions.
*
* <P>More recent work includes the IETF PKIX Working Group efforts,
* especially RFC2459.
*
* @author Dave Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @see X509CertInfo
*/
public class X509CertImpl extends X509Certificate implements DerEncoder {
private static final long serialVersionUID = -3457612960190864406L;
private static final String DOT = ".";
/**
* Public attribute names.
*/
public static final String NAME = "x509";
public static final String INFO = X509CertInfo.NAME;
public static final String ALG_ID = "algorithm";
public static final String SIGNATURE = "signature";
public static final String SIGNED_CERT = "signed_cert";
/**
* The following are defined for ease-of-use. These
* are the most frequently retrieved attributes.
*/
// x509.info.subject.dname
public static final String SUBJECT_DN = NAME + DOT + INFO + DOT +
X509CertInfo.SUBJECT + DOT + X509CertInfo.DN_NAME;
// x509.info.issuer.dname
public static final String ISSUER_DN = NAME + DOT + INFO + DOT +
X509CertInfo.ISSUER + DOT + X509CertInfo.DN_NAME;
// x509.info.serialNumber.number
public static final String SERIAL_ID = NAME + DOT + INFO + DOT +
X509CertInfo.SERIAL_NUMBER + DOT +
CertificateSerialNumber.NUMBER;
// x509.info.key.value
public static final String PUBLIC_KEY = NAME + DOT + INFO + DOT +
X509CertInfo.KEY + DOT +
CertificateX509Key.KEY;
// x509.info.version.value
public static final String VERSION = NAME + DOT + INFO + DOT +
X509CertInfo.VERSION + DOT +
CertificateVersion.VERSION;
// x509.algorithm
public static final String SIG_ALG = NAME + DOT + ALG_ID;
// x509.signature
public static final String SIG = NAME + DOT + SIGNATURE;
// when we sign and decode we set this to true
// this is our means to make certificates immutable
private boolean readOnly = false;
// Certificate data, and its envelope
private byte[] signedCert = null;
protected X509CertInfo info = null;
protected AlgorithmId algId = null;
protected byte[] signature = null;
// recognized extension OIDS
private static final String KEY_USAGE_OID = "2.5.29.15";
private static final String EXTENDED_KEY_USAGE_OID = "2.5.29.37";
private static final String BASIC_CONSTRAINT_OID = "2.5.29.19";
private static final String SUBJECT_ALT_NAME_OID = "2.5.29.17";
private static final String ISSUER_ALT_NAME_OID = "2.5.29.18";
private static final String AUTH_INFO_ACCESS_OID = "1.3.6.1.5.5.7.1.1";
// number of standard key usage bits.
private static final int NUM_STANDARD_KEY_USAGE = 9;
// SubjectAlterntativeNames cache
private Collection<List<?>> subjectAlternativeNames;
// IssuerAlternativeNames cache
private Collection<List<?>> issuerAlternativeNames;
// ExtendedKeyUsage cache
private List<String> extKeyUsage;
// AuthorityInformationAccess cache
private Set<AccessDescription> authInfoAccess;
/**
* PublicKey that has previously been used to verify
* the signature of this certificate. Null if the certificate has not
* yet been verified.
*/
private PublicKey verifiedPublicKey;
/**
* If verifiedPublicKey is not null, name of the provider used to
* successfully verify the signature of this certificate, or the
* empty String if no provider was explicitly specified.
*/
private String verifiedProvider;
/**
* If verifiedPublicKey is not null, result of the verification using
* verifiedPublicKey and verifiedProvider. If true, verification was
* successful, if false, it failed.
*/
private boolean verificationResult;
/**
* Default constructor.
*/
public X509CertImpl() { }
/**
* Unmarshals a certificate from its encoded form, parsing the
* encoded bytes. This form of constructor is used by agents which
* need to examine and use certificate contents. That is, this is
* one of the more commonly used constructors. Note that the buffer
* must include only a certificate, and no "garbage" may be left at
* the end. If you need to ignore data at the end of a certificate,
* use another constructor.
*
* @param certData the encoded bytes, with no trailing padding.
* @exception CertificateException on parsing and initialization errors.
*/
public X509CertImpl(byte[] certData) throws CertificateException {
try {
parse(new DerValue(certData));
} catch (IOException e) {
signedCert = null;
throw new CertificateException("Unable to initialize, " + e, e);
}
}
// BEGIN Android-removed: unused code.
/*
/**
* unmarshals an X.509 certificate from an input stream. If the
* certificate is RFC1421 hex-encoded, then it must begin with
* the line X509Factory.BEGIN_CERT and end with the line
* X509Factory.END_CERT.
*
* @param in an input stream holding at least one certificate that may
* be either DER-encoded or RFC1421 hex-encoded version of the
* DER-encoded certificate.
* @exception CertificateException on parsing and initialization errors.
*
public X509CertImpl(InputStream in) throws CertificateException {
DerValue der = null;
BufferedInputStream inBuffered = new BufferedInputStream(in);
// First try reading stream as HEX-encoded DER-encoded bytes,
// since not mistakable for raw DER
try {
inBuffered.mark(Integer.MAX_VALUE);
der = readRFC1421Cert(inBuffered);
} catch (IOException ioe) {
try {
// Next, try reading stream as raw DER-encoded bytes
inBuffered.reset();
der = new DerValue(inBuffered);
} catch (IOException ioe1) {
throw new CertificateException("Input stream must be " +
"either DER-encoded bytes " +
"or RFC1421 hex-encoded " +
"DER-encoded bytes: " +
ioe1.getMessage(), ioe1);
}
}
try {
parse(der);
} catch (IOException ioe) {
signedCert = null;
throw new CertificateException("Unable to parse DER value of " +
"certificate, " + ioe, ioe);
}
}
/**
* read input stream as HEX-encoded DER-encoded bytes
*
* @param in InputStream to read
* @returns DerValue corresponding to decoded HEX-encoded bytes
* @throws IOException if stream can not be interpreted as RFC1421
* encoded bytes
*
private DerValue readRFC1421Cert(InputStream in) throws IOException {
DerValue der = null;
String line = null;
BufferedReader certBufferedReader =
new BufferedReader(new InputStreamReader(in, "ASCII"));
try {
line = certBufferedReader.readLine();
} catch (IOException ioe1) {
throw new IOException("Unable to read InputStream: " +
ioe1.getMessage());
}
if (line.equals(X509Factory.BEGIN_CERT)) {
/* stream appears to be hex-encoded bytes *
ByteArrayOutputStream decstream = new ByteArrayOutputStream();
try {
while ((line = certBufferedReader.readLine()) != null) {
if (line.equals(X509Factory.END_CERT)) {
der = new DerValue(decstream.toByteArray());
break;
} else {
decstream.write(Pem.decode(line));
}
}
} catch (IOException ioe2) {
throw new IOException("Unable to read InputStream: "
+ ioe2.getMessage());
}
} else {
throw new IOException("InputStream is not RFC1421 hex-encoded " +
"DER bytes");
}
return der;
}
*/
// END Android-removed: unused code.
/**
* Construct an initialized X509 Certificate. The certificate is stored
* in raw form and has to be signed to be useful.
*
* @params info the X509CertificateInfo which the Certificate is to be
* created from.
*/
public X509CertImpl(X509CertInfo certInfo) {
this.info = certInfo;
}
/**
* Unmarshal a certificate from its encoded form, parsing a DER value.
* This form of constructor is used by agents which need to examine
* and use certificate contents.
*
* @param derVal the der value containing the encoded cert.
* @exception CertificateException on parsing and initialization errors.
*/
public X509CertImpl(DerValue derVal) throws CertificateException {
try {
parse(derVal);
} catch (IOException e) {
signedCert = null;
throw new CertificateException("Unable to initialize, " + e, e);
}
}
// BEGIN Android-added: Ctor to retain original encoded form for APKs parsing.
/**
* Unmarshal a certificate from its encoded form, parsing a DER value.
* This form of constructor is used by agents which need to examine
* and use certificate contents.
*
* @param derVal the der value containing the encoded cert.
* @exception CertificateException on parsing and initialization errors.
*/
public X509CertImpl(DerValue derVal, byte[] encoded)
throws CertificateException {
try {
parse(derVal, encoded);
} catch (IOException e) {
signedCert = null;
throw new CertificateException("Unable to initialize, " + e, e);
}
}
// END Android-added: Ctor to retain original encoded form for APKs parsing.
/**
* Appends the certificate to an output stream.
*
* @param out an input stream to which the certificate is appended.
* @exception CertificateEncodingException on encoding errors.
*/
public void encode(OutputStream out)
throws CertificateEncodingException {
if (signedCert == null)
throw new CertificateEncodingException(
"Null certificate to encode");
try {
out.write(signedCert.clone());
} catch (IOException e) {
throw new CertificateEncodingException(e.toString());
}
}
/**
* DER encode this object onto an output stream.
* Implements the <code>DerEncoder</code> interface.
*
* @param out the output stream on which to write the DER encoding.
*
* @exception IOException on encoding error.
*/
public void derEncode(OutputStream out) throws IOException {
if (signedCert == null)
throw new IOException("Null certificate to encode");
out.write(signedCert.clone());
}
/**
* Returns the encoded form of this certificate. It is
* assumed that each certificate type would have only a single
* form of encoding; for example, X.509 certificates would
* be encoded as ASN.1 DER.
*
* @exception CertificateEncodingException if an encoding error occurs.
*/
public byte[] getEncoded() throws CertificateEncodingException {
return getEncodedInternal().clone();
}
/**
* Returned the encoding as an uncloned byte array. Callers must
* guarantee that they neither modify it nor expose it to untrusted
* code.
*/
public byte[] getEncodedInternal() throws CertificateEncodingException {
if (signedCert == null) {
throw new CertificateEncodingException(
"Null certificate to encode");
}
return signedCert;
}
/**
* Throws an exception if the certificate was not signed using the
* verification key provided. Successfully verifying a certificate
* does <em>not</em> indicate that one should trust the entity which
* it represents.
*
* @param key the public key used for verification.
*
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchAlgorithmException on unsupported signature
* algorithms.
* @exception NoSuchProviderException if there's no default provider.
* @exception SignatureException on signature errors.
* @exception CertificateException on encoding errors.
*/
public void verify(PublicKey key)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException, SignatureException {
verify(key, "");
}
/**
* Throws an exception if the certificate was not signed using the
* verification key provided. Successfully verifying a certificate
* does <em>not</em> indicate that one should trust the entity which
* it represents.
*
* @param key the public key used for verification.
* @param sigProvider the name of the provider.
*
* @exception NoSuchAlgorithmException on unsupported signature
* algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException on incorrect provider.
* @exception SignatureException on signature errors.
* @exception CertificateException on encoding errors.
*/
public synchronized void verify(PublicKey key, String sigProvider)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException, SignatureException {
if (sigProvider == null) {
sigProvider = "";
}
if ((verifiedPublicKey != null) && verifiedPublicKey.equals(key)) {
// this certificate has already been verified using
// this public key. Make sure providers match, too.
if (sigProvider.equals(verifiedProvider)) {
if (verificationResult) {
return;
} else {
throw new SignatureException("Signature does not match.");
}
}
}
if (signedCert == null) {
throw new CertificateEncodingException("Uninitialized certificate");
}
// Verify the signature ...
Signature sigVerf = null;
if (sigProvider.length() == 0) {
sigVerf = Signature.getInstance(algId.getName());
} else {
sigVerf = Signature.getInstance(algId.getName(), sigProvider);
}
sigVerf.initVerify(key);
byte[] rawCert = info.getEncodedInfo();
sigVerf.update(rawCert, 0, rawCert.length);
// verify may throw SignatureException for invalid encodings, etc.
verificationResult = sigVerf.verify(signature);
verifiedPublicKey = key;
verifiedProvider = sigProvider;
if (verificationResult == false) {
throw new SignatureException("Signature does not match.");
}
}
/**
* Throws an exception if the certificate was not signed using the
* verification key provided. This method uses the signature verification
* engine supplied by the specified provider. Note that the specified
* Provider object does not have to be registered in the provider list.
* Successfully verifying a certificate does <em>not</em> indicate that one
* should trust the entity which it represents.
*
* @param key the public key used for verification.
* @param sigProvider the provider.
*
* @exception NoSuchAlgorithmException on unsupported signature
* algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception SignatureException on signature errors.
* @exception CertificateException on encoding errors.
*/
public synchronized void verify(PublicKey key, Provider sigProvider)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, SignatureException {
if (signedCert == null) {
throw new CertificateEncodingException("Uninitialized certificate");
}
// Verify the signature ...
Signature sigVerf = null;
if (sigProvider == null) {
sigVerf = Signature.getInstance(algId.getName());
} else {
sigVerf = Signature.getInstance(algId.getName(), sigProvider);
}
sigVerf.initVerify(key);
byte[] rawCert = info.getEncodedInfo();
sigVerf.update(rawCert, 0, rawCert.length);
// verify may throw SignatureException for invalid encodings, etc.
verificationResult = sigVerf.verify(signature);
verifiedPublicKey = key;
if (verificationResult == false) {
throw new SignatureException("Signature does not match.");
}
}
/**
* This static method is the default implementation of the
* verify(PublicKey key, Provider sigProvider) method in X509Certificate.
* Called from java.security.cert.X509Certificate.verify(PublicKey key,
* Provider sigProvider)
*/
public static void verify(X509Certificate cert, PublicKey key,
Provider sigProvider) throws CertificateException,
NoSuchAlgorithmException, InvalidKeyException, SignatureException {
cert.verify(key, sigProvider);
}
/**
* Creates an X.509 certificate, and signs it using the given key
* (associating a signature algorithm and an X.500 name).
* This operation is used to implement the certificate generation
* functionality of a certificate authority.
*
* @param key the private key used for signing.
* @param algorithm the name of the signature algorithm used.
*
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchAlgorithmException on unsupported signature
* algorithms.
* @exception NoSuchProviderException if there's no default provider.
* @exception SignatureException on signature errors.
* @exception CertificateException on encoding errors.
*/
public void sign(PrivateKey key, String algorithm)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException, SignatureException {
sign(key, algorithm, null);
}
/**
* Creates an X.509 certificate, and signs it using the given key
* (associating a signature algorithm and an X.500 name).
* This operation is used to implement the certificate generation
* functionality of a certificate authority.
*
* @param key the private key used for signing.
* @param algorithm the name of the signature algorithm used.
* @param provider the name of the provider.
*
* @exception NoSuchAlgorithmException on unsupported signature
* algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException on incorrect provider.
* @exception SignatureException on signature errors.
* @exception CertificateException on encoding errors.
*/
public void sign(PrivateKey key, String algorithm, String provider)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException, SignatureException {
try {
if (readOnly)
throw new CertificateEncodingException(
"cannot over-write existing certificate");
Signature sigEngine = null;
if ((provider == null) || (provider.length() == 0))
sigEngine = Signature.getInstance(algorithm);
else
sigEngine = Signature.getInstance(algorithm, provider);
sigEngine.initSign(key);
// in case the name is reset
algId = AlgorithmId.get(sigEngine.getAlgorithm());
DerOutputStream out = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
// encode certificate info
info.encode(tmp);
byte[] rawCert = tmp.toByteArray();
// encode algorithm identifier
algId.encode(tmp);
// Create and encode the signature itself.
sigEngine.update(rawCert, 0, rawCert.length);
signature = sigEngine.sign();
tmp.putBitString(signature);
// Wrap the signed data in a SEQUENCE { data, algorithm, sig }
out.write(DerValue.tag_Sequence, tmp);
signedCert = out.toByteArray();
readOnly = true;
} catch (IOException e) {
throw new CertificateEncodingException(e.toString());
}
}
/**
* Checks that the certificate is currently valid, i.e. the current
* time is within the specified validity period.
*
* @exception CertificateExpiredException if the certificate has expired.
* @exception CertificateNotYetValidException if the certificate is not
* yet valid.
*/
public void checkValidity()
throws CertificateExpiredException, CertificateNotYetValidException {
Date date = new Date();
checkValidity(date);
}
/**
* Checks that the specified date is within the certificate's
* validity period, or basically if the certificate would be
* valid at the specified date/time.
*
* @param date the Date to check against to see if this certificate
* is valid at that date/time.
*
* @exception CertificateExpiredException if the certificate has expired
* with respect to the <code>date</code> supplied.
* @exception CertificateNotYetValidException if the certificate is not
* yet valid with respect to the <code>date</code> supplied.
*/
public void checkValidity(Date date)
throws CertificateExpiredException, CertificateNotYetValidException {
CertificateValidity interval = null;
try {
interval = (CertificateValidity)info.get(CertificateValidity.NAME);
} catch (Exception e) {
throw new CertificateNotYetValidException("Incorrect validity period");
}
if (interval == null)
throw new CertificateNotYetValidException("Null validity period");
interval.valid(date);
}
/**
* Return the requested attribute from the certificate.
*
* Note that the X509CertInfo is not cloned for performance reasons.
* Callers must ensure that they do not modify it. All other
* attributes are cloned.
*
* @param name the name of the attribute.
* @exception CertificateParsingException on invalid attribute identifier.
*/
public Object get(String name)
throws CertificateParsingException {
X509AttributeName attr = new X509AttributeName(name);
String id = attr.getPrefix();
if (!(id.equalsIgnoreCase(NAME))) {
throw new CertificateParsingException("Invalid root of "
+ "attribute name, expected [" + NAME +
"], received " + "[" + id + "]");
}
attr = new X509AttributeName(attr.getSuffix());
id = attr.getPrefix();
if (id.equalsIgnoreCase(INFO)) {
if (info == null) {
return null;
}
if (attr.getSuffix() != null) {
try {
return info.get(attr.getSuffix());
} catch (IOException e) {
throw new CertificateParsingException(e.toString());
} catch (CertificateException e) {
throw new CertificateParsingException(e.toString());
}
} else {
return info;
}
} else if (id.equalsIgnoreCase(ALG_ID)) {
return(algId);
} else if (id.equalsIgnoreCase(SIGNATURE)) {
if (signature != null)
return signature.clone();
else
return null;
} else if (id.equalsIgnoreCase(SIGNED_CERT)) {
if (signedCert != null)
return signedCert.clone();
else
return null;
} else {
throw new CertificateParsingException("Attribute name not "
+ "recognized or get() not allowed for the same: " + id);
}
}
/**
* Set the requested attribute in the certificate.
*
* @param name the name of the attribute.
* @param obj the value of the attribute.
* @exception CertificateException on invalid attribute identifier.
* @exception IOException on encoding error of attribute.
*/
public void set(String name, Object obj)
throws CertificateException, IOException {
// check if immutable
if (readOnly)
throw new CertificateException("cannot over-write existing"
+ " certificate");
X509AttributeName attr = new X509AttributeName(name);
String id = attr.getPrefix();
if (!(id.equalsIgnoreCase(NAME))) {
throw new CertificateException("Invalid root of attribute name,"
+ " expected [" + NAME + "], received " + id);
}
attr = new X509AttributeName(attr.getSuffix());
id = attr.getPrefix();
if (id.equalsIgnoreCase(INFO)) {
if (attr.getSuffix() == null) {
if (!(obj instanceof X509CertInfo)) {
throw new CertificateException("Attribute value should"
+ " be of type X509CertInfo.");
}
info = (X509CertInfo)obj;
signedCert = null; //reset this as certificate data has changed
} else {
info.set(attr.getSuffix(), obj);
signedCert = null; //reset this as certificate data has changed
}
} else {
throw new CertificateException("Attribute name not recognized or " +
"set() not allowed for the same: " + id);
}
}
/**
* Delete the requested attribute from the certificate.
*
* @param name the name of the attribute.
* @exception CertificateException on invalid attribute identifier.
* @exception IOException on other errors.
*/
public void delete(String name)
throws CertificateException, IOException {
// check if immutable
if (readOnly)
throw new CertificateException("cannot over-write existing"
+ " certificate");
X509AttributeName attr = new X509AttributeName(name);
String id = attr.getPrefix();
if (!(id.equalsIgnoreCase(NAME))) {
throw new CertificateException("Invalid root of attribute name,"
+ " expected ["
+ NAME + "], received " + id);
}
attr = new X509AttributeName(attr.getSuffix());
id = attr.getPrefix();
if (id.equalsIgnoreCase(INFO)) {
if (attr.getSuffix() != null) {
info = null;
} else {
info.delete(attr.getSuffix());
}
} else if (id.equalsIgnoreCase(ALG_ID)) {
algId = null;
} else if (id.equalsIgnoreCase(SIGNATURE)) {
signature = null;
} else if (id.equalsIgnoreCase(SIGNED_CERT)) {
signedCert = null;
} else {
throw new CertificateException("Attribute name not recognized or " +
"delete() not allowed for the same: " + id);
}
}
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
public Enumeration<String> getElements() {
AttributeNameEnumeration elements = new AttributeNameEnumeration();
elements.addElement(NAME + DOT + INFO);
elements.addElement(NAME + DOT + ALG_ID);
elements.addElement(NAME + DOT + SIGNATURE);
elements.addElement(NAME + DOT + SIGNED_CERT);
return elements.elements();
}
/**
* Return the name of this attribute.
*/
public String getName() {
return(NAME);
}
/**
* Returns a printable representation of the certificate. This does not
* contain all the information available to distinguish this from any
* other certificate. The certificate must be fully constructed
* before this function may be called.
*/
public String toString() {
if (info == null || algId == null || signature == null)
return "";
StringBuilder sb = new StringBuilder();
sb.append("[\n");
sb.append(info.toString() + "\n");
sb.append(" Algorithm: [" + algId.toString() + "]\n");
HexDumpEncoder encoder = new HexDumpEncoder();
sb.append(" Signature:\n" + encoder.encodeBuffer(signature));
sb.append("\n]");
return sb.toString();
}
// the strongly typed gets, as per java.security.cert.X509Certificate
/**
* Gets the publickey from this certificate.
*
* @return the publickey.
*/
public PublicKey getPublicKey() {
if (info == null)
return null;
try {
PublicKey key = (PublicKey)info.get(CertificateX509Key.NAME
+ DOT + CertificateX509Key.KEY);
return key;
} catch (Exception e) {
return null;
}
}
/**
* Gets the version number from the certificate.
*
* @return the version number, i.e. 1, 2 or 3.
*/
public int getVersion() {
if (info == null)
return -1;
try {
int vers = ((Integer)info.get(CertificateVersion.NAME
+ DOT + CertificateVersion.VERSION)).intValue();
return vers+1;
} catch (Exception e) {
return -1;
}
}
/**
* Gets the serial number from the certificate.
*
* @return the serial number.
*/
public BigInteger getSerialNumber() {
SerialNumber ser = getSerialNumberObject();
return ser != null ? ser.getNumber() : null;
}
/**
* Gets the serial number from the certificate as
* a SerialNumber object.
*
* @return the serial number.
*/
public SerialNumber getSerialNumberObject() {
if (info == null)
return null;
try {
SerialNumber ser = (SerialNumber)info.get(
CertificateSerialNumber.NAME + DOT +
CertificateSerialNumber.NUMBER);
return ser;
} catch (Exception e) {
return null;
}
}
/**
* Gets the subject distinguished name from the certificate.
*
* @return the subject name.
*/
public Principal getSubjectDN() {
if (info == null)
return null;
try {
Principal subject = (Principal)info.get(X509CertInfo.SUBJECT + DOT +
X509CertInfo.DN_NAME);
return subject;
} catch (Exception e) {
return null;
}
}
/**
* Get subject name as X500Principal. Overrides implementation in
* X509Certificate with a slightly more efficient version that is
* also aware of X509CertImpl mutability.
*/
public X500Principal getSubjectX500Principal() {
if (info == null) {
return null;
}
try {
X500Principal subject = (X500Principal)info.get(
X509CertInfo.SUBJECT + DOT +
"x500principal");
return subject;
} catch (Exception e) {
return null;
}
}
/**
* Gets the issuer distinguished name from the certificate.
*
* @return the issuer name.
*/
public Principal getIssuerDN() {
if (info == null)
return null;
try {
Principal issuer = (Principal)info.get(X509CertInfo.ISSUER + DOT +
X509CertInfo.DN_NAME);
return issuer;
} catch (Exception e) {
return null;
}
}
/**
* Get issuer name as X500Principal. Overrides implementation in
* X509Certificate with a slightly more efficient version that is
* also aware of X509CertImpl mutability.
*/
public X500Principal getIssuerX500Principal() {
if (info == null) {
return null;
}
try {
X500Principal issuer = (X500Principal)info.get(
X509CertInfo.ISSUER + DOT +
"x500principal");
return issuer;
} catch (Exception e) {
return null;
}
}
/**
* Gets the notBefore date from the validity period of the certificate.
*
* @return the start date of the validity period.
*/
public Date getNotBefore() {
if (info == null)
return null;
try {
Date d = (Date) info.get(CertificateValidity.NAME + DOT +
CertificateValidity.NOT_BEFORE);
return d;
} catch (Exception e) {
return null;
}
}
/**
* Gets the notAfter date from the validity period of the certificate.
*
* @return the end date of the validity period.
*/
public Date getNotAfter() {
if (info == null)
return null;
try {
Date d = (Date) info.get(CertificateValidity.NAME + DOT +
CertificateValidity.NOT_AFTER);
return d;
} catch (Exception e) {
return null;
}
}
/**
* Gets the DER encoded certificate informations, the
* <code>tbsCertificate</code> from this certificate.
* This can be used to verify the signature independently.
*
* @return the DER encoded certificate information.
* @exception CertificateEncodingException if an encoding error occurs.
*/
public byte[] getTBSCertificate() throws CertificateEncodingException {
if (info != null) {
return info.getEncodedInfo();
} else
throw new CertificateEncodingException("Uninitialized certificate");
}
/**
* Gets the raw Signature bits from the certificate.
*
* @return the signature.
*/
public byte[] getSignature() {
if (signature == null)
return null;
return signature.clone();
}
/**
* Gets the signature algorithm name for the certificate
* signature algorithm.
* For example, the string "SHA-1/DSA" or "DSS".
*
* @return the signature algorithm name.
*/
public String getSigAlgName() {
if (algId == null)
return null;
return (algId.getName());
}
/**
* Gets the signature algorithm OID string from the certificate.
* For example, the string "1.2.840.10040.4.3"
*
* @return the signature algorithm oid string.
*/
public String getSigAlgOID() {
if (algId == null)
return null;
ObjectIdentifier oid = algId.getOID();
return (oid.toString());
}
/**
* Gets the DER encoded signature algorithm parameters from this
* certificate's signature algorithm.
*
* @return the DER encoded signature algorithm parameters, or
* null if no parameters are present.
*/
public byte[] getSigAlgParams() {
if (algId == null)
return null;
try {
return algId.getEncodedParams();
} catch (IOException e) {
return null;
}
}
/**
* Gets the Issuer Unique Identity from the certificate.
*
* @return the Issuer Unique Identity.
*/
public boolean[] getIssuerUniqueID() {
if (info == null)
return null;
try {
UniqueIdentity id = (UniqueIdentity)info.get(
X509CertInfo.ISSUER_ID);
if (id == null)
return null;
else
return (id.getId());
} catch (Exception e) {
return null;
}
}
/**
* Gets the Subject Unique Identity from the certificate.
*
* @return the Subject Unique Identity.
*/
public boolean[] getSubjectUniqueID() {
if (info == null)
return null;
try {
UniqueIdentity id = (UniqueIdentity)info.get(
X509CertInfo.SUBJECT_ID);
if (id == null)
return null;
else
return (id.getId());
} catch (Exception e) {
return null;
}
}
public KeyIdentifier getAuthKeyId() {
AuthorityKeyIdentifierExtension aki
= getAuthorityKeyIdentifierExtension();
if (aki != null) {
try {
return (KeyIdentifier)aki.get(
AuthorityKeyIdentifierExtension.KEY_ID);
} catch (IOException ioe) {} // not possible
}
return null;
}
/**
* Returns the subject's key identifier, or null
*/
public KeyIdentifier getSubjectKeyId() {
SubjectKeyIdentifierExtension ski = getSubjectKeyIdentifierExtension();
if (ski != null) {
try {
return (KeyIdentifier)ski.get(
SubjectKeyIdentifierExtension.KEY_ID);
} catch (IOException ioe) {} // not possible
}
return null;
}
/**
* Get AuthorityKeyIdentifier extension
* @return AuthorityKeyIdentifier object or null (if no such object
* in certificate)
*/
public AuthorityKeyIdentifierExtension getAuthorityKeyIdentifierExtension()
{
return (AuthorityKeyIdentifierExtension)
getExtension(PKIXExtensions.AuthorityKey_Id);
}
/**
* Get BasicConstraints extension
* @return BasicConstraints object or null (if no such object in
* certificate)
*/
public BasicConstraintsExtension getBasicConstraintsExtension() {
return (BasicConstraintsExtension)
getExtension(PKIXExtensions.BasicConstraints_Id);
}
/**
* Get CertificatePoliciesExtension
* @return CertificatePoliciesExtension or null (if no such object in
* certificate)
*/
public CertificatePoliciesExtension getCertificatePoliciesExtension() {
return (CertificatePoliciesExtension)
getExtension(PKIXExtensions.CertificatePolicies_Id);
}
/**
* Get ExtendedKeyUsage extension
* @return ExtendedKeyUsage extension object or null (if no such object
* in certificate)
*/
public ExtendedKeyUsageExtension getExtendedKeyUsageExtension() {
return (ExtendedKeyUsageExtension)
getExtension(PKIXExtensions.ExtendedKeyUsage_Id);
}
/**
* Get IssuerAlternativeName extension
* @return IssuerAlternativeName object or null (if no such object in
* certificate)
*/
public IssuerAlternativeNameExtension getIssuerAlternativeNameExtension() {
return (IssuerAlternativeNameExtension)
getExtension(PKIXExtensions.IssuerAlternativeName_Id);
}
/**
* Get NameConstraints extension
* @return NameConstraints object or null (if no such object in certificate)
*/
public NameConstraintsExtension getNameConstraintsExtension() {
return (NameConstraintsExtension)
getExtension(PKIXExtensions.NameConstraints_Id);
}
/**
* Get PolicyConstraints extension
* @return PolicyConstraints object or null (if no such object in
* certificate)
*/
public PolicyConstraintsExtension getPolicyConstraintsExtension() {
return (PolicyConstraintsExtension)
getExtension(PKIXExtensions.PolicyConstraints_Id);
}
/**
* Get PolicyMappingsExtension extension
* @return PolicyMappingsExtension object or null (if no such object
* in certificate)
*/
public PolicyMappingsExtension getPolicyMappingsExtension() {
return (PolicyMappingsExtension)
getExtension(PKIXExtensions.PolicyMappings_Id);
}
/**
* Get PrivateKeyUsage extension
* @return PrivateKeyUsage object or null (if no such object in certificate)
*/
public PrivateKeyUsageExtension getPrivateKeyUsageExtension() {
return (PrivateKeyUsageExtension)
getExtension(PKIXExtensions.PrivateKeyUsage_Id);
}
/**
* Get SubjectAlternativeName extension
* @return SubjectAlternativeName object or null (if no such object in
* certificate)
*/
public SubjectAlternativeNameExtension getSubjectAlternativeNameExtension()
{
return (SubjectAlternativeNameExtension)
getExtension(PKIXExtensions.SubjectAlternativeName_Id);
}
/**
* Get SubjectKeyIdentifier extension
* @return SubjectKeyIdentifier object or null (if no such object in
* certificate)
*/
public SubjectKeyIdentifierExtension getSubjectKeyIdentifierExtension() {
return (SubjectKeyIdentifierExtension)
getExtension(PKIXExtensions.SubjectKey_Id);
}
/**
* Get CRLDistributionPoints extension
* @return CRLDistributionPoints object or null (if no such object in
* certificate)
*/
public CRLDistributionPointsExtension getCRLDistributionPointsExtension() {
return (CRLDistributionPointsExtension)
getExtension(PKIXExtensions.CRLDistributionPoints_Id);
}
/**
* Return true if a critical extension is found that is
* not supported, otherwise return false.
*/
public boolean hasUnsupportedCriticalExtension() {
if (info == null)
return false;
try {
CertificateExtensions exts = (CertificateExtensions)info.get(
CertificateExtensions.NAME);
if (exts == null)
return false;
return exts.hasUnsupportedCriticalExtension();
} catch (Exception e) {
return false;
}
}
/**
* Gets a Set of the extension(s) marked CRITICAL in the
* certificate. In the returned set, each extension is
* represented by its OID string.
*
* @return a set of the extension oid strings in the
* certificate that are marked critical.
*/
public Set<String> getCriticalExtensionOIDs() {
if (info == null) {
return null;
}
try {
CertificateExtensions exts = (CertificateExtensions)info.get(
CertificateExtensions.NAME);
if (exts == null) {
return null;
}
Set<String> extSet = new TreeSet<>();
for (Extension ex : exts.getAllExtensions()) {
if (ex.isCritical()) {
extSet.add(ex.getExtensionId().toString());
}
}
return extSet;
} catch (Exception e) {
return null;
}
}
/**
* Gets a Set of the extension(s) marked NON-CRITICAL in the
* certificate. In the returned set, each extension is
* represented by its OID string.
*
* @return a set of the extension oid strings in the
* certificate that are NOT marked critical.
*/
public Set<String> getNonCriticalExtensionOIDs() {
if (info == null) {
return null;
}
try {
CertificateExtensions exts = (CertificateExtensions)info.get(
CertificateExtensions.NAME);
if (exts == null) {
return null;
}
Set<String> extSet = new TreeSet<>();
for (Extension ex : exts.getAllExtensions()) {
if (!ex.isCritical()) {
extSet.add(ex.getExtensionId().toString());
}
}
extSet.addAll(exts.getUnparseableExtensions().keySet());
return extSet;
} catch (Exception e) {
return null;
}
}
/**
* Gets the extension identified by the given ObjectIdentifier
*
* @param oid the Object Identifier value for the extension.
* @return Extension or null if certificate does not contain this
* extension
*/
public Extension getExtension(ObjectIdentifier oid) {
if (info == null) {
return null;
}
try {
CertificateExtensions extensions;
try {
extensions = (CertificateExtensions)info.get(CertificateExtensions.NAME);
} catch (CertificateException ce) {
return null;
}
if (extensions == null) {
return null;
} else {
Extension ex = extensions.getExtension(oid.toString());
if (ex != null) {
return ex;
}
for (Extension ex2: extensions.getAllExtensions()) {
if (ex2.getExtensionId().equals((Object)oid)) {
//XXXX May want to consider cloning this
return ex2;
}
}
/* no such extension in this certificate */
return null;
}
} catch (IOException ioe) {
return null;
}
}
public Extension getUnparseableExtension(ObjectIdentifier oid) {
if (info == null) {
return null;
}
try {
CertificateExtensions extensions;
try {
extensions = (CertificateExtensions)info.get(CertificateExtensions.NAME);
} catch (CertificateException ce) {
return null;
}
if (extensions == null) {
return null;
} else {
return extensions.getUnparseableExtensions().get(oid.toString());
}
} catch (IOException ioe) {
return null;
}
}
/**
* Gets the DER encoded extension identified by the given
* oid String.
*
* @param oid the Object Identifier value for the extension.
*/
public byte[] getExtensionValue(String oid) {
try {
ObjectIdentifier findOID = new ObjectIdentifier(oid);
String extAlias = OIDMap.getName(findOID);
Extension certExt = null;
CertificateExtensions exts = (CertificateExtensions)info.get(
CertificateExtensions.NAME);
if (extAlias == null) { // may be unknown
// get the extensions, search thru' for this oid
if (exts == null) {
return null;
}
for (Extension ex : exts.getAllExtensions()) {
ObjectIdentifier inCertOID = ex.getExtensionId();
if (inCertOID.equals((Object)findOID)) {
certExt = ex;
break;
}
}
} else { // there's sub-class that can handle this extension
try {
certExt = (Extension)this.get(extAlias);
} catch (CertificateException e) {
// get() throws an Exception instead of returning null, ignore
}
}
if (certExt == null) {
if (exts != null) {
certExt = exts.getUnparseableExtensions().get(oid);
}
if (certExt == null) {
return null;
}
}
byte[] extData = certExt.getExtensionValue();
if (extData == null) {
return null;
}
DerOutputStream out = new DerOutputStream();
out.putOctetString(extData);
return out.toByteArray();
} catch (Exception e) {
return null;
}
}
/**
* Get a boolean array representing the bits of the KeyUsage extension,
* (oid = 2.5.29.15).
* @return the bit values of this extension as an array of booleans.
*/
public boolean[] getKeyUsage() {
try {
String extAlias = OIDMap.getName(PKIXExtensions.KeyUsage_Id);
if (extAlias == null)
return null;
KeyUsageExtension certExt = (KeyUsageExtension)this.get(extAlias);
if (certExt == null)
return null;
boolean[] ret = certExt.getBits();
if (ret.length < NUM_STANDARD_KEY_USAGE) {
boolean[] usageBits = new boolean[NUM_STANDARD_KEY_USAGE];
System.arraycopy(ret, 0, usageBits, 0, ret.length);
ret = usageBits;
}
return ret;
} catch (Exception e) {
return null;
}
}
/**
* This method are the overridden implementation of
* getExtendedKeyUsage method in X509Certificate in the Sun
* provider. It is better performance-wise since it returns cached
* values.
*/
public synchronized List<String> getExtendedKeyUsage()
throws CertificateParsingException {
if (readOnly && extKeyUsage != null) {
return extKeyUsage;
} else {
ExtendedKeyUsageExtension ext = getExtendedKeyUsageExtension();
if (ext == null) {
return null;
}
extKeyUsage =
Collections.unmodifiableList(ext.getExtendedKeyUsage());
return extKeyUsage;
}
}
/**
* This static method is the default implementation of the
* getExtendedKeyUsage method in X509Certificate. A
* X509Certificate provider generally should overwrite this to
* provide among other things caching for better performance.
*/
public static List<String> getExtendedKeyUsage(X509Certificate cert)
throws CertificateParsingException {
try {
byte[] ext = cert.getExtensionValue(EXTENDED_KEY_USAGE_OID);
if (ext == null)
return null;
DerValue val = new DerValue(ext);
byte[] data = val.getOctetString();
ExtendedKeyUsageExtension ekuExt =
new ExtendedKeyUsageExtension(Boolean.FALSE, data);
return Collections.unmodifiableList(ekuExt.getExtendedKeyUsage());
} catch (IOException ioe) {
throw new CertificateParsingException(ioe);
}
}
/**
* Get the certificate constraints path length from the
* the critical BasicConstraints extension, (oid = 2.5.29.19).
* @return the length of the constraint.
*/
public int getBasicConstraints() {
try {
String extAlias = OIDMap.getName(PKIXExtensions.BasicConstraints_Id);
if (extAlias == null)
return -1;
BasicConstraintsExtension certExt =
(BasicConstraintsExtension)this.get(extAlias);
if (certExt == null)
return -1;
if (((Boolean)certExt.get(BasicConstraintsExtension.IS_CA)
).booleanValue() == true)
return ((Integer)certExt.get(
BasicConstraintsExtension.PATH_LEN)).intValue();
else
return -1;
} catch (Exception e) {
return -1;
}
}
/**
* Converts a GeneralNames structure into an immutable Collection of
* alternative names (subject or issuer) in the form required by
* {@link #getSubjectAlternativeNames} or
* {@link #getIssuerAlternativeNames}.
*
* @param names the GeneralNames to be converted
* @return an immutable Collection of alternative names
*/
private static Collection<List<?>> makeAltNames(GeneralNames names) {
if (names.isEmpty()) {
return Collections.<List<?>>emptySet();
}
List<List<?>> newNames = new ArrayList<>();
for (GeneralName gname : names.names()) {
GeneralNameInterface name = gname.getName();
List<Object> nameEntry = new ArrayList<>(2);
nameEntry.add(Integer.valueOf(name.getType()));
switch (name.getType()) {
case GeneralNameInterface.NAME_RFC822:
nameEntry.add(((RFC822Name) name).getName());
break;
case GeneralNameInterface.NAME_DNS:
nameEntry.add(((DNSName) name).getName());
break;
case GeneralNameInterface.NAME_DIRECTORY:
nameEntry.add(((X500Name) name).getRFC2253Name());
break;
case GeneralNameInterface.NAME_URI:
nameEntry.add(((URIName) name).getName());
break;
case GeneralNameInterface.NAME_IP:
try {
nameEntry.add(((IPAddressName) name).getName());
} catch (IOException ioe) {
// IPAddressName in cert is bogus
throw new RuntimeException("IPAddress cannot be parsed",
ioe);
}
break;
case GeneralNameInterface.NAME_OID:
nameEntry.add(((OIDName) name).getOID().toString());
break;
default:
// add DER encoded form
DerOutputStream derOut = new DerOutputStream();
try {
name.encode(derOut);
} catch (IOException ioe) {
// should not occur since name has already been decoded
// from cert (this would indicate a bug in our code)
throw new RuntimeException("name cannot be encoded", ioe);
}
nameEntry.add(derOut.toByteArray());
break;
}
newNames.add(Collections.unmodifiableList(nameEntry));
}
return Collections.unmodifiableCollection(newNames);
}
/**
* Checks a Collection of altNames and clones any name entries of type
* byte [].
*/ // only partially generified due to javac bug
private static Collection<List<?>> cloneAltNames(Collection<List<?>> altNames) {
boolean mustClone = false;
for (List<?> nameEntry : altNames) {
if (nameEntry.get(1) instanceof byte[]) {
// must clone names
mustClone = true;
}
}
if (mustClone) {
List<List<?>> namesCopy = new ArrayList<>();
for (List<?> nameEntry : altNames) {
Object nameObject = nameEntry.get(1);
if (nameObject instanceof byte[]) {
List<Object> nameEntryCopy =
new ArrayList<>(nameEntry);
nameEntryCopy.set(1, ((byte[])nameObject).clone());
namesCopy.add(Collections.unmodifiableList(nameEntryCopy));
} else {
namesCopy.add(nameEntry);
}
}
return Collections.unmodifiableCollection(namesCopy);
} else {
return altNames;
}
}
/**
* This method are the overridden implementation of
* getSubjectAlternativeNames method in X509Certificate in the Sun
* provider. It is better performance-wise since it returns cached
* values.
*/
public synchronized Collection<List<?>> getSubjectAlternativeNames()
throws CertificateParsingException {
// return cached value if we can
if (readOnly && subjectAlternativeNames != null) {
return cloneAltNames(subjectAlternativeNames);
}
SubjectAlternativeNameExtension subjectAltNameExt =
getSubjectAlternativeNameExtension();
if (subjectAltNameExt == null) {
return null;
}
GeneralNames names;
try {
names = subjectAltNameExt.get(
SubjectAlternativeNameExtension.SUBJECT_NAME);
} catch (IOException ioe) {
// should not occur
return Collections.<List<?>>emptySet();
}
subjectAlternativeNames = makeAltNames(names);
return subjectAlternativeNames;
}
/**
* This static method is the default implementation of the
* getSubjectAlternaitveNames method in X509Certificate. A
* X509Certificate provider generally should overwrite this to
* provide among other things caching for better performance.
*/
public static Collection<List<?>> getSubjectAlternativeNames(X509Certificate cert)
throws CertificateParsingException {
try {
byte[] ext = cert.getExtensionValue(SUBJECT_ALT_NAME_OID);
if (ext == null) {
return null;
}
DerValue val = new DerValue(ext);
byte[] data = val.getOctetString();
SubjectAlternativeNameExtension subjectAltNameExt =
new SubjectAlternativeNameExtension(Boolean.FALSE,
data);
GeneralNames names;
try {
names = subjectAltNameExt.get(
SubjectAlternativeNameExtension.SUBJECT_NAME);
} catch (IOException ioe) {
// should not occur
return Collections.<List<?>>emptySet();
}
return makeAltNames(names);
} catch (IOException ioe) {
throw new CertificateParsingException(ioe);
}
}
/**
* This method are the overridden implementation of
* getIssuerAlternativeNames method in X509Certificate in the Sun
* provider. It is better performance-wise since it returns cached
* values.
*/
public synchronized Collection<List<?>> getIssuerAlternativeNames()
throws CertificateParsingException {
// return cached value if we can
if (readOnly && issuerAlternativeNames != null) {
return cloneAltNames(issuerAlternativeNames);
}
IssuerAlternativeNameExtension issuerAltNameExt =
getIssuerAlternativeNameExtension();
if (issuerAltNameExt == null) {
return null;
}
GeneralNames names;
try {
names = issuerAltNameExt.get(
IssuerAlternativeNameExtension.ISSUER_NAME);
} catch (IOException ioe) {
// should not occur
return Collections.<List<?>>emptySet();
}
issuerAlternativeNames = makeAltNames(names);
return issuerAlternativeNames;
}
/**
* This static method is the default implementation of the
* getIssuerAlternaitveNames method in X509Certificate. A
* X509Certificate provider generally should overwrite this to
* provide among other things caching for better performance.
*/
public static Collection<List<?>> getIssuerAlternativeNames(X509Certificate cert)
throws CertificateParsingException {
try {
byte[] ext = cert.getExtensionValue(ISSUER_ALT_NAME_OID);
if (ext == null) {
return null;
}
DerValue val = new DerValue(ext);
byte[] data = val.getOctetString();
IssuerAlternativeNameExtension issuerAltNameExt =
new IssuerAlternativeNameExtension(Boolean.FALSE,
data);
GeneralNames names;
try {
names = issuerAltNameExt.get(
IssuerAlternativeNameExtension.ISSUER_NAME);
} catch (IOException ioe) {
// should not occur
return Collections.<List<?>>emptySet();
}
return makeAltNames(names);
} catch (IOException ioe) {
throw new CertificateParsingException(ioe);
}
}
public AuthorityInfoAccessExtension getAuthorityInfoAccessExtension() {
return (AuthorityInfoAccessExtension)
getExtension(PKIXExtensions.AuthInfoAccess_Id);
}
/************************************************************/
/*
* Cert is a SIGNED ASN.1 macro, a three elment sequence:
*
* - Data to be signed (ToBeSigned) -- the "raw" cert
* - Signature algorithm (SigAlgId)
* - The signature bits
*
* This routine unmarshals the certificate, saving the signature
* parts away for later verification.
*/
private void parse(DerValue val)
throws CertificateException, IOException {
// BEGIN Android-added: Use original encoded form of cert rather than regenerating.
parse(
val,
null // use re-encoded form of val as the encoded form
);
}
/*
* Cert is a SIGNED ASN.1 macro, a three elment sequence:
*
* - Data to be signed (ToBeSigned) -- the "raw" cert
* - Signature algorithm (SigAlgId)
* - The signature bits
*
* This routine unmarshals the certificate, saving the signature
* parts away for later verification.
*/
private void parse(DerValue val, byte[] originalEncodedForm)
throws CertificateException, IOException {
// END Android-added: Use original encoded form of cert rather than regenerating.
// check if can over write the certificate
if (readOnly)
throw new CertificateParsingException(
"cannot over-write existing certificate");
if (val.data == null || val.tag != DerValue.tag_Sequence)
throw new CertificateParsingException(
"invalid DER-encoded certificate data");
// Android-changed: Needed for providing encoded form of cert.
// signedCert = val.toByteArray();
signedCert =
(originalEncodedForm != null)
? originalEncodedForm : val.toByteArray();
DerValue[] seq = new DerValue[3];
seq[0] = val.data.getDerValue();
seq[1] = val.data.getDerValue();
seq[2] = val.data.getDerValue();
if (val.data.available() != 0) {
throw new CertificateParsingException("signed overrun, bytes = "
+ val.data.available());
}
if (seq[0].tag != DerValue.tag_Sequence) {
throw new CertificateParsingException("signed fields invalid");
}
algId = AlgorithmId.parse(seq[1]);
signature = seq[2].getBitString();
if (seq[1].data.available() != 0) {
throw new CertificateParsingException("algid field overrun");
}
if (seq[2].data.available() != 0)
throw new CertificateParsingException("signed fields overrun");
// The CertificateInfo
info = new X509CertInfo(seq[0]);
// the "inner" and "outer" signature algorithms must match
AlgorithmId infoSigAlg = (AlgorithmId)info.get(
CertificateAlgorithmId.NAME
+ DOT +
CertificateAlgorithmId.ALGORITHM);
if (! algId.equals(infoSigAlg))
throw new CertificateException("Signature algorithm mismatch");
readOnly = true;
}
/**
* Extract the subject or issuer X500Principal from an X509Certificate.
* Parses the encoded form of the cert to preserve the principal's
* ASN.1 encoding.
*/
private static X500Principal getX500Principal(X509Certificate cert,
boolean getIssuer) throws Exception {
byte[] encoded = cert.getEncoded();
DerInputStream derIn = new DerInputStream(encoded);
DerValue tbsCert = derIn.getSequence(3)[0];
DerInputStream tbsIn = tbsCert.data;
DerValue tmp;
tmp = tbsIn.getDerValue();
// skip version number if present
if (tmp.isContextSpecific((byte)0)) {
tmp = tbsIn.getDerValue();
}
// tmp always contains serial number now
tmp = tbsIn.getDerValue(); // skip signature
tmp = tbsIn.getDerValue(); // issuer
if (getIssuer == false) {
tmp = tbsIn.getDerValue(); // skip validity
tmp = tbsIn.getDerValue(); // subject
}
byte[] principalBytes = tmp.toByteArray();
return new X500Principal(principalBytes);
}
/**
* Extract the subject X500Principal from an X509Certificate.
* Called from java.security.cert.X509Certificate.getSubjectX500Principal().
*/
public static X500Principal getSubjectX500Principal(X509Certificate cert) {
try {
return getX500Principal(cert, false);
} catch (Exception e) {
throw new RuntimeException("Could not parse subject", e);
}
}
/**
* Extract the issuer X500Principal from an X509Certificate.
* Called from java.security.cert.X509Certificate.getIssuerX500Principal().
*/
public static X500Principal getIssuerX500Principal(X509Certificate cert) {
try {
return getX500Principal(cert, true);
} catch (Exception e) {
throw new RuntimeException("Could not parse issuer", e);
}
}
/**
* Returned the encoding of the given certificate for internal use.
* Callers must guarantee that they neither modify it nor expose it
* to untrusted code. Uses getEncodedInternal() if the certificate
* is instance of X509CertImpl, getEncoded() otherwise.
*/
public static byte[] getEncodedInternal(Certificate cert)
throws CertificateEncodingException {
if (cert instanceof X509CertImpl) {
return ((X509CertImpl)cert).getEncodedInternal();
} else {
return cert.getEncoded();
}
}
/**
* Utility method to convert an arbitrary instance of X509Certificate
* to a X509CertImpl. Does a cast if possible, otherwise reparses
* the encoding.
*/
public static X509CertImpl toImpl(X509Certificate cert)
throws CertificateException {
if (cert instanceof X509CertImpl) {
return (X509CertImpl)cert;
} else {
return X509Factory.intern(cert);
}
}
/**
* Utility method to test if a certificate is self-issued. This is
* the case iff the subject and issuer X500Principals are equal.
*/
public static boolean isSelfIssued(X509Certificate cert) {
X500Principal subject = cert.getSubjectX500Principal();
X500Principal issuer = cert.getIssuerX500Principal();
return subject.equals(issuer);
}
/**
* Utility method to test if a certificate is self-signed. This is
* the case iff the subject and issuer X500Principals are equal
* AND the certificate's subject public key can be used to verify
* the certificate. In case of exception, returns false.
*/
public static boolean isSelfSigned(X509Certificate cert,
String sigProvider) {
if (isSelfIssued(cert)) {
try {
if (sigProvider == null) {
cert.verify(cert.getPublicKey());
} else {
cert.verify(cert.getPublicKey(), sigProvider);
}
return true;
} catch (Exception e) {
// In case of exception, return false
}
}
return false;
}
private ConcurrentHashMap<String,String> fingerprints =
new ConcurrentHashMap<>(2);
// BEGIN Android-removed: unused code.
// public String getFingerprint(String algorithm) {
// return fingerprints.computeIfAbsent(algorithm,
// x -> getFingerprint(x, this));
// }
// END Android-removed: unused code.
/**
* Gets the requested finger print of the certificate. The result
* only contains 0-9 and A-F. No small case, no colon.
*/
public static String getFingerprint(String algorithm,
X509Certificate cert) {
String fingerPrint = "";
try {
byte[] encCertInfo = cert.getEncoded();
MessageDigest md = MessageDigest.getInstance(algorithm);
byte[] digest = md.digest(encCertInfo);
StringBuffer buf = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
byte2hex(digest[i], buf);
}
fingerPrint = buf.toString();
} catch (NoSuchAlgorithmException | CertificateEncodingException e) {
// ignored
}
return fingerPrint;
}
/**
* Converts a byte to hex digit and writes to the supplied buffer
*/
private static void byte2hex(byte b, StringBuffer buf) {
char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F' };
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high]);
buf.append(hexChars[low]);
}
}
|