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