View Javadoc
1   /*
2    * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
3    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4    *
5    * This code is free software; you can redistribute it and/or modify it
6    * under the terms of the GNU General Public License version 2 only, as
7    * published by the Free Software Foundation.  Oracle designates this
8    * particular file as subject to the "Classpath" exception as provided
9    * by Oracle in the LICENSE file that accompanied this code.
10   *
11   * This code is distributed in the hope that it will be useful, but WITHOUT
12   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14   * version 2 for more details (a copy is included in the LICENSE file that
15   * accompanied this code).
16   *
17   * You should have received a copy of the GNU General Public License version
18   * 2 along with this work; if not, write to the Free Software Foundation,
19   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20   *
21   * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22   * or visit www.oracle.com if you need additional information or have any
23   * questions.
24   */
25  
26  package sun.security.x509;
27  
28  import java.io.BufferedReader;
29  import java.io.BufferedInputStream;
30  import java.io.ByteArrayOutputStream;
31  import java.io.IOException;
32  import java.io.InputStream;
33  import java.io.InputStreamReader;
34  import java.io.OutputStream;
35  import java.math.BigInteger;
36  import java.security.*;
37  import java.security.cert.*;
38  import java.security.cert.Certificate;
39  import java.util.*;
40  import java.util.concurrent.ConcurrentHashMap;
41  
42  import javax.security.auth.x500.X500Principal;
43  
44  import sun.misc.HexDumpEncoder;
45  import java.util.Base64;
46  import sun.security.util.*;
47  import sun.security.provider.X509Factory;
48  
49  /**
50   * The X509CertImpl class represents an X.509 certificate. These certificates
51   * are widely used to support authentication and other functionality in
52   * Internet security systems.  Common applications include Privacy Enhanced
53   * Mail (PEM), Transport Layer Security (SSL), code signing for trusted
54   * software distribution, and Secure Electronic Transactions (SET).  There
55   * is a commercial infrastructure ready to manage large scale deployments
56   * of X.509 identity certificates.
57   *
58   * <P>These certificates are managed and vouched for by <em>Certificate
59   * Authorities</em> (CAs).  CAs are services which create certificates by
60   * placing data in the X.509 standard format and then digitally signing
61   * that data.  Such signatures are quite difficult to forge.  CAs act as
62   * trusted third parties, making introductions between agents who have no
63   * direct knowledge of each other.  CA certificates are either signed by
64   * themselves, or by some other CA such as a "root" CA.
65   *
66   * <P>RFC 1422 is very informative, though it does not describe much
67   * of the recent work being done with X.509 certificates.  That includes
68   * a 1996 version (X.509v3) and a variety of enhancements being made to
69   * facilitate an explosion of personal certificates used as "Internet
70   * Drivers' Licences", or with SET for credit card transactions.
71   *
72   * <P>More recent work includes the IETF PKIX Working Group efforts,
73   * especially RFC2459.
74   *
75   * @author Dave Brownell
76   * @author Amit Kapoor
77   * @author Hemma Prafullchandra
78   * @see X509CertInfo
79   */
80  public class X509CertImpl extends X509Certificate implements DerEncoder {
81  
82      private static final long serialVersionUID = -3457612960190864406L;
83  
84      private static final String DOT = ".";
85      /**
86       * Public attribute names.
87       */
88      public static final String NAME = "x509";
89      public static final String INFO = X509CertInfo.NAME;
90      public static final String ALG_ID = "algorithm";
91      public static final String SIGNATURE = "signature";
92      public static final String SIGNED_CERT = "signed_cert";
93  
94      /**
95       * The following are defined for ease-of-use. These
96       * are the most frequently retrieved attributes.
97       */
98      // x509.info.subject.dname
99      public static final String SUBJECT_DN = NAME + DOT + INFO + DOT +
100                                X509CertInfo.SUBJECT + DOT + X509CertInfo.DN_NAME;
101     // x509.info.issuer.dname
102     public static final String ISSUER_DN = NAME + DOT + INFO + DOT +
103                                X509CertInfo.ISSUER + DOT + X509CertInfo.DN_NAME;
104     // x509.info.serialNumber.number
105     public static final String SERIAL_ID = NAME + DOT + INFO + DOT +
106                                X509CertInfo.SERIAL_NUMBER + DOT +
107                                CertificateSerialNumber.NUMBER;
108     // x509.info.key.value
109     public static final String PUBLIC_KEY = NAME + DOT + INFO + DOT +
110                                X509CertInfo.KEY + DOT +
111                                CertificateX509Key.KEY;
112 
113     // x509.info.version.value
114     public static final String VERSION = NAME + DOT + INFO + DOT +
115                                X509CertInfo.VERSION + DOT +
116                                CertificateVersion.VERSION;
117 
118     // x509.algorithm
119     public static final String SIG_ALG = NAME + DOT + ALG_ID;
120 
121     // x509.signature
122     public static final String SIG = NAME + DOT + SIGNATURE;
123 
124     // when we sign and decode we set this to true
125     // this is our means to make certificates immutable
126     private boolean readOnly = false;
127 
128     // Certificate data, and its envelope
129     private byte[]              signedCert = null;
130     protected X509CertInfo      info = null;
131     protected AlgorithmId       algId = null;
132     protected byte[]            signature = null;
133 
134     // recognized extension OIDS
135     private static final String KEY_USAGE_OID = "2.5.29.15";
136     private static final String EXTENDED_KEY_USAGE_OID = "2.5.29.37";
137     private static final String BASIC_CONSTRAINT_OID = "2.5.29.19";
138     private static final String SUBJECT_ALT_NAME_OID = "2.5.29.17";
139     private static final String ISSUER_ALT_NAME_OID = "2.5.29.18";
140     private static final String AUTH_INFO_ACCESS_OID = "1.3.6.1.5.5.7.1.1";
141 
142     // number of standard key usage bits.
143     private static final int NUM_STANDARD_KEY_USAGE = 9;
144 
145     // SubjectAlterntativeNames cache
146     private Collection<List<?>> subjectAlternativeNames;
147 
148     // IssuerAlternativeNames cache
149     private Collection<List<?>> issuerAlternativeNames;
150 
151     // ExtendedKeyUsage cache
152     private List<String> extKeyUsage;
153 
154     // AuthorityInformationAccess cache
155     private Set<AccessDescription> authInfoAccess;
156 
157     /**
158      * PublicKey that has previously been used to verify
159      * the signature of this certificate. Null if the certificate has not
160      * yet been verified.
161      */
162     private PublicKey verifiedPublicKey;
163     /**
164      * If verifiedPublicKey is not null, name of the provider used to
165      * successfully verify the signature of this certificate, or the
166      * empty String if no provider was explicitly specified.
167      */
168     private String verifiedProvider;
169     /**
170      * If verifiedPublicKey is not null, result of the verification using
171      * verifiedPublicKey and verifiedProvider. If true, verification was
172      * successful, if false, it failed.
173      */
174     private boolean verificationResult;
175 
176     /**
177      * Default constructor.
178      */
179     public X509CertImpl() { }
180 
181     /**
182      * Unmarshals a certificate from its encoded form, parsing the
183      * encoded bytes.  This form of constructor is used by agents which
184      * need to examine and use certificate contents.  That is, this is
185      * one of the more commonly used constructors.  Note that the buffer
186      * must include only a certificate, and no "garbage" may be left at
187      * the end.  If you need to ignore data at the end of a certificate,
188      * use another constructor.
189      *
190      * @param certData the encoded bytes, with no trailing padding.
191      * @exception CertificateException on parsing and initialization errors.
192      */
193     public X509CertImpl(byte[] certData) throws CertificateException {
194         try {
195             parse(new DerValue(certData));
196         } catch (IOException e) {
197             signedCert = null;
198             throw new CertificateException("Unable to initialize, " + e, e);
199         }
200     }
201 
202     /**
203      * unmarshals an X.509 certificate from an input stream.  If the
204      * certificate is RFC1421 hex-encoded, then it must begin with
205      * the line X509Factory.BEGIN_CERT and end with the line
206      * X509Factory.END_CERT.
207      *
208      * @param in an input stream holding at least one certificate that may
209      *        be either DER-encoded or RFC1421 hex-encoded version of the
210      *        DER-encoded certificate.
211      * @exception CertificateException on parsing and initialization errors.
212      */
213     public X509CertImpl(InputStream in) throws CertificateException {
214 
215         DerValue der = null;
216 
217         BufferedInputStream inBuffered = new BufferedInputStream(in);
218 
219         // First try reading stream as HEX-encoded DER-encoded bytes,
220         // since not mistakable for raw DER
221         try {
222             inBuffered.mark(Integer.MAX_VALUE);
223             der = readRFC1421Cert(inBuffered);
224         } catch (IOException ioe) {
225             try {
226                 // Next, try reading stream as raw DER-encoded bytes
227                 inBuffered.reset();
228                 der = new DerValue(inBuffered);
229             } catch (IOException ioe1) {
230                 throw new CertificateException("Input stream must be " +
231                                                "either DER-encoded bytes " +
232                                                "or RFC1421 hex-encoded " +
233                                                "DER-encoded bytes: " +
234                                                ioe1.getMessage(), ioe1);
235             }
236         }
237         try {
238             parse(der);
239         } catch (IOException ioe) {
240             signedCert = null;
241             throw new CertificateException("Unable to parse DER value of " +
242                                            "certificate, " + ioe, ioe);
243         }
244     }
245 
246     /**
247      * read input stream as HEX-encoded DER-encoded bytes
248      *
249      * @param in InputStream to read
250      * @returns DerValue corresponding to decoded HEX-encoded bytes
251      * @throws IOException if stream can not be interpreted as RFC1421
252      *                     encoded bytes
253      */
254     private DerValue readRFC1421Cert(InputStream in) throws IOException {
255         DerValue der = null;
256         String line = null;
257         BufferedReader certBufferedReader =
258             new BufferedReader(new InputStreamReader(in, "ASCII"));
259         try {
260             line = certBufferedReader.readLine();
261         } catch (IOException ioe1) {
262             throw new IOException("Unable to read InputStream: " +
263                                   ioe1.getMessage());
264         }
265         if (line.equals(X509Factory.BEGIN_CERT)) {
266             /* stream appears to be hex-encoded bytes */
267             ByteArrayOutputStream decstream = new ByteArrayOutputStream();
268             try {
269                 while ((line = certBufferedReader.readLine()) != null) {
270                     if (line.equals(X509Factory.END_CERT)) {
271                         der = new DerValue(decstream.toByteArray());
272                         break;
273                     } else {
274                         decstream.write(Base64.getMimeDecoder().decode(line));
275                     }
276                 }
277             } catch (IOException ioe2) {
278                 throw new IOException("Unable to read InputStream: "
279                                       + ioe2.getMessage());
280             }
281         } else {
282             throw new IOException("InputStream is not RFC1421 hex-encoded " +
283                                   "DER bytes");
284         }
285         return der;
286     }
287 
288     /**
289      * Construct an initialized X509 Certificate. The certificate is stored
290      * in raw form and has to be signed to be useful.
291      *
292      * @params info the X509CertificateInfo which the Certificate is to be
293      *              created from.
294      */
295     public X509CertImpl(X509CertInfo certInfo) {
296         this.info = certInfo;
297     }
298 
299     /**
300      * Unmarshal a certificate from its encoded form, parsing a DER value.
301      * This form of constructor is used by agents which need to examine
302      * and use certificate contents.
303      *
304      * @param derVal the der value containing the encoded cert.
305      * @exception CertificateException on parsing and initialization errors.
306      */
307     public X509CertImpl(DerValue derVal) throws CertificateException {
308         try {
309             parse(derVal);
310         } catch (IOException e) {
311             signedCert = null;
312             throw new CertificateException("Unable to initialize, " + e, e);
313         }
314     }
315 
316     /**
317      * Appends the certificate to an output stream.
318      *
319      * @param out an input stream to which the certificate is appended.
320      * @exception CertificateEncodingException on encoding errors.
321      */
322     public void encode(OutputStream out)
323     throws CertificateEncodingException {
324         if (signedCert == null)
325             throw new CertificateEncodingException(
326                           "Null certificate to encode");
327         try {
328             out.write(signedCert.clone());
329         } catch (IOException e) {
330             throw new CertificateEncodingException(e.toString());
331         }
332     }
333 
334     /**
335      * DER encode this object onto an output stream.
336      * Implements the <code>DerEncoder</code> interface.
337      *
338      * @param out the output stream on which to write the DER encoding.
339      *
340      * @exception IOException on encoding error.
341      */
342     public void derEncode(OutputStream out) throws IOException {
343         if (signedCert == null)
344             throw new IOException("Null certificate to encode");
345         out.write(signedCert.clone());
346     }
347 
348     /**
349      * Returns the encoded form of this certificate. It is
350      * assumed that each certificate type would have only a single
351      * form of encoding; for example, X.509 certificates would
352      * be encoded as ASN.1 DER.
353      *
354      * @exception CertificateEncodingException if an encoding error occurs.
355      */
356     public byte[] getEncoded() throws CertificateEncodingException {
357         return getEncodedInternal().clone();
358     }
359 
360     /**
361      * Returned the encoding as an uncloned byte array. Callers must
362      * guarantee that they neither modify it nor expose it to untrusted
363      * code.
364      */
365     public byte[] getEncodedInternal() throws CertificateEncodingException {
366         if (signedCert == null) {
367             throw new CertificateEncodingException(
368                           "Null certificate to encode");
369         }
370         return signedCert;
371     }
372 
373     /**
374      * Throws an exception if the certificate was not signed using the
375      * verification key provided.  Successfully verifying a certificate
376      * does <em>not</em> indicate that one should trust the entity which
377      * it represents.
378      *
379      * @param key the public key used for verification.
380      *
381      * @exception InvalidKeyException on incorrect key.
382      * @exception NoSuchAlgorithmException on unsupported signature
383      * algorithms.
384      * @exception NoSuchProviderException if there's no default provider.
385      * @exception SignatureException on signature errors.
386      * @exception CertificateException on encoding errors.
387      */
388     public void verify(PublicKey key)
389     throws CertificateException, NoSuchAlgorithmException,
390         InvalidKeyException, NoSuchProviderException, SignatureException {
391 
392         verify(key, "");
393     }
394 
395     /**
396      * Throws an exception if the certificate was not signed using the
397      * verification key provided.  Successfully verifying a certificate
398      * does <em>not</em> indicate that one should trust the entity which
399      * it represents.
400      *
401      * @param key the public key used for verification.
402      * @param sigProvider the name of the provider.
403      *
404      * @exception NoSuchAlgorithmException on unsupported signature
405      * algorithms.
406      * @exception InvalidKeyException on incorrect key.
407      * @exception NoSuchProviderException on incorrect provider.
408      * @exception SignatureException on signature errors.
409      * @exception CertificateException on encoding errors.
410      */
411     public synchronized void verify(PublicKey key, String sigProvider)
412             throws CertificateException, NoSuchAlgorithmException,
413             InvalidKeyException, NoSuchProviderException, SignatureException {
414         if (sigProvider == null) {
415             sigProvider = "";
416         }
417         if ((verifiedPublicKey != null) && verifiedPublicKey.equals(key)) {
418             // this certificate has already been verified using
419             // this public key. Make sure providers match, too.
420             if (sigProvider.equals(verifiedProvider)) {
421                 if (verificationResult) {
422                     return;
423                 } else {
424                     throw new SignatureException("Signature does not match.");
425                 }
426             }
427         }
428         if (signedCert == null) {
429             throw new CertificateEncodingException("Uninitialized certificate");
430         }
431         // Verify the signature ...
432         Signature sigVerf = null;
433         if (sigProvider.length() == 0) {
434             sigVerf = Signature.getInstance(algId.getName());
435         } else {
436             sigVerf = Signature.getInstance(algId.getName(), sigProvider);
437         }
438         sigVerf.initVerify(key);
439 
440         byte[] rawCert = info.getEncodedInfo();
441         sigVerf.update(rawCert, 0, rawCert.length);
442 
443         // verify may throw SignatureException for invalid encodings, etc.
444         verificationResult = sigVerf.verify(signature);
445         verifiedPublicKey = key;
446         verifiedProvider = sigProvider;
447 
448         if (verificationResult == false) {
449             throw new SignatureException("Signature does not match.");
450         }
451     }
452 
453     /**
454      * Throws an exception if the certificate was not signed using the
455      * verification key provided.  This method uses the signature verification
456      * engine supplied by the specified provider. Note that the specified
457      * Provider object does not have to be registered in the provider list.
458      * Successfully verifying a certificate does <em>not</em> indicate that one
459      * should trust the entity which it represents.
460      *
461      * @param key the public key used for verification.
462      * @param sigProvider the provider.
463      *
464      * @exception NoSuchAlgorithmException on unsupported signature
465      * algorithms.
466      * @exception InvalidKeyException on incorrect key.
467      * @exception SignatureException on signature errors.
468      * @exception CertificateException on encoding errors.
469      */
470     public synchronized void verify(PublicKey key, Provider sigProvider)
471             throws CertificateException, NoSuchAlgorithmException,
472             InvalidKeyException, SignatureException {
473         if (signedCert == null) {
474             throw new CertificateEncodingException("Uninitialized certificate");
475         }
476         // Verify the signature ...
477         Signature sigVerf = null;
478         if (sigProvider == null) {
479             sigVerf = Signature.getInstance(algId.getName());
480         } else {
481             sigVerf = Signature.getInstance(algId.getName(), sigProvider);
482         }
483         sigVerf.initVerify(key);
484 
485         byte[] rawCert = info.getEncodedInfo();
486         sigVerf.update(rawCert, 0, rawCert.length);
487 
488         // verify may throw SignatureException for invalid encodings, etc.
489         verificationResult = sigVerf.verify(signature);
490         verifiedPublicKey = key;
491 
492         if (verificationResult == false) {
493             throw new SignatureException("Signature does not match.");
494         }
495     }
496 
497      /**
498      * This static method is the default implementation of the
499      * verify(PublicKey key, Provider sigProvider) method in X509Certificate.
500      * Called from java.security.cert.X509Certificate.verify(PublicKey key,
501      * Provider sigProvider)
502      */
503     public static void verify(X509Certificate cert, PublicKey key,
504             Provider sigProvider) throws CertificateException,
505             NoSuchAlgorithmException, InvalidKeyException, SignatureException {
506         cert.verify(key, sigProvider);
507     }
508 
509     /**
510      * Creates an X.509 certificate, and signs it using the given key
511      * (associating a signature algorithm and an X.500 name).
512      * This operation is used to implement the certificate generation
513      * functionality of a certificate authority.
514      *
515      * @param key the private key used for signing.
516      * @param algorithm the name of the signature algorithm used.
517      *
518      * @exception InvalidKeyException on incorrect key.
519      * @exception NoSuchAlgorithmException on unsupported signature
520      * algorithms.
521      * @exception NoSuchProviderException if there's no default provider.
522      * @exception SignatureException on signature errors.
523      * @exception CertificateException on encoding errors.
524      */
525     public void sign(PrivateKey key, String algorithm)
526     throws CertificateException, NoSuchAlgorithmException,
527         InvalidKeyException, NoSuchProviderException, SignatureException {
528         sign(key, algorithm, null);
529     }
530 
531     /**
532      * Creates an X.509 certificate, and signs it using the given key
533      * (associating a signature algorithm and an X.500 name).
534      * This operation is used to implement the certificate generation
535      * functionality of a certificate authority.
536      *
537      * @param key the private key used for signing.
538      * @param algorithm the name of the signature algorithm used.
539      * @param provider the name of the provider.
540      *
541      * @exception NoSuchAlgorithmException on unsupported signature
542      * algorithms.
543      * @exception InvalidKeyException on incorrect key.
544      * @exception NoSuchProviderException on incorrect provider.
545      * @exception SignatureException on signature errors.
546      * @exception CertificateException on encoding errors.
547      */
548     public void sign(PrivateKey key, String algorithm, String provider)
549     throws CertificateException, NoSuchAlgorithmException,
550         InvalidKeyException, NoSuchProviderException, SignatureException {
551         try {
552             if (readOnly)
553                 throw new CertificateEncodingException(
554                               "cannot over-write existing certificate");
555             Signature sigEngine = null;
556             if ((provider == null) || (provider.length() == 0))
557                 sigEngine = Signature.getInstance(algorithm);
558             else
559                 sigEngine = Signature.getInstance(algorithm, provider);
560 
561             sigEngine.initSign(key);
562 
563                                 // in case the name is reset
564             algId = AlgorithmId.get(sigEngine.getAlgorithm());
565 
566             DerOutputStream out = new DerOutputStream();
567             DerOutputStream tmp = new DerOutputStream();
568 
569             // encode certificate info
570             info.encode(tmp);
571             byte[] rawCert = tmp.toByteArray();
572 
573             // encode algorithm identifier
574             algId.encode(tmp);
575 
576             // Create and encode the signature itself.
577             sigEngine.update(rawCert, 0, rawCert.length);
578             signature = sigEngine.sign();
579             tmp.putBitString(signature);
580 
581             // Wrap the signed data in a SEQUENCE { data, algorithm, sig }
582             out.write(DerValue.tag_Sequence, tmp);
583             signedCert = out.toByteArray();
584             readOnly = true;
585 
586         } catch (IOException e) {
587             throw new CertificateEncodingException(e.toString());
588       }
589     }
590 
591     /**
592      * Checks that the certificate is currently valid, i.e. the current
593      * time is within the specified validity period.
594      *
595      * @exception CertificateExpiredException if the certificate has expired.
596      * @exception CertificateNotYetValidException if the certificate is not
597      * yet valid.
598      */
599     public void checkValidity()
600     throws CertificateExpiredException, CertificateNotYetValidException {
601         Date date = new Date();
602         checkValidity(date);
603     }
604 
605     /**
606      * Checks that the specified date is within the certificate's
607      * validity period, or basically if the certificate would be
608      * valid at the specified date/time.
609      *
610      * @param date the Date to check against to see if this certificate
611      *        is valid at that date/time.
612      *
613      * @exception CertificateExpiredException if the certificate has expired
614      * with respect to the <code>date</code> supplied.
615      * @exception CertificateNotYetValidException if the certificate is not
616      * yet valid with respect to the <code>date</code> supplied.
617      */
618     public void checkValidity(Date date)
619     throws CertificateExpiredException, CertificateNotYetValidException {
620 
621         CertificateValidity interval = null;
622         try {
623             interval = (CertificateValidity)info.get(CertificateValidity.NAME);
624         } catch (Exception e) {
625             throw new CertificateNotYetValidException("Incorrect validity period");
626         }
627         if (interval == null)
628             throw new CertificateNotYetValidException("Null validity period");
629         interval.valid(date);
630     }
631 
632     /**
633      * Return the requested attribute from the certificate.
634      *
635      * Note that the X509CertInfo is not cloned for performance reasons.
636      * Callers must ensure that they do not modify it. All other
637      * attributes are cloned.
638      *
639      * @param name the name of the attribute.
640      * @exception CertificateParsingException on invalid attribute identifier.
641      */
642     public Object get(String name)
643     throws CertificateParsingException {
644         X509AttributeName attr = new X509AttributeName(name);
645         String id = attr.getPrefix();
646         if (!(id.equalsIgnoreCase(NAME))) {
647             throw new CertificateParsingException("Invalid root of "
648                           + "attribute name, expected [" + NAME +
649                           "], received " + "[" + id + "]");
650         }
651         attr = new X509AttributeName(attr.getSuffix());
652         id = attr.getPrefix();
653 
654         if (id.equalsIgnoreCase(INFO)) {
655             if (info == null) {
656                 return null;
657             }
658             if (attr.getSuffix() != null) {
659                 try {
660                     return info.get(attr.getSuffix());
661                 } catch (IOException e) {
662                     throw new CertificateParsingException(e.toString());
663                 } catch (CertificateException e) {
664                     throw new CertificateParsingException(e.toString());
665                 }
666             } else {
667                 return info;
668             }
669         } else if (id.equalsIgnoreCase(ALG_ID)) {
670             return(algId);
671         } else if (id.equalsIgnoreCase(SIGNATURE)) {
672             if (signature != null)
673                 return signature.clone();
674             else
675                 return null;
676         } else if (id.equalsIgnoreCase(SIGNED_CERT)) {
677             if (signedCert != null)
678                 return signedCert.clone();
679             else
680                 return null;
681         } else {
682             throw new CertificateParsingException("Attribute name not "
683                  + "recognized or get() not allowed for the same: " + id);
684         }
685     }
686 
687     /**
688      * Set the requested attribute in the certificate.
689      *
690      * @param name the name of the attribute.
691      * @param obj the value of the attribute.
692      * @exception CertificateException on invalid attribute identifier.
693      * @exception IOException on encoding error of attribute.
694      */
695     public void set(String name, Object obj)
696     throws CertificateException, IOException {
697         // check if immutable
698         if (readOnly)
699             throw new CertificateException("cannot over-write existing"
700                                            + " certificate");
701 
702         X509AttributeName attr = new X509AttributeName(name);
703         String id = attr.getPrefix();
704         if (!(id.equalsIgnoreCase(NAME))) {
705             throw new CertificateException("Invalid root of attribute name,"
706                            + " expected [" + NAME + "], received " + id);
707         }
708         attr = new X509AttributeName(attr.getSuffix());
709         id = attr.getPrefix();
710 
711         if (id.equalsIgnoreCase(INFO)) {
712             if (attr.getSuffix() == null) {
713                 if (!(obj instanceof X509CertInfo)) {
714                     throw new CertificateException("Attribute value should"
715                                     + " be of type X509CertInfo.");
716                 }
717                 info = (X509CertInfo)obj;
718                 signedCert = null;  //reset this as certificate data has changed
719             } else {
720                 info.set(attr.getSuffix(), obj);
721                 signedCert = null;  //reset this as certificate data has changed
722             }
723         } else {
724             throw new CertificateException("Attribute name not recognized or " +
725                               "set() not allowed for the same: " + id);
726         }
727     }
728 
729     /**
730      * Delete the requested attribute from the certificate.
731      *
732      * @param name the name of the attribute.
733      * @exception CertificateException on invalid attribute identifier.
734      * @exception IOException on other errors.
735      */
736     public void delete(String name)
737     throws CertificateException, IOException {
738         // check if immutable
739         if (readOnly)
740             throw new CertificateException("cannot over-write existing"
741                                            + " certificate");
742 
743         X509AttributeName attr = new X509AttributeName(name);
744         String id = attr.getPrefix();
745         if (!(id.equalsIgnoreCase(NAME))) {
746             throw new CertificateException("Invalid root of attribute name,"
747                                    + " expected ["
748                                    + NAME + "], received " + id);
749         }
750         attr = new X509AttributeName(attr.getSuffix());
751         id = attr.getPrefix();
752 
753         if (id.equalsIgnoreCase(INFO)) {
754             if (attr.getSuffix() != null) {
755                 info = null;
756             } else {
757                 info.delete(attr.getSuffix());
758             }
759         } else if (id.equalsIgnoreCase(ALG_ID)) {
760             algId = null;
761         } else if (id.equalsIgnoreCase(SIGNATURE)) {
762             signature = null;
763         } else if (id.equalsIgnoreCase(SIGNED_CERT)) {
764             signedCert = null;
765         } else {
766             throw new CertificateException("Attribute name not recognized or " +
767                               "delete() not allowed for the same: " + id);
768         }
769     }
770 
771     /**
772      * Return an enumeration of names of attributes existing within this
773      * attribute.
774      */
775     public Enumeration<String> getElements() {
776         AttributeNameEnumeration elements = new AttributeNameEnumeration();
777         elements.addElement(NAME + DOT + INFO);
778         elements.addElement(NAME + DOT + ALG_ID);
779         elements.addElement(NAME + DOT + SIGNATURE);
780         elements.addElement(NAME + DOT + SIGNED_CERT);
781 
782         return elements.elements();
783     }
784 
785     /**
786      * Return the name of this attribute.
787      */
788     public String getName() {
789         return(NAME);
790     }
791 
792     /**
793      * Returns a printable representation of the certificate.  This does not
794      * contain all the information available to distinguish this from any
795      * other certificate.  The certificate must be fully constructed
796      * before this function may be called.
797      */
798     public String toString() {
799         if (info == null || algId == null || signature == null)
800             return "";
801 
802         StringBuilder sb = new StringBuilder();
803 
804         sb.append("[\n");
805         sb.append(info.toString() + "\n");
806         sb.append("  Algorithm: [" + algId.toString() + "]\n");
807 
808         HexDumpEncoder encoder = new HexDumpEncoder();
809         sb.append("  Signature:\n" + encoder.encodeBuffer(signature));
810         sb.append("\n]");
811 
812         return sb.toString();
813     }
814 
815     // the strongly typed gets, as per java.security.cert.X509Certificate
816 
817     /**
818      * Gets the publickey from this certificate.
819      *
820      * @return the publickey.
821      */
822     public PublicKey getPublicKey() {
823         if (info == null)
824             return null;
825         try {
826             PublicKey key = (PublicKey)info.get(CertificateX509Key.NAME
827                                 + DOT + CertificateX509Key.KEY);
828             return key;
829         } catch (Exception e) {
830             return null;
831         }
832     }
833 
834     /**
835      * Gets the version number from the certificate.
836      *
837      * @return the version number, i.e. 1, 2 or 3.
838      */
839     public int getVersion() {
840         if (info == null)
841             return -1;
842         try {
843             int vers = ((Integer)info.get(CertificateVersion.NAME
844                         + DOT + CertificateVersion.VERSION)).intValue();
845             return vers+1;
846         } catch (Exception e) {
847             return -1;
848         }
849     }
850 
851     /**
852      * Gets the serial number from the certificate.
853      *
854      * @return the serial number.
855      */
856     public BigInteger getSerialNumber() {
857         SerialNumber ser = getSerialNumberObject();
858 
859         return ser != null ? ser.getNumber() : null;
860     }
861 
862     /**
863      * Gets the serial number from the certificate as
864      * a SerialNumber object.
865      *
866      * @return the serial number.
867      */
868     public SerialNumber getSerialNumberObject() {
869         if (info == null)
870             return null;
871         try {
872             SerialNumber ser = (SerialNumber)info.get(
873                               CertificateSerialNumber.NAME + DOT +
874                               CertificateSerialNumber.NUMBER);
875            return ser;
876         } catch (Exception e) {
877             return null;
878         }
879     }
880 
881 
882     /**
883      * Gets the subject distinguished name from the certificate.
884      *
885      * @return the subject name.
886      */
887     public Principal getSubjectDN() {
888         if (info == null)
889             return null;
890         try {
891             Principal subject = (Principal)info.get(X509CertInfo.SUBJECT + DOT +
892                                                     X509CertInfo.DN_NAME);
893             return subject;
894         } catch (Exception e) {
895             return null;
896         }
897     }
898 
899     /**
900      * Get subject name as X500Principal. Overrides implementation in
901      * X509Certificate with a slightly more efficient version that is
902      * also aware of X509CertImpl mutability.
903      */
904     public X500Principal getSubjectX500Principal() {
905         if (info == null) {
906             return null;
907         }
908         try {
909             X500Principal subject = (X500Principal)info.get(
910                                             X509CertInfo.SUBJECT + DOT +
911                                             "x500principal");
912             return subject;
913         } catch (Exception e) {
914             return null;
915         }
916     }
917 
918     /**
919      * Gets the issuer distinguished name from the certificate.
920      *
921      * @return the issuer name.
922      */
923     public Principal getIssuerDN() {
924         if (info == null)
925             return null;
926         try {
927             Principal issuer = (Principal)info.get(X509CertInfo.ISSUER + DOT +
928                                                    X509CertInfo.DN_NAME);
929             return issuer;
930         } catch (Exception e) {
931             return null;
932         }
933     }
934 
935     /**
936      * Get issuer name as X500Principal. Overrides implementation in
937      * X509Certificate with a slightly more efficient version that is
938      * also aware of X509CertImpl mutability.
939      */
940     public X500Principal getIssuerX500Principal() {
941         if (info == null) {
942             return null;
943         }
944         try {
945             X500Principal issuer = (X500Principal)info.get(
946                                             X509CertInfo.ISSUER + DOT +
947                                             "x500principal");
948             return issuer;
949         } catch (Exception e) {
950             return null;
951         }
952     }
953 
954     /**
955      * Gets the notBefore date from the validity period of the certificate.
956      *
957      * @return the start date of the validity period.
958      */
959     public Date getNotBefore() {
960         if (info == null)
961             return null;
962         try {
963             Date d = (Date) info.get(CertificateValidity.NAME + DOT +
964                                         CertificateValidity.NOT_BEFORE);
965             return d;
966         } catch (Exception e) {
967             return null;
968         }
969     }
970 
971     /**
972      * Gets the notAfter date from the validity period of the certificate.
973      *
974      * @return the end date of the validity period.
975      */
976     public Date getNotAfter() {
977         if (info == null)
978             return null;
979         try {
980             Date d = (Date) info.get(CertificateValidity.NAME + DOT +
981                                      CertificateValidity.NOT_AFTER);
982             return d;
983         } catch (Exception e) {
984             return null;
985         }
986     }
987 
988     /**
989      * Gets the DER encoded certificate informations, the
990      * <code>tbsCertificate</code> from this certificate.
991      * This can be used to verify the signature independently.
992      *
993      * @return the DER encoded certificate information.
994      * @exception CertificateEncodingException if an encoding error occurs.
995      */
996     public byte[] getTBSCertificate() throws CertificateEncodingException {
997         if (info != null) {
998             return info.getEncodedInfo();
999         } else
1000             throw new CertificateEncodingException("Uninitialized certificate");
1001     }
1002 
1003     /**
1004      * Gets the raw Signature bits from the certificate.
1005      *
1006      * @return the signature.
1007      */
1008     public byte[] getSignature() {
1009         if (signature == null)
1010             return null;
1011         byte[] dup = new byte[signature.length];
1012         System.arraycopy(signature, 0, dup, 0, dup.length);
1013         return dup;
1014     }
1015 
1016     /**
1017      * Gets the signature algorithm name for the certificate
1018      * signature algorithm.
1019      * For example, the string "SHA-1/DSA" or "DSS".
1020      *
1021      * @return the signature algorithm name.
1022      */
1023     public String getSigAlgName() {
1024         if (algId == null)
1025             return null;
1026         return (algId.getName());
1027     }
1028 
1029     /**
1030      * Gets the signature algorithm OID string from the certificate.
1031      * For example, the string "1.2.840.10040.4.3"
1032      *
1033      * @return the signature algorithm oid string.
1034      */
1035     public String getSigAlgOID() {
1036         if (algId == null)
1037             return null;
1038         ObjectIdentifier oid = algId.getOID();
1039         return (oid.toString());
1040     }
1041 
1042     /**
1043      * Gets the DER encoded signature algorithm parameters from this
1044      * certificate's signature algorithm.
1045      *
1046      * @return the DER encoded signature algorithm parameters, or
1047      *         null if no parameters are present.
1048      */
1049     public byte[] getSigAlgParams() {
1050         if (algId == null)
1051             return null;
1052         try {
1053             return algId.getEncodedParams();
1054         } catch (IOException e) {
1055             return null;
1056         }
1057     }
1058 
1059     /**
1060      * Gets the Issuer Unique Identity from the certificate.
1061      *
1062      * @return the Issuer Unique Identity.
1063      */
1064     public boolean[] getIssuerUniqueID() {
1065         if (info == null)
1066             return null;
1067         try {
1068             UniqueIdentity id = (UniqueIdentity)info.get(
1069                                  X509CertInfo.ISSUER_ID);
1070             if (id == null)
1071                 return null;
1072             else
1073                 return (id.getId());
1074         } catch (Exception e) {
1075             return null;
1076         }
1077     }
1078 
1079     /**
1080      * Gets the Subject Unique Identity from the certificate.
1081      *
1082      * @return the Subject Unique Identity.
1083      */
1084     public boolean[] getSubjectUniqueID() {
1085         if (info == null)
1086             return null;
1087         try {
1088             UniqueIdentity id = (UniqueIdentity)info.get(
1089                                  X509CertInfo.SUBJECT_ID);
1090             if (id == null)
1091                 return null;
1092             else
1093                 return (id.getId());
1094         } catch (Exception e) {
1095             return null;
1096         }
1097     }
1098 
1099     public KeyIdentifier getAuthKeyId() {
1100         AuthorityKeyIdentifierExtension aki
1101             = getAuthorityKeyIdentifierExtension();
1102         if (aki != null) {
1103             try {
1104                 return (KeyIdentifier)aki.get(
1105                     AuthorityKeyIdentifierExtension.KEY_ID);
1106             } catch (IOException ioe) {} // not possible
1107         }
1108         return null;
1109     }
1110 
1111     /**
1112      * Returns the subject's key identifier, or null
1113      */
1114     public KeyIdentifier getSubjectKeyId() {
1115         SubjectKeyIdentifierExtension ski = getSubjectKeyIdentifierExtension();
1116         if (ski != null) {
1117             try {
1118                 return (KeyIdentifier)ski.get(
1119                     SubjectKeyIdentifierExtension.KEY_ID);
1120             } catch (IOException ioe) {} // not possible
1121         }
1122         return null;
1123     }
1124 
1125     /**
1126      * Get AuthorityKeyIdentifier extension
1127      * @return AuthorityKeyIdentifier object or null (if no such object
1128      * in certificate)
1129      */
1130     public AuthorityKeyIdentifierExtension getAuthorityKeyIdentifierExtension()
1131     {
1132         return (AuthorityKeyIdentifierExtension)
1133             getExtension(PKIXExtensions.AuthorityKey_Id);
1134     }
1135 
1136     /**
1137      * Get BasicConstraints extension
1138      * @return BasicConstraints object or null (if no such object in
1139      * certificate)
1140      */
1141     public BasicConstraintsExtension getBasicConstraintsExtension() {
1142         return (BasicConstraintsExtension)
1143             getExtension(PKIXExtensions.BasicConstraints_Id);
1144     }
1145 
1146     /**
1147      * Get CertificatePoliciesExtension
1148      * @return CertificatePoliciesExtension or null (if no such object in
1149      * certificate)
1150      */
1151     public CertificatePoliciesExtension getCertificatePoliciesExtension() {
1152         return (CertificatePoliciesExtension)
1153             getExtension(PKIXExtensions.CertificatePolicies_Id);
1154     }
1155 
1156     /**
1157      * Get ExtendedKeyUsage extension
1158      * @return ExtendedKeyUsage extension object or null (if no such object
1159      * in certificate)
1160      */
1161     public ExtendedKeyUsageExtension getExtendedKeyUsageExtension() {
1162         return (ExtendedKeyUsageExtension)
1163             getExtension(PKIXExtensions.ExtendedKeyUsage_Id);
1164     }
1165 
1166     /**
1167      * Get IssuerAlternativeName extension
1168      * @return IssuerAlternativeName object or null (if no such object in
1169      * certificate)
1170      */
1171     public IssuerAlternativeNameExtension getIssuerAlternativeNameExtension() {
1172         return (IssuerAlternativeNameExtension)
1173             getExtension(PKIXExtensions.IssuerAlternativeName_Id);
1174     }
1175 
1176     /**
1177      * Get NameConstraints extension
1178      * @return NameConstraints object or null (if no such object in certificate)
1179      */
1180     public NameConstraintsExtension getNameConstraintsExtension() {
1181         return (NameConstraintsExtension)
1182             getExtension(PKIXExtensions.NameConstraints_Id);
1183     }
1184 
1185     /**
1186      * Get PolicyConstraints extension
1187      * @return PolicyConstraints object or null (if no such object in
1188      * certificate)
1189      */
1190     public PolicyConstraintsExtension getPolicyConstraintsExtension() {
1191         return (PolicyConstraintsExtension)
1192             getExtension(PKIXExtensions.PolicyConstraints_Id);
1193     }
1194 
1195     /**
1196      * Get PolicyMappingsExtension extension
1197      * @return PolicyMappingsExtension object or null (if no such object
1198      * in certificate)
1199      */
1200     public PolicyMappingsExtension getPolicyMappingsExtension() {
1201         return (PolicyMappingsExtension)
1202             getExtension(PKIXExtensions.PolicyMappings_Id);
1203     }
1204 
1205     /**
1206      * Get PrivateKeyUsage extension
1207      * @return PrivateKeyUsage object or null (if no such object in certificate)
1208      */
1209     public PrivateKeyUsageExtension getPrivateKeyUsageExtension() {
1210         return (PrivateKeyUsageExtension)
1211             getExtension(PKIXExtensions.PrivateKeyUsage_Id);
1212     }
1213 
1214     /**
1215      * Get SubjectAlternativeName extension
1216      * @return SubjectAlternativeName object or null (if no such object in
1217      * certificate)
1218      */
1219     public SubjectAlternativeNameExtension getSubjectAlternativeNameExtension()
1220     {
1221         return (SubjectAlternativeNameExtension)
1222             getExtension(PKIXExtensions.SubjectAlternativeName_Id);
1223     }
1224 
1225     /**
1226      * Get SubjectKeyIdentifier extension
1227      * @return SubjectKeyIdentifier object or null (if no such object in
1228      * certificate)
1229      */
1230     public SubjectKeyIdentifierExtension getSubjectKeyIdentifierExtension() {
1231         return (SubjectKeyIdentifierExtension)
1232             getExtension(PKIXExtensions.SubjectKey_Id);
1233     }
1234 
1235     /**
1236      * Get CRLDistributionPoints extension
1237      * @return CRLDistributionPoints object or null (if no such object in
1238      * certificate)
1239      */
1240     public CRLDistributionPointsExtension getCRLDistributionPointsExtension() {
1241         return (CRLDistributionPointsExtension)
1242             getExtension(PKIXExtensions.CRLDistributionPoints_Id);
1243     }
1244 
1245     /**
1246      * Return true if a critical extension is found that is
1247      * not supported, otherwise return false.
1248      */
1249     public boolean hasUnsupportedCriticalExtension() {
1250         if (info == null)
1251             return false;
1252         try {
1253             CertificateExtensions exts = (CertificateExtensions)info.get(
1254                                          CertificateExtensions.NAME);
1255             if (exts == null)
1256                 return false;
1257             return exts.hasUnsupportedCriticalExtension();
1258         } catch (Exception e) {
1259             return false;
1260         }
1261     }
1262 
1263     /**
1264      * Gets a Set of the extension(s) marked CRITICAL in the
1265      * certificate. In the returned set, each extension is
1266      * represented by its OID string.
1267      *
1268      * @return a set of the extension oid strings in the
1269      * certificate that are marked critical.
1270      */
1271     public Set<String> getCriticalExtensionOIDs() {
1272         if (info == null) {
1273             return null;
1274         }
1275         try {
1276             CertificateExtensions exts = (CertificateExtensions)info.get(
1277                                          CertificateExtensions.NAME);
1278             if (exts == null) {
1279                 return null;
1280             }
1281             Set<String> extSet = new TreeSet<>();
1282             for (Extension ex : exts.getAllExtensions()) {
1283                 if (ex.isCritical()) {
1284                     extSet.add(ex.getExtensionId().toString());
1285                 }
1286             }
1287             return extSet;
1288         } catch (Exception e) {
1289             return null;
1290         }
1291     }
1292 
1293     /**
1294      * Gets a Set of the extension(s) marked NON-CRITICAL in the
1295      * certificate. In the returned set, each extension is
1296      * represented by its OID string.
1297      *
1298      * @return a set of the extension oid strings in the
1299      * certificate that are NOT marked critical.
1300      */
1301     public Set<String> getNonCriticalExtensionOIDs() {
1302         if (info == null) {
1303             return null;
1304         }
1305         try {
1306             CertificateExtensions exts = (CertificateExtensions)info.get(
1307                                          CertificateExtensions.NAME);
1308             if (exts == null) {
1309                 return null;
1310             }
1311             Set<String> extSet = new TreeSet<>();
1312             for (Extension ex : exts.getAllExtensions()) {
1313                 if (!ex.isCritical()) {
1314                     extSet.add(ex.getExtensionId().toString());
1315                 }
1316             }
1317             extSet.addAll(exts.getUnparseableExtensions().keySet());
1318             return extSet;
1319         } catch (Exception e) {
1320             return null;
1321         }
1322     }
1323 
1324     /**
1325      * Gets the extension identified by the given ObjectIdentifier
1326      *
1327      * @param oid the Object Identifier value for the extension.
1328      * @return Extension or null if certificate does not contain this
1329      *         extension
1330      */
1331     public Extension getExtension(ObjectIdentifier oid) {
1332         if (info == null) {
1333             return null;
1334         }
1335         try {
1336             CertificateExtensions extensions;
1337             try {
1338                 extensions = (CertificateExtensions)info.get(CertificateExtensions.NAME);
1339             } catch (CertificateException ce) {
1340                 return null;
1341             }
1342             if (extensions == null) {
1343                 return null;
1344             } else {
1345                 Extension ex = extensions.getExtension(oid.toString());
1346                 if (ex != null) {
1347                     return ex;
1348                 }
1349                 for (Extension ex2: extensions.getAllExtensions()) {
1350                     if (ex2.getExtensionId().equals((Object)oid)) {
1351                         //XXXX May want to consider cloning this
1352                         return ex2;
1353                     }
1354                 }
1355                 /* no such extension in this certificate */
1356                 return null;
1357             }
1358         } catch (IOException ioe) {
1359             return null;
1360         }
1361     }
1362 
1363     public Extension getUnparseableExtension(ObjectIdentifier oid) {
1364         if (info == null) {
1365             return null;
1366         }
1367         try {
1368             CertificateExtensions extensions;
1369             try {
1370                 extensions = (CertificateExtensions)info.get(CertificateExtensions.NAME);
1371             } catch (CertificateException ce) {
1372                 return null;
1373             }
1374             if (extensions == null) {
1375                 return null;
1376             } else {
1377                 return extensions.getUnparseableExtensions().get(oid.toString());
1378             }
1379         } catch (IOException ioe) {
1380             return null;
1381         }
1382     }
1383 
1384     /**
1385      * Gets the DER encoded extension identified by the given
1386      * oid String.
1387      *
1388      * @param oid the Object Identifier value for the extension.
1389      */
1390     public byte[] getExtensionValue(String oid) {
1391         try {
1392             ObjectIdentifier findOID = new ObjectIdentifier(oid);
1393             String extAlias = OIDMap.getName(findOID);
1394             Extension certExt = null;
1395             CertificateExtensions exts = (CertificateExtensions)info.get(
1396                                      CertificateExtensions.NAME);
1397 
1398             if (extAlias == null) { // may be unknown
1399                 // get the extensions, search thru' for this oid
1400                 if (exts == null) {
1401                     return null;
1402                 }
1403 
1404                 for (Extension ex : exts.getAllExtensions()) {
1405                     ObjectIdentifier inCertOID = ex.getExtensionId();
1406                     if (inCertOID.equals((Object)findOID)) {
1407                         certExt = ex;
1408                         break;
1409                     }
1410                 }
1411             } else { // there's sub-class that can handle this extension
1412                 try {
1413                     certExt = (Extension)this.get(extAlias);
1414                 } catch (CertificateException e) {
1415                     // get() throws an Exception instead of returning null, ignore
1416                 }
1417             }
1418             if (certExt == null) {
1419                 if (exts != null) {
1420                     certExt = exts.getUnparseableExtensions().get(oid);
1421                 }
1422                 if (certExt == null) {
1423                     return null;
1424                 }
1425             }
1426             byte[] extData = certExt.getExtensionValue();
1427             if (extData == null) {
1428                 return null;
1429             }
1430             DerOutputStream out = new DerOutputStream();
1431             out.putOctetString(extData);
1432             return out.toByteArray();
1433         } catch (Exception e) {
1434             return null;
1435         }
1436     }
1437 
1438     /**
1439      * Get a boolean array representing the bits of the KeyUsage extension,
1440      * (oid = 2.5.29.15).
1441      * @return the bit values of this extension as an array of booleans.
1442      */
1443     public boolean[] getKeyUsage() {
1444         try {
1445             String extAlias = OIDMap.getName(PKIXExtensions.KeyUsage_Id);
1446             if (extAlias == null)
1447                 return null;
1448 
1449             KeyUsageExtension certExt = (KeyUsageExtension)this.get(extAlias);
1450             if (certExt == null)
1451                 return null;
1452 
1453             boolean[] ret = certExt.getBits();
1454             if (ret.length < NUM_STANDARD_KEY_USAGE) {
1455                 boolean[] usageBits = new boolean[NUM_STANDARD_KEY_USAGE];
1456                 System.arraycopy(ret, 0, usageBits, 0, ret.length);
1457                 ret = usageBits;
1458             }
1459             return ret;
1460         } catch (Exception e) {
1461             return null;
1462         }
1463     }
1464 
1465     /**
1466      * This method are the overridden implementation of
1467      * getExtendedKeyUsage method in X509Certificate in the Sun
1468      * provider. It is better performance-wise since it returns cached
1469      * values.
1470      */
1471     public synchronized List<String> getExtendedKeyUsage()
1472         throws CertificateParsingException {
1473         if (readOnly && extKeyUsage != null) {
1474             return extKeyUsage;
1475         } else {
1476             ExtendedKeyUsageExtension ext = getExtendedKeyUsageExtension();
1477             if (ext == null) {
1478                 return null;
1479             }
1480             extKeyUsage =
1481                 Collections.unmodifiableList(ext.getExtendedKeyUsage());
1482             return extKeyUsage;
1483         }
1484     }
1485 
1486     /**
1487      * This static method is the default implementation of the
1488      * getExtendedKeyUsage method in X509Certificate. A
1489      * X509Certificate provider generally should overwrite this to
1490      * provide among other things caching for better performance.
1491      */
1492     public static List<String> getExtendedKeyUsage(X509Certificate cert)
1493         throws CertificateParsingException {
1494         try {
1495             byte[] ext = cert.getExtensionValue(EXTENDED_KEY_USAGE_OID);
1496             if (ext == null)
1497                 return null;
1498             DerValue val = new DerValue(ext);
1499             byte[] data = val.getOctetString();
1500 
1501             ExtendedKeyUsageExtension ekuExt =
1502                 new ExtendedKeyUsageExtension(Boolean.FALSE, data);
1503             return Collections.unmodifiableList(ekuExt.getExtendedKeyUsage());
1504         } catch (IOException ioe) {
1505             throw new CertificateParsingException(ioe);
1506         }
1507     }
1508 
1509     /**
1510      * Get the certificate constraints path length from the
1511      * the critical BasicConstraints extension, (oid = 2.5.29.19).
1512      * @return the length of the constraint.
1513      */
1514     public int getBasicConstraints() {
1515         try {
1516             String extAlias = OIDMap.getName(PKIXExtensions.BasicConstraints_Id);
1517             if (extAlias == null)
1518                 return -1;
1519             BasicConstraintsExtension certExt =
1520                         (BasicConstraintsExtension)this.get(extAlias);
1521             if (certExt == null)
1522                 return -1;
1523 
1524             if (((Boolean)certExt.get(BasicConstraintsExtension.IS_CA)
1525                  ).booleanValue() == true)
1526                 return ((Integer)certExt.get(
1527                         BasicConstraintsExtension.PATH_LEN)).intValue();
1528             else
1529                 return -1;
1530         } catch (Exception e) {
1531             return -1;
1532         }
1533     }
1534 
1535     /**
1536      * Converts a GeneralNames structure into an immutable Collection of
1537      * alternative names (subject or issuer) in the form required by
1538      * {@link #getSubjectAlternativeNames} or
1539      * {@link #getIssuerAlternativeNames}.
1540      *
1541      * @param names the GeneralNames to be converted
1542      * @return an immutable Collection of alternative names
1543      */
1544     private static Collection<List<?>> makeAltNames(GeneralNames names) {
1545         if (names.isEmpty()) {
1546             return Collections.<List<?>>emptySet();
1547         }
1548         List<List<?>> newNames = new ArrayList<>();
1549         for (GeneralName gname : names.names()) {
1550             GeneralNameInterface name = gname.getName();
1551             List<Object> nameEntry = new ArrayList<>(2);
1552             nameEntry.add(Integer.valueOf(name.getType()));
1553             switch (name.getType()) {
1554             case GeneralNameInterface.NAME_RFC822:
1555                 nameEntry.add(((RFC822Name) name).getName());
1556                 break;
1557             case GeneralNameInterface.NAME_DNS:
1558                 nameEntry.add(((DNSName) name).getName());
1559                 break;
1560             case GeneralNameInterface.NAME_DIRECTORY:
1561                 nameEntry.add(((X500Name) name).getRFC2253Name());
1562                 break;
1563             case GeneralNameInterface.NAME_URI:
1564                 nameEntry.add(((URIName) name).getName());
1565                 break;
1566             case GeneralNameInterface.NAME_IP:
1567                 try {
1568                     nameEntry.add(((IPAddressName) name).getName());
1569                 } catch (IOException ioe) {
1570                     // IPAddressName in cert is bogus
1571                     throw new RuntimeException("IPAddress cannot be parsed",
1572                         ioe);
1573                 }
1574                 break;
1575             case GeneralNameInterface.NAME_OID:
1576                 nameEntry.add(((OIDName) name).getOID().toString());
1577                 break;
1578             default:
1579                 // add DER encoded form
1580                 DerOutputStream derOut = new DerOutputStream();
1581                 try {
1582                     name.encode(derOut);
1583                 } catch (IOException ioe) {
1584                     // should not occur since name has already been decoded
1585                     // from cert (this would indicate a bug in our code)
1586                     throw new RuntimeException("name cannot be encoded", ioe);
1587                 }
1588                 nameEntry.add(derOut.toByteArray());
1589                 break;
1590             }
1591             newNames.add(Collections.unmodifiableList(nameEntry));
1592         }
1593         return Collections.unmodifiableCollection(newNames);
1594     }
1595 
1596     /**
1597      * Checks a Collection of altNames and clones any name entries of type
1598      * byte [].
1599      */ // only partially generified due to javac bug
1600     private static Collection<List<?>> cloneAltNames(Collection<List<?>> altNames) {
1601         boolean mustClone = false;
1602         for (List<?> nameEntry : altNames) {
1603             if (nameEntry.get(1) instanceof byte[]) {
1604                 // must clone names
1605                 mustClone = true;
1606             }
1607         }
1608         if (mustClone) {
1609             List<List<?>> namesCopy = new ArrayList<>();
1610             for (List<?> nameEntry : altNames) {
1611                 Object nameObject = nameEntry.get(1);
1612                 if (nameObject instanceof byte[]) {
1613                     List<Object> nameEntryCopy =
1614                                         new ArrayList<>(nameEntry);
1615                     nameEntryCopy.set(1, ((byte[])nameObject).clone());
1616                     namesCopy.add(Collections.unmodifiableList(nameEntryCopy));
1617                 } else {
1618                     namesCopy.add(nameEntry);
1619                 }
1620             }
1621             return Collections.unmodifiableCollection(namesCopy);
1622         } else {
1623             return altNames;
1624         }
1625     }
1626 
1627     /**
1628      * This method are the overridden implementation of
1629      * getSubjectAlternativeNames method in X509Certificate in the Sun
1630      * provider. It is better performance-wise since it returns cached
1631      * values.
1632      */
1633     public synchronized Collection<List<?>> getSubjectAlternativeNames()
1634         throws CertificateParsingException {
1635         // return cached value if we can
1636         if (readOnly && subjectAlternativeNames != null)  {
1637             return cloneAltNames(subjectAlternativeNames);
1638         }
1639         SubjectAlternativeNameExtension subjectAltNameExt =
1640             getSubjectAlternativeNameExtension();
1641         if (subjectAltNameExt == null) {
1642             return null;
1643         }
1644         GeneralNames names;
1645         try {
1646             names = subjectAltNameExt.get(
1647                     SubjectAlternativeNameExtension.SUBJECT_NAME);
1648         } catch (IOException ioe) {
1649             // should not occur
1650             return Collections.<List<?>>emptySet();
1651         }
1652         subjectAlternativeNames = makeAltNames(names);
1653         return subjectAlternativeNames;
1654     }
1655 
1656     /**
1657      * This static method is the default implementation of the
1658      * getSubjectAlternaitveNames method in X509Certificate. A
1659      * X509Certificate provider generally should overwrite this to
1660      * provide among other things caching for better performance.
1661      */
1662     public static Collection<List<?>> getSubjectAlternativeNames(X509Certificate cert)
1663         throws CertificateParsingException {
1664         try {
1665             byte[] ext = cert.getExtensionValue(SUBJECT_ALT_NAME_OID);
1666             if (ext == null) {
1667                 return null;
1668             }
1669             DerValue val = new DerValue(ext);
1670             byte[] data = val.getOctetString();
1671 
1672             SubjectAlternativeNameExtension subjectAltNameExt =
1673                 new SubjectAlternativeNameExtension(Boolean.FALSE,
1674                                                     data);
1675 
1676             GeneralNames names;
1677             try {
1678                 names = subjectAltNameExt.get(
1679                         SubjectAlternativeNameExtension.SUBJECT_NAME);
1680             }  catch (IOException ioe) {
1681                 // should not occur
1682                 return Collections.<List<?>>emptySet();
1683             }
1684             return makeAltNames(names);
1685         } catch (IOException ioe) {
1686             throw new CertificateParsingException(ioe);
1687         }
1688     }
1689 
1690     /**
1691      * This method are the overridden implementation of
1692      * getIssuerAlternativeNames method in X509Certificate in the Sun
1693      * provider. It is better performance-wise since it returns cached
1694      * values.
1695      */
1696     public synchronized Collection<List<?>> getIssuerAlternativeNames()
1697         throws CertificateParsingException {
1698         // return cached value if we can
1699         if (readOnly && issuerAlternativeNames != null) {
1700             return cloneAltNames(issuerAlternativeNames);
1701         }
1702         IssuerAlternativeNameExtension issuerAltNameExt =
1703             getIssuerAlternativeNameExtension();
1704         if (issuerAltNameExt == null) {
1705             return null;
1706         }
1707         GeneralNames names;
1708         try {
1709             names = issuerAltNameExt.get(
1710                     IssuerAlternativeNameExtension.ISSUER_NAME);
1711         } catch (IOException ioe) {
1712             // should not occur
1713             return Collections.<List<?>>emptySet();
1714         }
1715         issuerAlternativeNames = makeAltNames(names);
1716         return issuerAlternativeNames;
1717     }
1718 
1719     /**
1720      * This static method is the default implementation of the
1721      * getIssuerAlternaitveNames method in X509Certificate. A
1722      * X509Certificate provider generally should overwrite this to
1723      * provide among other things caching for better performance.
1724      */
1725     public static Collection<List<?>> getIssuerAlternativeNames(X509Certificate cert)
1726         throws CertificateParsingException {
1727         try {
1728             byte[] ext = cert.getExtensionValue(ISSUER_ALT_NAME_OID);
1729             if (ext == null) {
1730                 return null;
1731             }
1732 
1733             DerValue val = new DerValue(ext);
1734             byte[] data = val.getOctetString();
1735 
1736             IssuerAlternativeNameExtension issuerAltNameExt =
1737                 new IssuerAlternativeNameExtension(Boolean.FALSE,
1738                                                     data);
1739             GeneralNames names;
1740             try {
1741                 names = issuerAltNameExt.get(
1742                         IssuerAlternativeNameExtension.ISSUER_NAME);
1743             }  catch (IOException ioe) {
1744                 // should not occur
1745                 return Collections.<List<?>>emptySet();
1746             }
1747             return makeAltNames(names);
1748         } catch (IOException ioe) {
1749             throw new CertificateParsingException(ioe);
1750         }
1751     }
1752 
1753     public AuthorityInfoAccessExtension getAuthorityInfoAccessExtension() {
1754         return (AuthorityInfoAccessExtension)
1755             getExtension(PKIXExtensions.AuthInfoAccess_Id);
1756     }
1757 
1758     /************************************************************/
1759 
1760     /*
1761      * Cert is a SIGNED ASN.1 macro, a three elment sequence:
1762      *
1763      *  - Data to be signed (ToBeSigned) -- the "raw" cert
1764      *  - Signature algorithm (SigAlgId)
1765      *  - The signature bits
1766      *
1767      * This routine unmarshals the certificate, saving the signature
1768      * parts away for later verification.
1769      */
1770     private void parse(DerValue val)
1771     throws CertificateException, IOException {
1772         // check if can over write the certificate
1773         if (readOnly)
1774             throw new CertificateParsingException(
1775                       "cannot over-write existing certificate");
1776 
1777         if (val.data == null || val.tag != DerValue.tag_Sequence)
1778             throw new CertificateParsingException(
1779                       "invalid DER-encoded certificate data");
1780 
1781         signedCert = val.toByteArray();
1782         DerValue[] seq = new DerValue[3];
1783 
1784         seq[0] = val.data.getDerValue();
1785         seq[1] = val.data.getDerValue();
1786         seq[2] = val.data.getDerValue();
1787 
1788         if (val.data.available() != 0) {
1789             throw new CertificateParsingException("signed overrun, bytes = "
1790                                      + val.data.available());
1791         }
1792         if (seq[0].tag != DerValue.tag_Sequence) {
1793             throw new CertificateParsingException("signed fields invalid");
1794         }
1795 
1796         algId = AlgorithmId.parse(seq[1]);
1797         signature = seq[2].getBitString();
1798 
1799         if (seq[1].data.available() != 0) {
1800             throw new CertificateParsingException("algid field overrun");
1801         }
1802         if (seq[2].data.available() != 0)
1803             throw new CertificateParsingException("signed fields overrun");
1804 
1805         // The CertificateInfo
1806         info = new X509CertInfo(seq[0]);
1807 
1808         // the "inner" and "outer" signature algorithms must match
1809         AlgorithmId infoSigAlg = (AlgorithmId)info.get(
1810                                               CertificateAlgorithmId.NAME
1811                                               + DOT +
1812                                               CertificateAlgorithmId.ALGORITHM);
1813         if (! algId.equals(infoSigAlg))
1814             throw new CertificateException("Signature algorithm mismatch");
1815         readOnly = true;
1816     }
1817 
1818     /**
1819      * Extract the subject or issuer X500Principal from an X509Certificate.
1820      * Parses the encoded form of the cert to preserve the principal's
1821      * ASN.1 encoding.
1822      */
1823     private static X500Principal getX500Principal(X509Certificate cert,
1824             boolean getIssuer) throws Exception {
1825         byte[] encoded = cert.getEncoded();
1826         DerInputStream derIn = new DerInputStream(encoded);
1827         DerValue tbsCert = derIn.getSequence(3)[0];
1828         DerInputStream tbsIn = tbsCert.data;
1829         DerValue tmp;
1830         tmp = tbsIn.getDerValue();
1831         // skip version number if present
1832         if (tmp.isContextSpecific((byte)0)) {
1833           tmp = tbsIn.getDerValue();
1834         }
1835         // tmp always contains serial number now
1836         tmp = tbsIn.getDerValue();              // skip signature
1837         tmp = tbsIn.getDerValue();              // issuer
1838         if (getIssuer == false) {
1839             tmp = tbsIn.getDerValue();          // skip validity
1840             tmp = tbsIn.getDerValue();          // subject
1841         }
1842         byte[] principalBytes = tmp.toByteArray();
1843         return new X500Principal(principalBytes);
1844     }
1845 
1846     /**
1847      * Extract the subject X500Principal from an X509Certificate.
1848      * Called from java.security.cert.X509Certificate.getSubjectX500Principal().
1849      */
1850     public static X500Principal getSubjectX500Principal(X509Certificate cert) {
1851         try {
1852             return getX500Principal(cert, false);
1853         } catch (Exception e) {
1854             throw new RuntimeException("Could not parse subject", e);
1855         }
1856     }
1857 
1858     /**
1859      * Extract the issuer X500Principal from an X509Certificate.
1860      * Called from java.security.cert.X509Certificate.getIssuerX500Principal().
1861      */
1862     public static X500Principal getIssuerX500Principal(X509Certificate cert) {
1863         try {
1864             return getX500Principal(cert, true);
1865         } catch (Exception e) {
1866             throw new RuntimeException("Could not parse issuer", e);
1867         }
1868     }
1869 
1870     /**
1871      * Returned the encoding of the given certificate for internal use.
1872      * Callers must guarantee that they neither modify it nor expose it
1873      * to untrusted code. Uses getEncodedInternal() if the certificate
1874      * is instance of X509CertImpl, getEncoded() otherwise.
1875      */
1876     public static byte[] getEncodedInternal(Certificate cert)
1877             throws CertificateEncodingException {
1878         if (cert instanceof X509CertImpl) {
1879             return ((X509CertImpl)cert).getEncodedInternal();
1880         } else {
1881             return cert.getEncoded();
1882         }
1883     }
1884 
1885     /**
1886      * Utility method to convert an arbitrary instance of X509Certificate
1887      * to a X509CertImpl. Does a cast if possible, otherwise reparses
1888      * the encoding.
1889      */
1890     public static X509CertImpl toImpl(X509Certificate cert)
1891             throws CertificateException {
1892         if (cert instanceof X509CertImpl) {
1893             return (X509CertImpl)cert;
1894         } else {
1895             return X509Factory.intern(cert);
1896         }
1897     }
1898 
1899     /**
1900      * Utility method to test if a certificate is self-issued. This is
1901      * the case iff the subject and issuer X500Principals are equal.
1902      */
1903     public static boolean isSelfIssued(X509Certificate cert) {
1904         X500Principal subject = cert.getSubjectX500Principal();
1905         X500Principal issuer = cert.getIssuerX500Principal();
1906         return subject.equals(issuer);
1907     }
1908 
1909     /**
1910      * Utility method to test if a certificate is self-signed. This is
1911      * the case iff the subject and issuer X500Principals are equal
1912      * AND the certificate's subject public key can be used to verify
1913      * the certificate. In case of exception, returns false.
1914      */
1915     public static boolean isSelfSigned(X509Certificate cert,
1916         String sigProvider) {
1917         if (isSelfIssued(cert)) {
1918             try {
1919                 if (sigProvider == null) {
1920                     cert.verify(cert.getPublicKey());
1921                 } else {
1922                     cert.verify(cert.getPublicKey(), sigProvider);
1923                 }
1924                 return true;
1925             } catch (Exception e) {
1926                 // In case of exception, return false
1927             }
1928         }
1929         return false;
1930     }
1931 
1932     private ConcurrentHashMap<String,String> fingerprints =
1933             new ConcurrentHashMap<>(2);
1934 
1935     public String getFingerprint(String algorithm) {
1936         return fingerprints.computeIfAbsent(algorithm,
1937                 x -> getCertificateFingerPrint(x));
1938     }
1939 
1940     /**
1941      * Gets the requested finger print of the certificate. The result
1942      * only contains 0-9 and A-F. No small case, no colon.
1943      */
1944     private String getCertificateFingerPrint(String mdAlg) {
1945         String fingerPrint = "";
1946         try {
1947             byte[] encCertInfo = getEncoded();
1948             MessageDigest md = MessageDigest.getInstance(mdAlg);
1949             byte[] digest = md.digest(encCertInfo);
1950             StringBuffer buf = new StringBuffer();
1951             for (int i = 0; i < digest.length; i++) {
1952                 byte2hex(digest[i], buf);
1953             }
1954             fingerPrint = buf.toString();
1955         } catch (NoSuchAlgorithmException | CertificateEncodingException e) {
1956             // ignored
1957         }
1958         return fingerPrint;
1959     }
1960 
1961     /**
1962      * Converts a byte to hex digit and writes to the supplied buffer
1963      */
1964     private static void byte2hex(byte b, StringBuffer buf) {
1965         char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
1966                 '9', 'A', 'B', 'C', 'D', 'E', 'F' };
1967         int high = ((b & 0xf0) >> 4);
1968         int low = (b & 0x0f);
1969         buf.append(hexChars[high]);
1970         buf.append(hexChars[low]);
1971     }
1972 }