1 /*
   2  * Copyright (c) 1996, 2016, 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.security.util.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 char 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      * @return 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(Pem.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      * @param certInfo 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         HexDumpEncoder encoder = new HexDumpEncoder();
 803         return "[\n" + info + '\n' +
 804             "  Algorithm: [" + algId + "]\n" +
 805             "  Signature:\n" + encoder.encodeBuffer(signature) + "\n]";
 806     }
 807 
 808     // the strongly typed gets, as per java.security.cert.X509Certificate
 809 
 810     /**
 811      * Gets the publickey from this certificate.
 812      *
 813      * @return the publickey.
 814      */
 815     public PublicKey getPublicKey() {
 816         if (info == null)
 817             return null;
 818         try {
 819             PublicKey key = (PublicKey)info.get(CertificateX509Key.NAME
 820                                 + DOT + CertificateX509Key.KEY);
 821             return key;
 822         } catch (Exception e) {
 823             return null;
 824         }
 825     }
 826 
 827     /**
 828      * Gets the version number from the certificate.
 829      *
 830      * @return the version number, i.e. 1, 2 or 3.
 831      */
 832     public int getVersion() {
 833         if (info == null)
 834             return -1;
 835         try {
 836             int vers = ((Integer)info.get(CertificateVersion.NAME
 837                         + DOT + CertificateVersion.VERSION)).intValue();
 838             return vers+1;
 839         } catch (Exception e) {
 840             return -1;
 841         }
 842     }
 843 
 844     /**
 845      * Gets the serial number from the certificate.
 846      *
 847      * @return the serial number.
 848      */
 849     public BigInteger getSerialNumber() {
 850         SerialNumber ser = getSerialNumberObject();
 851 
 852         return ser != null ? ser.getNumber() : null;
 853     }
 854 
 855     /**
 856      * Gets the serial number from the certificate as
 857      * a SerialNumber object.
 858      *
 859      * @return the serial number.
 860      */
 861     public SerialNumber getSerialNumberObject() {
 862         if (info == null)
 863             return null;
 864         try {
 865             SerialNumber ser = (SerialNumber)info.get(
 866                               CertificateSerialNumber.NAME + DOT +
 867                               CertificateSerialNumber.NUMBER);
 868            return ser;
 869         } catch (Exception e) {
 870             return null;
 871         }
 872     }
 873 
 874 
 875     /**
 876      * Gets the subject distinguished name from the certificate.
 877      *
 878      * @return the subject name.
 879      */
 880     public Principal getSubjectDN() {
 881         if (info == null)
 882             return null;
 883         try {
 884             Principal subject = (Principal)info.get(X509CertInfo.SUBJECT + DOT +
 885                                                     X509CertInfo.DN_NAME);
 886             return subject;
 887         } catch (Exception e) {
 888             return null;
 889         }
 890     }
 891 
 892     /**
 893      * Get subject name as X500Principal. Overrides implementation in
 894      * X509Certificate with a slightly more efficient version that is
 895      * also aware of X509CertImpl mutability.
 896      */
 897     public X500Principal getSubjectX500Principal() {
 898         if (info == null) {
 899             return null;
 900         }
 901         try {
 902             X500Principal subject = (X500Principal)info.get(
 903                                             X509CertInfo.SUBJECT + DOT +
 904                                             "x500principal");
 905             return subject;
 906         } catch (Exception e) {
 907             return null;
 908         }
 909     }
 910 
 911     /**
 912      * Gets the issuer distinguished name from the certificate.
 913      *
 914      * @return the issuer name.
 915      */
 916     public Principal getIssuerDN() {
 917         if (info == null)
 918             return null;
 919         try {
 920             Principal issuer = (Principal)info.get(X509CertInfo.ISSUER + DOT +
 921                                                    X509CertInfo.DN_NAME);
 922             return issuer;
 923         } catch (Exception e) {
 924             return null;
 925         }
 926     }
 927 
 928     /**
 929      * Get issuer name as X500Principal. Overrides implementation in
 930      * X509Certificate with a slightly more efficient version that is
 931      * also aware of X509CertImpl mutability.
 932      */
 933     public X500Principal getIssuerX500Principal() {
 934         if (info == null) {
 935             return null;
 936         }
 937         try {
 938             X500Principal issuer = (X500Principal)info.get(
 939                                             X509CertInfo.ISSUER + DOT +
 940                                             "x500principal");
 941             return issuer;
 942         } catch (Exception e) {
 943             return null;
 944         }
 945     }
 946 
 947     /**
 948      * Gets the notBefore date from the validity period of the certificate.
 949      *
 950      * @return the start date of the validity period.
 951      */
 952     public Date getNotBefore() {
 953         if (info == null)
 954             return null;
 955         try {
 956             Date d = (Date) info.get(CertificateValidity.NAME + DOT +
 957                                         CertificateValidity.NOT_BEFORE);
 958             return d;
 959         } catch (Exception e) {
 960             return null;
 961         }
 962     }
 963 
 964     /**
 965      * Gets the notAfter date from the validity period of the certificate.
 966      *
 967      * @return the end date of the validity period.
 968      */
 969     public Date getNotAfter() {
 970         if (info == null)
 971             return null;
 972         try {
 973             Date d = (Date) info.get(CertificateValidity.NAME + DOT +
 974                                      CertificateValidity.NOT_AFTER);
 975             return d;
 976         } catch (Exception e) {
 977             return null;
 978         }
 979     }
 980 
 981     /**
 982      * Gets the DER encoded certificate informations, the
 983      * <code>tbsCertificate</code> from this certificate.
 984      * This can be used to verify the signature independently.
 985      *
 986      * @return the DER encoded certificate information.
 987      * @exception CertificateEncodingException if an encoding error occurs.
 988      */
 989     public byte[] getTBSCertificate() throws CertificateEncodingException {
 990         if (info != null) {
 991             return info.getEncodedInfo();
 992         } else
 993             throw new CertificateEncodingException("Uninitialized certificate");
 994     }
 995 
 996     /**
 997      * Gets the raw Signature bits from the certificate.
 998      *
 999      * @return the signature.
1000      */
1001     public byte[] getSignature() {
1002         if (signature == null)
1003             return null;
1004         return signature.clone();
1005     }
1006 
1007     /**
1008      * Gets the signature algorithm name for the certificate
1009      * signature algorithm.
1010      * For example, the string "SHA-1/DSA" or "DSS".
1011      *
1012      * @return the signature algorithm name.
1013      */
1014     public String getSigAlgName() {
1015         if (algId == null)
1016             return null;
1017         return (algId.getName());
1018     }
1019 
1020     /**
1021      * Gets the signature algorithm OID string from the certificate.
1022      * For example, the string "1.2.840.10040.4.3"
1023      *
1024      * @return the signature algorithm oid string.
1025      */
1026     public String getSigAlgOID() {
1027         if (algId == null)
1028             return null;
1029         ObjectIdentifier oid = algId.getOID();
1030         return (oid.toString());
1031     }
1032 
1033     /**
1034      * Gets the DER encoded signature algorithm parameters from this
1035      * certificate's signature algorithm.
1036      *
1037      * @return the DER encoded signature algorithm parameters, or
1038      *         null if no parameters are present.
1039      */
1040     public byte[] getSigAlgParams() {
1041         if (algId == null)
1042             return null;
1043         try {
1044             return algId.getEncodedParams();
1045         } catch (IOException e) {
1046             return null;
1047         }
1048     }
1049 
1050     /**
1051      * Gets the Issuer Unique Identity from the certificate.
1052      *
1053      * @return the Issuer Unique Identity.
1054      */
1055     public boolean[] getIssuerUniqueID() {
1056         if (info == null)
1057             return null;
1058         try {
1059             UniqueIdentity id = (UniqueIdentity)info.get(
1060                                  X509CertInfo.ISSUER_ID);
1061             if (id == null)
1062                 return null;
1063             else
1064                 return (id.getId());
1065         } catch (Exception e) {
1066             return null;
1067         }
1068     }
1069 
1070     /**
1071      * Gets the Subject Unique Identity from the certificate.
1072      *
1073      * @return the Subject Unique Identity.
1074      */
1075     public boolean[] getSubjectUniqueID() {
1076         if (info == null)
1077             return null;
1078         try {
1079             UniqueIdentity id = (UniqueIdentity)info.get(
1080                                  X509CertInfo.SUBJECT_ID);
1081             if (id == null)
1082                 return null;
1083             else
1084                 return (id.getId());
1085         } catch (Exception e) {
1086             return null;
1087         }
1088     }
1089 
1090     public KeyIdentifier getAuthKeyId() {
1091         AuthorityKeyIdentifierExtension aki
1092             = getAuthorityKeyIdentifierExtension();
1093         if (aki != null) {
1094             try {
1095                 return (KeyIdentifier)aki.get(
1096                     AuthorityKeyIdentifierExtension.KEY_ID);
1097             } catch (IOException ioe) {} // not possible
1098         }
1099         return null;
1100     }
1101 
1102     /**
1103      * Returns the subject's key identifier, or null
1104      */
1105     public KeyIdentifier getSubjectKeyId() {
1106         SubjectKeyIdentifierExtension ski = getSubjectKeyIdentifierExtension();
1107         if (ski != null) {
1108             try {
1109                 return ski.get(SubjectKeyIdentifierExtension.KEY_ID);
1110             } catch (IOException ioe) {} // not possible
1111         }
1112         return null;
1113     }
1114 
1115     /**
1116      * Get AuthorityKeyIdentifier extension
1117      * @return AuthorityKeyIdentifier object or null (if no such object
1118      * in certificate)
1119      */
1120     public AuthorityKeyIdentifierExtension getAuthorityKeyIdentifierExtension()
1121     {
1122         return (AuthorityKeyIdentifierExtension)
1123             getExtension(PKIXExtensions.AuthorityKey_Id);
1124     }
1125 
1126     /**
1127      * Get BasicConstraints extension
1128      * @return BasicConstraints object or null (if no such object in
1129      * certificate)
1130      */
1131     public BasicConstraintsExtension getBasicConstraintsExtension() {
1132         return (BasicConstraintsExtension)
1133             getExtension(PKIXExtensions.BasicConstraints_Id);
1134     }
1135 
1136     /**
1137      * Get CertificatePoliciesExtension
1138      * @return CertificatePoliciesExtension or null (if no such object in
1139      * certificate)
1140      */
1141     public CertificatePoliciesExtension getCertificatePoliciesExtension() {
1142         return (CertificatePoliciesExtension)
1143             getExtension(PKIXExtensions.CertificatePolicies_Id);
1144     }
1145 
1146     /**
1147      * Get ExtendedKeyUsage extension
1148      * @return ExtendedKeyUsage extension object or null (if no such object
1149      * in certificate)
1150      */
1151     public ExtendedKeyUsageExtension getExtendedKeyUsageExtension() {
1152         return (ExtendedKeyUsageExtension)
1153             getExtension(PKIXExtensions.ExtendedKeyUsage_Id);
1154     }
1155 
1156     /**
1157      * Get IssuerAlternativeName extension
1158      * @return IssuerAlternativeName object or null (if no such object in
1159      * certificate)
1160      */
1161     public IssuerAlternativeNameExtension getIssuerAlternativeNameExtension() {
1162         return (IssuerAlternativeNameExtension)
1163             getExtension(PKIXExtensions.IssuerAlternativeName_Id);
1164     }
1165 
1166     /**
1167      * Get NameConstraints extension
1168      * @return NameConstraints object or null (if no such object in certificate)
1169      */
1170     public NameConstraintsExtension getNameConstraintsExtension() {
1171         return (NameConstraintsExtension)
1172             getExtension(PKIXExtensions.NameConstraints_Id);
1173     }
1174 
1175     /**
1176      * Get PolicyConstraints extension
1177      * @return PolicyConstraints object or null (if no such object in
1178      * certificate)
1179      */
1180     public PolicyConstraintsExtension getPolicyConstraintsExtension() {
1181         return (PolicyConstraintsExtension)
1182             getExtension(PKIXExtensions.PolicyConstraints_Id);
1183     }
1184 
1185     /**
1186      * Get PolicyMappingsExtension extension
1187      * @return PolicyMappingsExtension object or null (if no such object
1188      * in certificate)
1189      */
1190     public PolicyMappingsExtension getPolicyMappingsExtension() {
1191         return (PolicyMappingsExtension)
1192             getExtension(PKIXExtensions.PolicyMappings_Id);
1193     }
1194 
1195     /**
1196      * Get PrivateKeyUsage extension
1197      * @return PrivateKeyUsage object or null (if no such object in certificate)
1198      */
1199     public PrivateKeyUsageExtension getPrivateKeyUsageExtension() {
1200         return (PrivateKeyUsageExtension)
1201             getExtension(PKIXExtensions.PrivateKeyUsage_Id);
1202     }
1203 
1204     /**
1205      * Get SubjectAlternativeName extension
1206      * @return SubjectAlternativeName object or null (if no such object in
1207      * certificate)
1208      */
1209     public SubjectAlternativeNameExtension getSubjectAlternativeNameExtension()
1210     {
1211         return (SubjectAlternativeNameExtension)
1212             getExtension(PKIXExtensions.SubjectAlternativeName_Id);
1213     }
1214 
1215     /**
1216      * Get SubjectKeyIdentifier extension
1217      * @return SubjectKeyIdentifier object or null (if no such object in
1218      * certificate)
1219      */
1220     public SubjectKeyIdentifierExtension getSubjectKeyIdentifierExtension() {
1221         return (SubjectKeyIdentifierExtension)
1222             getExtension(PKIXExtensions.SubjectKey_Id);
1223     }
1224 
1225     /**
1226      * Get CRLDistributionPoints extension
1227      * @return CRLDistributionPoints object or null (if no such object in
1228      * certificate)
1229      */
1230     public CRLDistributionPointsExtension getCRLDistributionPointsExtension() {
1231         return (CRLDistributionPointsExtension)
1232             getExtension(PKIXExtensions.CRLDistributionPoints_Id);
1233     }
1234 
1235     /**
1236      * Return true if a critical extension is found that is
1237      * not supported, otherwise return false.
1238      */
1239     public boolean hasUnsupportedCriticalExtension() {
1240         if (info == null)
1241             return false;
1242         try {
1243             CertificateExtensions exts = (CertificateExtensions)info.get(
1244                                          CertificateExtensions.NAME);
1245             if (exts == null)
1246                 return false;
1247             return exts.hasUnsupportedCriticalExtension();
1248         } catch (Exception e) {
1249             return false;
1250         }
1251     }
1252 
1253     /**
1254      * Gets a Set of the extension(s) marked CRITICAL in the
1255      * certificate. In the returned set, each extension is
1256      * represented by its OID string.
1257      *
1258      * @return a set of the extension oid strings in the
1259      * certificate that are marked critical.
1260      */
1261     public Set<String> getCriticalExtensionOIDs() {
1262         if (info == null) {
1263             return null;
1264         }
1265         try {
1266             CertificateExtensions exts = (CertificateExtensions)info.get(
1267                                          CertificateExtensions.NAME);
1268             if (exts == null) {
1269                 return null;
1270             }
1271             Set<String> extSet = new TreeSet<>();
1272             for (Extension ex : exts.getAllExtensions()) {
1273                 if (ex.isCritical()) {
1274                     extSet.add(ex.getExtensionId().toString());
1275                 }
1276             }
1277             return extSet;
1278         } catch (Exception e) {
1279             return null;
1280         }
1281     }
1282 
1283     /**
1284      * Gets a Set of the extension(s) marked NON-CRITICAL in the
1285      * certificate. In the returned set, each extension is
1286      * represented by its OID string.
1287      *
1288      * @return a set of the extension oid strings in the
1289      * certificate that are NOT marked critical.
1290      */
1291     public Set<String> getNonCriticalExtensionOIDs() {
1292         if (info == null) {
1293             return null;
1294         }
1295         try {
1296             CertificateExtensions exts = (CertificateExtensions)info.get(
1297                                          CertificateExtensions.NAME);
1298             if (exts == null) {
1299                 return null;
1300             }
1301             Set<String> extSet = new TreeSet<>();
1302             for (Extension ex : exts.getAllExtensions()) {
1303                 if (!ex.isCritical()) {
1304                     extSet.add(ex.getExtensionId().toString());
1305                 }
1306             }
1307             extSet.addAll(exts.getUnparseableExtensions().keySet());
1308             return extSet;
1309         } catch (Exception e) {
1310             return null;
1311         }
1312     }
1313 
1314     /**
1315      * Gets the extension identified by the given ObjectIdentifier
1316      *
1317      * @param oid the Object Identifier value for the extension.
1318      * @return Extension or null if certificate does not contain this
1319      *         extension
1320      */
1321     public Extension getExtension(ObjectIdentifier oid) {
1322         if (info == null) {
1323             return null;
1324         }
1325         try {
1326             CertificateExtensions extensions;
1327             try {
1328                 extensions = (CertificateExtensions)info.get(CertificateExtensions.NAME);
1329             } catch (CertificateException ce) {
1330                 return null;
1331             }
1332             if (extensions == null) {
1333                 return null;
1334             } else {
1335                 Extension ex = extensions.getExtension(oid.toString());
1336                 if (ex != null) {
1337                     return ex;
1338                 }
1339                 for (Extension ex2: extensions.getAllExtensions()) {
1340                     if (ex2.getExtensionId().equals(oid)) {
1341                         //XXXX May want to consider cloning this
1342                         return ex2;
1343                     }
1344                 }
1345                 /* no such extension in this certificate */
1346                 return null;
1347             }
1348         } catch (IOException ioe) {
1349             return null;
1350         }
1351     }
1352 
1353     public Extension getUnparseableExtension(ObjectIdentifier oid) {
1354         if (info == null) {
1355             return null;
1356         }
1357         try {
1358             CertificateExtensions extensions;
1359             try {
1360                 extensions = (CertificateExtensions)info.get(CertificateExtensions.NAME);
1361             } catch (CertificateException ce) {
1362                 return null;
1363             }
1364             if (extensions == null) {
1365                 return null;
1366             } else {
1367                 return extensions.getUnparseableExtensions().get(oid.toString());
1368             }
1369         } catch (IOException ioe) {
1370             return null;
1371         }
1372     }
1373 
1374     /**
1375      * Gets the DER encoded extension identified by the given
1376      * oid String.
1377      *
1378      * @param oid the Object Identifier value for the extension.
1379      */
1380     public byte[] getExtensionValue(String oid) {
1381         try {
1382             ObjectIdentifier findOID = new ObjectIdentifier(oid);
1383             String extAlias = OIDMap.getName(findOID);
1384             Extension certExt = null;
1385             CertificateExtensions exts = (CertificateExtensions)info.get(
1386                                      CertificateExtensions.NAME);
1387 
1388             if (extAlias == null) { // may be unknown
1389                 // get the extensions, search thru' for this oid
1390                 if (exts == null) {
1391                     return null;
1392                 }
1393 
1394                 for (Extension ex : exts.getAllExtensions()) {
1395                     ObjectIdentifier inCertOID = ex.getExtensionId();
1396                     if (inCertOID.equals(findOID)) {
1397                         certExt = ex;
1398                         break;
1399                     }
1400                 }
1401             } else { // there's sub-class that can handle this extension
1402                 try {
1403                     certExt = (Extension)this.get(extAlias);
1404                 } catch (CertificateException e) {
1405                     // get() throws an Exception instead of returning null, ignore
1406                 }
1407             }
1408             if (certExt == null) {
1409                 if (exts != null) {
1410                     certExt = exts.getUnparseableExtensions().get(oid);
1411                 }
1412                 if (certExt == null) {
1413                     return null;
1414                 }
1415             }
1416             byte[] extData = certExt.getExtensionValue();
1417             if (extData == null) {
1418                 return null;
1419             }
1420             DerOutputStream out = new DerOutputStream();
1421             out.putOctetString(extData);
1422             return out.toByteArray();
1423         } catch (Exception e) {
1424             return null;
1425         }
1426     }
1427 
1428     /**
1429      * Get a boolean array representing the bits of the KeyUsage extension,
1430      * (oid = 2.5.29.15).
1431      * @return the bit values of this extension as an array of booleans.
1432      */
1433     public boolean[] getKeyUsage() {
1434         try {
1435             String extAlias = OIDMap.getName(PKIXExtensions.KeyUsage_Id);
1436             if (extAlias == null)
1437                 return null;
1438 
1439             KeyUsageExtension certExt = (KeyUsageExtension)this.get(extAlias);
1440             if (certExt == null)
1441                 return null;
1442 
1443             boolean[] ret = certExt.getBits();
1444             if (ret.length < NUM_STANDARD_KEY_USAGE) {
1445                 boolean[] usageBits = new boolean[NUM_STANDARD_KEY_USAGE];
1446                 System.arraycopy(ret, 0, usageBits, 0, ret.length);
1447                 ret = usageBits;
1448             }
1449             return ret;
1450         } catch (Exception e) {
1451             return null;
1452         }
1453     }
1454 
1455     /**
1456      * This method are the overridden implementation of
1457      * getExtendedKeyUsage method in X509Certificate in the Sun
1458      * provider. It is better performance-wise since it returns cached
1459      * values.
1460      */
1461     public synchronized List<String> getExtendedKeyUsage()
1462         throws CertificateParsingException {
1463         if (readOnly && extKeyUsage != null) {
1464             return extKeyUsage;
1465         } else {
1466             ExtendedKeyUsageExtension ext = getExtendedKeyUsageExtension();
1467             if (ext == null) {
1468                 return null;
1469             }
1470             extKeyUsage =
1471                 Collections.unmodifiableList(ext.getExtendedKeyUsage());
1472             return extKeyUsage;
1473         }
1474     }
1475 
1476     /**
1477      * This static method is the default implementation of the
1478      * getExtendedKeyUsage method in X509Certificate. A
1479      * X509Certificate provider generally should overwrite this to
1480      * provide among other things caching for better performance.
1481      */
1482     public static List<String> getExtendedKeyUsage(X509Certificate cert)
1483         throws CertificateParsingException {
1484         try {
1485             byte[] ext = cert.getExtensionValue(EXTENDED_KEY_USAGE_OID);
1486             if (ext == null)
1487                 return null;
1488             DerValue val = new DerValue(ext);
1489             byte[] data = val.getOctetString();
1490 
1491             ExtendedKeyUsageExtension ekuExt =
1492                 new ExtendedKeyUsageExtension(Boolean.FALSE, data);
1493             return Collections.unmodifiableList(ekuExt.getExtendedKeyUsage());
1494         } catch (IOException ioe) {
1495             throw new CertificateParsingException(ioe);
1496         }
1497     }
1498 
1499     /**
1500      * Get the certificate constraints path length from the
1501      * the critical BasicConstraints extension, (oid = 2.5.29.19).
1502      * @return the length of the constraint.
1503      */
1504     public int getBasicConstraints() {
1505         try {
1506             String extAlias = OIDMap.getName(PKIXExtensions.BasicConstraints_Id);
1507             if (extAlias == null)
1508                 return -1;
1509             BasicConstraintsExtension certExt =
1510                         (BasicConstraintsExtension)this.get(extAlias);
1511             if (certExt == null)
1512                 return -1;
1513 
1514             if (((Boolean)certExt.get(BasicConstraintsExtension.IS_CA)
1515                  ).booleanValue() == true)
1516                 return ((Integer)certExt.get(
1517                         BasicConstraintsExtension.PATH_LEN)).intValue();
1518             else
1519                 return -1;
1520         } catch (Exception e) {
1521             return -1;
1522         }
1523     }
1524 
1525     /**
1526      * Converts a GeneralNames structure into an immutable Collection of
1527      * alternative names (subject or issuer) in the form required by
1528      * {@link #getSubjectAlternativeNames} or
1529      * {@link #getIssuerAlternativeNames}.
1530      *
1531      * @param names the GeneralNames to be converted
1532      * @return an immutable Collection of alternative names
1533      */
1534     private static Collection<List<?>> makeAltNames(GeneralNames names) {
1535         if (names.isEmpty()) {
1536             return Collections.<List<?>>emptySet();
1537         }
1538         List<List<?>> newNames = new ArrayList<>();
1539         for (GeneralName gname : names.names()) {
1540             GeneralNameInterface name = gname.getName();
1541             List<Object> nameEntry = new ArrayList<>(2);
1542             nameEntry.add(Integer.valueOf(name.getType()));
1543             switch (name.getType()) {
1544             case GeneralNameInterface.NAME_RFC822:
1545                 nameEntry.add(((RFC822Name) name).getName());
1546                 break;
1547             case GeneralNameInterface.NAME_DNS:
1548                 nameEntry.add(((DNSName) name).getName());
1549                 break;
1550             case GeneralNameInterface.NAME_DIRECTORY:
1551                 nameEntry.add(((X500Name) name).getRFC2253Name());
1552                 break;
1553             case GeneralNameInterface.NAME_URI:
1554                 nameEntry.add(((URIName) name).getName());
1555                 break;
1556             case GeneralNameInterface.NAME_IP:
1557                 try {
1558                     nameEntry.add(((IPAddressName) name).getName());
1559                 } catch (IOException ioe) {
1560                     // IPAddressName in cert is bogus
1561                     throw new RuntimeException("IPAddress cannot be parsed",
1562                         ioe);
1563                 }
1564                 break;
1565             case GeneralNameInterface.NAME_OID:
1566                 nameEntry.add(((OIDName) name).getOID().toString());
1567                 break;
1568             default:
1569                 // add DER encoded form
1570                 DerOutputStream derOut = new DerOutputStream();
1571                 try {
1572                     name.encode(derOut);
1573                 } catch (IOException ioe) {
1574                     // should not occur since name has already been decoded
1575                     // from cert (this would indicate a bug in our code)
1576                     throw new RuntimeException("name cannot be encoded", ioe);
1577                 }
1578                 nameEntry.add(derOut.toByteArray());
1579                 break;
1580             }
1581             newNames.add(Collections.unmodifiableList(nameEntry));
1582         }
1583         return Collections.unmodifiableCollection(newNames);
1584     }
1585 
1586     /**
1587      * Checks a Collection of altNames and clones any name entries of type
1588      * byte [].
1589      */ // only partially generified due to javac bug
1590     private static Collection<List<?>> cloneAltNames(Collection<List<?>> altNames) {
1591         boolean mustClone = false;
1592         for (List<?> nameEntry : altNames) {
1593             if (nameEntry.get(1) instanceof byte[]) {
1594                 // must clone names
1595                 mustClone = true;
1596             }
1597         }
1598         if (mustClone) {
1599             List<List<?>> namesCopy = new ArrayList<>();
1600             for (List<?> nameEntry : altNames) {
1601                 Object nameObject = nameEntry.get(1);
1602                 if (nameObject instanceof byte[]) {
1603                     List<Object> nameEntryCopy =
1604                                         new ArrayList<>(nameEntry);
1605                     nameEntryCopy.set(1, ((byte[])nameObject).clone());
1606                     namesCopy.add(Collections.unmodifiableList(nameEntryCopy));
1607                 } else {
1608                     namesCopy.add(nameEntry);
1609                 }
1610             }
1611             return Collections.unmodifiableCollection(namesCopy);
1612         } else {
1613             return altNames;
1614         }
1615     }
1616 
1617     /**
1618      * This method are the overridden implementation of
1619      * getSubjectAlternativeNames method in X509Certificate in the Sun
1620      * provider. It is better performance-wise since it returns cached
1621      * values.
1622      */
1623     public synchronized Collection<List<?>> getSubjectAlternativeNames()
1624         throws CertificateParsingException {
1625         // return cached value if we can
1626         if (readOnly && subjectAlternativeNames != null)  {
1627             return cloneAltNames(subjectAlternativeNames);
1628         }
1629         SubjectAlternativeNameExtension subjectAltNameExt =
1630             getSubjectAlternativeNameExtension();
1631         if (subjectAltNameExt == null) {
1632             return null;
1633         }
1634         GeneralNames names;
1635         try {
1636             names = subjectAltNameExt.get(
1637                     SubjectAlternativeNameExtension.SUBJECT_NAME);
1638         } catch (IOException ioe) {
1639             // should not occur
1640             return Collections.<List<?>>emptySet();
1641         }
1642         subjectAlternativeNames = makeAltNames(names);
1643         return subjectAlternativeNames;
1644     }
1645 
1646     /**
1647      * This static method is the default implementation of the
1648      * getSubjectAlternaitveNames method in X509Certificate. A
1649      * X509Certificate provider generally should overwrite this to
1650      * provide among other things caching for better performance.
1651      */
1652     public static Collection<List<?>> getSubjectAlternativeNames(X509Certificate cert)
1653         throws CertificateParsingException {
1654         try {
1655             byte[] ext = cert.getExtensionValue(SUBJECT_ALT_NAME_OID);
1656             if (ext == null) {
1657                 return null;
1658             }
1659             DerValue val = new DerValue(ext);
1660             byte[] data = val.getOctetString();
1661 
1662             SubjectAlternativeNameExtension subjectAltNameExt =
1663                 new SubjectAlternativeNameExtension(Boolean.FALSE,
1664                                                     data);
1665 
1666             GeneralNames names;
1667             try {
1668                 names = subjectAltNameExt.get(
1669                         SubjectAlternativeNameExtension.SUBJECT_NAME);
1670             }  catch (IOException ioe) {
1671                 // should not occur
1672                 return Collections.<List<?>>emptySet();
1673             }
1674             return makeAltNames(names);
1675         } catch (IOException ioe) {
1676             throw new CertificateParsingException(ioe);
1677         }
1678     }
1679 
1680     /**
1681      * This method are the overridden implementation of
1682      * getIssuerAlternativeNames method in X509Certificate in the Sun
1683      * provider. It is better performance-wise since it returns cached
1684      * values.
1685      */
1686     public synchronized Collection<List<?>> getIssuerAlternativeNames()
1687         throws CertificateParsingException {
1688         // return cached value if we can
1689         if (readOnly && issuerAlternativeNames != null) {
1690             return cloneAltNames(issuerAlternativeNames);
1691         }
1692         IssuerAlternativeNameExtension issuerAltNameExt =
1693             getIssuerAlternativeNameExtension();
1694         if (issuerAltNameExt == null) {
1695             return null;
1696         }
1697         GeneralNames names;
1698         try {
1699             names = issuerAltNameExt.get(
1700                     IssuerAlternativeNameExtension.ISSUER_NAME);
1701         } catch (IOException ioe) {
1702             // should not occur
1703             return Collections.<List<?>>emptySet();
1704         }
1705         issuerAlternativeNames = makeAltNames(names);
1706         return issuerAlternativeNames;
1707     }
1708 
1709     /**
1710      * This static method is the default implementation of the
1711      * getIssuerAlternaitveNames method in X509Certificate. A
1712      * X509Certificate provider generally should overwrite this to
1713      * provide among other things caching for better performance.
1714      */
1715     public static Collection<List<?>> getIssuerAlternativeNames(X509Certificate cert)
1716         throws CertificateParsingException {
1717         try {
1718             byte[] ext = cert.getExtensionValue(ISSUER_ALT_NAME_OID);
1719             if (ext == null) {
1720                 return null;
1721             }
1722 
1723             DerValue val = new DerValue(ext);
1724             byte[] data = val.getOctetString();
1725 
1726             IssuerAlternativeNameExtension issuerAltNameExt =
1727                 new IssuerAlternativeNameExtension(Boolean.FALSE,
1728                                                     data);
1729             GeneralNames names;
1730             try {
1731                 names = issuerAltNameExt.get(
1732                         IssuerAlternativeNameExtension.ISSUER_NAME);
1733             }  catch (IOException ioe) {
1734                 // should not occur
1735                 return Collections.<List<?>>emptySet();
1736             }
1737             return makeAltNames(names);
1738         } catch (IOException ioe) {
1739             throw new CertificateParsingException(ioe);
1740         }
1741     }
1742 
1743     public AuthorityInfoAccessExtension getAuthorityInfoAccessExtension() {
1744         return (AuthorityInfoAccessExtension)
1745             getExtension(PKIXExtensions.AuthInfoAccess_Id);
1746     }
1747 
1748     /************************************************************/
1749 
1750     /*
1751      * Cert is a SIGNED ASN.1 macro, a three elment sequence:
1752      *
1753      *  - Data to be signed (ToBeSigned) -- the "raw" cert
1754      *  - Signature algorithm (SigAlgId)
1755      *  - The signature bits
1756      *
1757      * This routine unmarshals the certificate, saving the signature
1758      * parts away for later verification.
1759      */
1760     private void parse(DerValue val)
1761     throws CertificateException, IOException {
1762         // check if can over write the certificate
1763         if (readOnly)
1764             throw new CertificateParsingException(
1765                       "cannot over-write existing certificate");
1766 
1767         if (val.data == null || val.tag != DerValue.tag_Sequence)
1768             throw new CertificateParsingException(
1769                       "invalid DER-encoded certificate data");
1770 
1771         signedCert = val.toByteArray();
1772         DerValue[] seq = new DerValue[3];
1773 
1774         seq[0] = val.data.getDerValue();
1775         seq[1] = val.data.getDerValue();
1776         seq[2] = val.data.getDerValue();
1777 
1778         if (val.data.available() != 0) {
1779             throw new CertificateParsingException("signed overrun, bytes = "
1780                                      + val.data.available());
1781         }
1782         if (seq[0].tag != DerValue.tag_Sequence) {
1783             throw new CertificateParsingException("signed fields invalid");
1784         }
1785 
1786         algId = AlgorithmId.parse(seq[1]);
1787         signature = seq[2].getBitString();
1788 
1789         if (seq[1].data.available() != 0) {
1790             throw new CertificateParsingException("algid field overrun");
1791         }
1792         if (seq[2].data.available() != 0)
1793             throw new CertificateParsingException("signed fields overrun");
1794 
1795         // The CertificateInfo
1796         info = new X509CertInfo(seq[0]);
1797 
1798         // the "inner" and "outer" signature algorithms must match
1799         AlgorithmId infoSigAlg = (AlgorithmId)info.get(
1800                                               CertificateAlgorithmId.NAME
1801                                               + DOT +
1802                                               CertificateAlgorithmId.ALGORITHM);
1803         if (! algId.equals(infoSigAlg))
1804             throw new CertificateException("Signature algorithm mismatch");
1805         readOnly = true;
1806     }
1807 
1808     /**
1809      * Extract the subject or issuer X500Principal from an X509Certificate.
1810      * Parses the encoded form of the cert to preserve the principal's
1811      * ASN.1 encoding.
1812      */
1813     private static X500Principal getX500Principal(X509Certificate cert,
1814             boolean getIssuer) throws Exception {
1815         byte[] encoded = cert.getEncoded();
1816         DerInputStream derIn = new DerInputStream(encoded);
1817         DerValue tbsCert = derIn.getSequence(3)[0];
1818         DerInputStream tbsIn = tbsCert.data;
1819         DerValue tmp;
1820         tmp = tbsIn.getDerValue();
1821         // skip version number if present
1822         if (tmp.isContextSpecific((byte)0)) {
1823           tmp = tbsIn.getDerValue();
1824         }
1825         // tmp always contains serial number now
1826         tmp = tbsIn.getDerValue();              // skip signature
1827         tmp = tbsIn.getDerValue();              // issuer
1828         if (getIssuer == false) {
1829             tmp = tbsIn.getDerValue();          // skip validity
1830             tmp = tbsIn.getDerValue();          // subject
1831         }
1832         byte[] principalBytes = tmp.toByteArray();
1833         return new X500Principal(principalBytes);
1834     }
1835 
1836     /**
1837      * Extract the subject X500Principal from an X509Certificate.
1838      * Called from java.security.cert.X509Certificate.getSubjectX500Principal().
1839      */
1840     public static X500Principal getSubjectX500Principal(X509Certificate cert) {
1841         try {
1842             return getX500Principal(cert, false);
1843         } catch (Exception e) {
1844             throw new RuntimeException("Could not parse subject", e);
1845         }
1846     }
1847 
1848     /**
1849      * Extract the issuer X500Principal from an X509Certificate.
1850      * Called from java.security.cert.X509Certificate.getIssuerX500Principal().
1851      */
1852     public static X500Principal getIssuerX500Principal(X509Certificate cert) {
1853         try {
1854             return getX500Principal(cert, true);
1855         } catch (Exception e) {
1856             throw new RuntimeException("Could not parse issuer", e);
1857         }
1858     }
1859 
1860     /**
1861      * Returned the encoding of the given certificate for internal use.
1862      * Callers must guarantee that they neither modify it nor expose it
1863      * to untrusted code. Uses getEncodedInternal() if the certificate
1864      * is instance of X509CertImpl, getEncoded() otherwise.
1865      */
1866     public static byte[] getEncodedInternal(Certificate cert)
1867             throws CertificateEncodingException {
1868         if (cert instanceof X509CertImpl) {
1869             return ((X509CertImpl)cert).getEncodedInternal();
1870         } else {
1871             return cert.getEncoded();
1872         }
1873     }
1874 
1875     /**
1876      * Utility method to convert an arbitrary instance of X509Certificate
1877      * to a X509CertImpl. Does a cast if possible, otherwise reparses
1878      * the encoding.
1879      */
1880     public static X509CertImpl toImpl(X509Certificate cert)
1881             throws CertificateException {
1882         if (cert instanceof X509CertImpl) {
1883             return (X509CertImpl)cert;
1884         } else {
1885             return X509Factory.intern(cert);
1886         }
1887     }
1888 
1889     /**
1890      * Utility method to test if a certificate is self-issued. This is
1891      * the case iff the subject and issuer X500Principals are equal.
1892      */
1893     public static boolean isSelfIssued(X509Certificate cert) {
1894         X500Principal subject = cert.getSubjectX500Principal();
1895         X500Principal issuer = cert.getIssuerX500Principal();
1896         return subject.equals(issuer);
1897     }
1898 
1899     /**
1900      * Utility method to test if a certificate is self-signed. This is
1901      * the case iff the subject and issuer X500Principals are equal
1902      * AND the certificate's subject public key can be used to verify
1903      * the certificate. In case of exception, returns false.
1904      */
1905     public static boolean isSelfSigned(X509Certificate cert,
1906         String sigProvider) {
1907         if (isSelfIssued(cert)) {
1908             try {
1909                 if (sigProvider == null) {
1910                     cert.verify(cert.getPublicKey());
1911                 } else {
1912                     cert.verify(cert.getPublicKey(), sigProvider);
1913                 }
1914                 return true;
1915             } catch (Exception e) {
1916                 // In case of exception, return false
1917             }
1918         }
1919         return false;
1920     }
1921 
1922     private ConcurrentHashMap<String,String> fingerprints =
1923             new ConcurrentHashMap<>(2);
1924 
1925     public String getFingerprint(String algorithm) {
1926         return fingerprints.computeIfAbsent(algorithm,
1927             x -> getFingerprint(x, this));
1928     }
1929 
1930     /**
1931      * Gets the requested finger print of the certificate. The result
1932      * only contains 0-9 and A-F. No small case, no colon.
1933      */
1934     public static String getFingerprint(String algorithm,
1935             X509Certificate cert) {
1936         try {
1937             byte[] encCertInfo = cert.getEncoded();
1938             MessageDigest md = MessageDigest.getInstance(algorithm);
1939             byte[] digest = md.digest(encCertInfo);
1940             StringBuilder sb = new StringBuilder(digest.length * 2);
1941             for (int i = 0; i < digest.length; i++) {
1942                 byte2hex(digest[i], sb);
1943             }
1944             return sb.toString();
1945         } catch (NoSuchAlgorithmException | CertificateEncodingException e) {
1946             // ignored
1947         }
1948         return "";
1949     }
1950 
1951     /**
1952      * Converts a byte to hex digit and writes to the supplied builder
1953      */
1954     private static void byte2hex(byte b, StringBuilder buf) {
1955         char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
1956                 '9', 'A', 'B', 'C', 'D', 'E', 'F' };
1957         int high = ((b & 0xf0) >> 4);
1958         int low = (b & 0x0f);
1959         buf.append(hexChars[high])
1960             .append(hexChars[low]);
1961     }
1962 }