X509CertSelector.java 104.3 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
 */

package java.security.cert;

import java.io.IOException;
import java.math.BigInteger;
import java.security.PublicKey;
import java.util.*;
import javax.security.auth.x500.X500Principal;

import sun.misc.HexDumpEncoder;
import sun.security.util.Debug;
import sun.security.util.DerInputStream;
import sun.security.util.DerValue;
import sun.security.util.ObjectIdentifier;
import sun.security.x509.*;

/**
42
 * A {@code CertSelector} that selects {@code X509Certificates} that
D
duke 已提交
43
 * match all specified criteria. This class is particularly useful when
44
 * selecting certificates from a {@code CertStore} to build a
D
duke 已提交
45 46
 * PKIX-compliant certification path.
 * <p>
47 48 49
 * When first constructed, an {@code X509CertSelector} has no criteria
 * enabled and each of the {@code get} methods return a default value
 * ({@code null}, or {@code -1} for the {@link #getBasicConstraints
D
duke 已提交
50
 * getBasicConstraints} method). Therefore, the {@link #match match}
51
 * method would return {@code true} for any {@code X509Certificate}.
D
duke 已提交
52 53 54
 * Typically, several criteria are enabled (by calling
 * {@link #setIssuer setIssuer} or
 * {@link #setKeyUsage setKeyUsage}, for instance) and then the
55
 * {@code X509CertSelector} is passed to
D
duke 已提交
56 57 58 59 60
 * {@link CertStore#getCertificates CertStore.getCertificates} or some similar
 * method.
 * <p>
 * Several criteria can be enabled (by calling {@link #setIssuer setIssuer}
 * and {@link #setSerialNumber setSerialNumber},
61 62
 * for example) such that the {@code match} method
 * usually uniquely matches a single {@code X509Certificate}. We say
D
duke 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
 * usually, since it is possible for two issuing CAs to have the same
 * distinguished name and each issue a certificate with the same serial
 * number. Other unique combinations include the issuer, subject,
 * subjectKeyIdentifier and/or the subjectPublicKey criteria.
 * <p>
 * Please refer to <a href="http://www.ietf.org/rfc/rfc3280.txt">RFC 3280:
 * Internet X.509 Public Key Infrastructure Certificate and CRL Profile</a> for
 * definitions of the X.509 certificate extensions mentioned below.
 * <p>
 * <b>Concurrent Access</b>
 * <p>
 * Unless otherwise specified, the methods defined in this class are not
 * thread-safe. Multiple threads that need to access a single
 * object concurrently should synchronize amongst themselves and
 * provide the necessary locking. Multiple threads each manipulating
 * separate objects need not synchronize.
 *
 * @see CertSelector
 * @see X509Certificate
 *
 * @since       1.4
 * @author      Steve Hanna
 */
public class X509CertSelector implements CertSelector {

    private static final Debug debug = Debug.getInstance("certpath");

    private final static ObjectIdentifier ANY_EXTENDED_KEY_USAGE =
        ObjectIdentifier.newInternal(new int[] {2, 5, 29, 37, 0});

    static {
        CertPathHelperImpl.initialize();
    }

    private BigInteger serialNumber;
    private X500Principal issuer;
    private X500Principal subject;
    private byte[] subjectKeyID;
    private byte[] authorityKeyID;
    private Date certificateValid;
    private Date privateKeyValid;
    private ObjectIdentifier subjectPublicKeyAlgID;
    private PublicKey subjectPublicKey;
    private byte[] subjectPublicKeyBytes;
    private boolean[] keyUsage;
    private Set<String> keyPurposeSet;
    private Set<ObjectIdentifier> keyPurposeOIDSet;
    private Set<List<?>> subjectAlternativeNames;
    private Set<GeneralNameInterface> subjectAlternativeGeneralNames;
    private CertificatePolicySet policy;
    private Set<String> policySet;
    private Set<List<?>> pathToNames;
    private Set<GeneralNameInterface> pathToGeneralNames;
    private NameConstraintsExtension nc;
    private byte[] ncBytes;
    private int basicConstraints = -1;
    private X509Certificate x509Cert;
    private boolean matchAllSubjectAltNames = true;

    private static final Boolean FALSE = Boolean.FALSE;

    private static final int PRIVATE_KEY_USAGE_ID = 0;
    private static final int SUBJECT_ALT_NAME_ID = 1;
    private static final int NAME_CONSTRAINTS_ID = 2;
    private static final int CERT_POLICIES_ID = 3;
    private static final int EXTENDED_KEY_USAGE_ID = 4;
    private static final int NUM_OF_EXTENSIONS = 5;
    private static final String[] EXTENSION_OIDS = new String[NUM_OF_EXTENSIONS];

    static {
        EXTENSION_OIDS[PRIVATE_KEY_USAGE_ID]  = "2.5.29.16";
        EXTENSION_OIDS[SUBJECT_ALT_NAME_ID]   = "2.5.29.17";
        EXTENSION_OIDS[NAME_CONSTRAINTS_ID]   = "2.5.29.30";
        EXTENSION_OIDS[CERT_POLICIES_ID]      = "2.5.29.32";
        EXTENSION_OIDS[EXTENDED_KEY_USAGE_ID] = "2.5.29.37";
    };

    /* Constants representing the GeneralName types */
    static final int NAME_ANY = 0;
    static final int NAME_RFC822 = 1;
    static final int NAME_DNS = 2;
    static final int NAME_X400 = 3;
    static final int NAME_DIRECTORY = 4;
    static final int NAME_EDI = 5;
    static final int NAME_URI = 6;
    static final int NAME_IP = 7;
    static final int NAME_OID = 8;

    /**
152 153
     * Creates an {@code X509CertSelector}. Initially, no criteria are set
     * so any {@code X509Certificate} will match.
D
duke 已提交
154 155 156 157 158 159 160
     */
    public X509CertSelector() {
        // empty
    }

    /**
     * Sets the certificateEquals criterion. The specified
161 162 163
     * {@code X509Certificate} must be equal to the
     * {@code X509Certificate} passed to the {@code match} method.
     * If {@code null}, then this check is not applied.
D
duke 已提交
164 165 166 167 168 169
     *
     * <p>This method is particularly useful when it is necessary to
     * match a single certificate. Although other criteria can be specified
     * in conjunction with the certificateEquals criterion, it is usually not
     * practical or necessary.
     *
170 171
     * @param cert the {@code X509Certificate} to match (or
     * {@code null})
D
duke 已提交
172 173 174 175 176 177 178 179 180
     * @see #getCertificate
     */
    public void setCertificate(X509Certificate cert) {
        x509Cert = cert;
    }

    /**
     * Sets the serialNumber criterion. The specified serial number
     * must match the certificate serial number in the
181
     * {@code X509Certificate}. If {@code null}, any certificate
D
duke 已提交
182 183 184
     * serial number will do.
     *
     * @param serial the certificate serial number to match
185
     *        (or {@code null})
D
duke 已提交
186 187 188 189 190 191 192 193 194
     * @see #getSerialNumber
     */
    public void setSerialNumber(BigInteger serial) {
        serialNumber = serial;
    }

    /**
     * Sets the issuer criterion. The specified distinguished name
     * must match the issuer distinguished name in the
195
     * {@code X509Certificate}. If {@code null}, any issuer
D
duke 已提交
196 197 198
     * distinguished name will do.
     *
     * @param issuer a distinguished name as X500Principal
199
     *                 (or {@code null})
D
duke 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
     * @since 1.5
     */
    public void setIssuer(X500Principal issuer) {
        this.issuer = issuer;
    }

    /**
     * <strong>Denigrated</strong>, use {@linkplain #setIssuer(X500Principal)}
     * or {@linkplain #setIssuer(byte[])} instead. This method should not be
     * relied on as it can fail to match some certificates because of a loss of
     * encoding information in the
     * <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a> String form
     * of some distinguished names.
     * <p>
     * Sets the issuer criterion. The specified distinguished name
     * must match the issuer distinguished name in the
216
     * {@code X509Certificate}. If {@code null}, any issuer
D
duke 已提交
217 218
     * distinguished name will do.
     * <p>
219
     * If {@code issuerDN} is not {@code null}, it should contain a
D
duke 已提交
220 221 222
     * distinguished name, in RFC 2253 format.
     *
     * @param issuerDN a distinguished name in RFC 2253 format
223
     *                 (or {@code null})
D
duke 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236
     * @throws IOException if a parsing error occurs (incorrect form for DN)
     */
    public void setIssuer(String issuerDN) throws IOException {
        if (issuerDN == null) {
            issuer = null;
        } else {
            issuer = new X500Name(issuerDN).asX500Principal();
        }
    }

    /**
     * Sets the issuer criterion. The specified distinguished name
     * must match the issuer distinguished name in the
237
     * {@code X509Certificate}. If {@code null} is specified,
D
duke 已提交
238 239 240
     * the issuer criterion is disabled and any issuer distinguished name will
     * do.
     * <p>
241
     * If {@code issuerDN} is not {@code null}, it should contain a
D
duke 已提交
242 243
     * single DER encoded distinguished name, as defined in X.501. The ASN.1
     * notation for this structure is as follows.
244
     * <pre>{@code
D
duke 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
     * Name ::= CHOICE {
     *   RDNSequence }
     *
     * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
     *
     * RelativeDistinguishedName ::=
     *   SET SIZE (1 .. MAX) OF AttributeTypeAndValue
     *
     * AttributeTypeAndValue ::= SEQUENCE {
     *   type     AttributeType,
     *   value    AttributeValue }
     *
     * AttributeType ::= OBJECT IDENTIFIER
     *
     * AttributeValue ::= ANY DEFINED BY AttributeType
     * ....
     * DirectoryString ::= CHOICE {
     *       teletexString           TeletexString (SIZE (1..MAX)),
     *       printableString         PrintableString (SIZE (1..MAX)),
     *       universalString         UniversalString (SIZE (1..MAX)),
     *       utf8String              UTF8String (SIZE (1.. MAX)),
     *       bmpString               BMPString (SIZE (1..MAX)) }
267
     * }</pre>
D
duke 已提交
268 269 270 271 272
     * <p>
     * Note that the byte array specified here is cloned to protect against
     * subsequent modifications.
     *
     * @param issuerDN a byte array containing the distinguished name
273
     *                 in ASN.1 DER encoded form (or {@code null})
D
duke 已提交
274 275 276 277 278 279
     * @throws IOException if an encoding error occurs (incorrect form for DN)
     */
    public void setIssuer(byte[] issuerDN) throws IOException {
        try {
            issuer = (issuerDN == null ? null : new X500Principal(issuerDN));
        } catch (IllegalArgumentException e) {
280
            throw new IOException("Invalid name", e);
D
duke 已提交
281 282 283 284 285 286
        }
    }

    /**
     * Sets the subject criterion. The specified distinguished name
     * must match the subject distinguished name in the
287
     * {@code X509Certificate}. If {@code null}, any subject
D
duke 已提交
288 289 290
     * distinguished name will do.
     *
     * @param subject a distinguished name as X500Principal
291
     *                  (or {@code null})
D
duke 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
     * @since 1.5
     */
    public void setSubject(X500Principal subject) {
        this.subject = subject;
    }

    /**
     * <strong>Denigrated</strong>, use {@linkplain #setSubject(X500Principal)}
     * or {@linkplain #setSubject(byte[])} instead. This method should not be
     * relied on as it can fail to match some certificates because of a loss of
     * encoding information in the RFC 2253 String form of some distinguished
     * names.
     * <p>
     * Sets the subject criterion. The specified distinguished name
     * must match the subject distinguished name in the
307
     * {@code X509Certificate}. If {@code null}, any subject
D
duke 已提交
308 309
     * distinguished name will do.
     * <p>
310
     * If {@code subjectDN} is not {@code null}, it should contain a
D
duke 已提交
311 312 313
     * distinguished name, in RFC 2253 format.
     *
     * @param subjectDN a distinguished name in RFC 2253 format
314
     *                  (or {@code null})
D
duke 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327
     * @throws IOException if a parsing error occurs (incorrect form for DN)
     */
    public void setSubject(String subjectDN) throws IOException {
        if (subjectDN == null) {
            subject = null;
        } else {
            subject = new X500Name(subjectDN).asX500Principal();
        }
    }

    /**
     * Sets the subject criterion. The specified distinguished name
     * must match the subject distinguished name in the
328
     * {@code X509Certificate}. If {@code null}, any subject
D
duke 已提交
329 330
     * distinguished name will do.
     * <p>
331
     * If {@code subjectDN} is not {@code null}, it should contain a
D
duke 已提交
332 333 334 335 336
     * single DER encoded distinguished name, as defined in X.501. For the ASN.1
     * notation for this structure, see
     * {@link #setIssuer(byte [] issuerDN) setIssuer(byte [] issuerDN)}.
     *
     * @param subjectDN a byte array containing the distinguished name in
337
     *                  ASN.1 DER format (or {@code null})
D
duke 已提交
338 339 340 341 342 343
     * @throws IOException if an encoding error occurs (incorrect form for DN)
     */
    public void setSubject(byte[] subjectDN) throws IOException {
        try {
            subject = (subjectDN == null ? null : new X500Principal(subjectDN));
        } catch (IllegalArgumentException e) {
344
            throw new IOException("Invalid name", e);
D
duke 已提交
345 346 347 348 349
        }
    }

    /**
     * Sets the subjectKeyIdentifier criterion. The
350
     * {@code X509Certificate} must contain a SubjectKeyIdentifier
D
duke 已提交
351 352
     * extension for which the contents of the extension
     * matches the specified criterion value.
353
     * If the criterion value is {@code null}, no
D
duke 已提交
354 355
     * subjectKeyIdentifier check will be done.
     * <p>
356
     * If {@code subjectKeyID} is not {@code null}, it
D
duke 已提交
357 358 359 360 361 362
     * should contain a single DER encoded value corresponding to the contents
     * of the extension value (not including the object identifier,
     * criticality setting, and encapsulating OCTET STRING)
     * for a SubjectKeyIdentifier extension.
     * The ASN.1 notation for this structure follows.
     * <p>
363
     * <pre>{@code
D
duke 已提交
364 365 366
     * SubjectKeyIdentifier ::= KeyIdentifier
     *
     * KeyIdentifier ::= OCTET STRING
367
     * }</pre>
D
duke 已提交
368 369 370
     * <p>
     * Since the format of subject key identifiers is not mandated by
     * any standard, subject key identifiers are not parsed by the
371
     * {@code X509CertSelector}. Instead, the values are compared using
D
duke 已提交
372 373 374 375 376
     * a byte-by-byte comparison.
     * <p>
     * Note that the byte array supplied here is cloned to protect against
     * subsequent modifications.
     *
377
     * @param subjectKeyID the subject key identifier (or {@code null})
D
duke 已提交
378 379 380 381 382 383
     * @see #getSubjectKeyIdentifier
     */
    public void setSubjectKeyIdentifier(byte[] subjectKeyID) {
        if (subjectKeyID == null) {
            this.subjectKeyID = null;
        } else {
384
            this.subjectKeyID = subjectKeyID.clone();
D
duke 已提交
385 386 387 388 389
        }
    }

    /**
     * Sets the authorityKeyIdentifier criterion. The
390
     * {@code X509Certificate} must contain an
D
duke 已提交
391 392
     * AuthorityKeyIdentifier extension for which the contents of the
     * extension value matches the specified criterion value.
393
     * If the criterion value is {@code null}, no
D
duke 已提交
394 395
     * authorityKeyIdentifier check will be done.
     * <p>
396
     * If {@code authorityKeyID} is not {@code null}, it
D
duke 已提交
397 398 399 400 401 402
     * should contain a single DER encoded value corresponding to the contents
     * of the extension value (not including the object identifier,
     * criticality setting, and encapsulating OCTET STRING)
     * for an AuthorityKeyIdentifier extension.
     * The ASN.1 notation for this structure follows.
     * <p>
403
     * <pre>{@code
D
duke 已提交
404 405 406 407 408 409
     * AuthorityKeyIdentifier ::= SEQUENCE {
     *    keyIdentifier             [0] KeyIdentifier           OPTIONAL,
     *    authorityCertIssuer       [1] GeneralNames            OPTIONAL,
     *    authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL  }
     *
     * KeyIdentifier ::= OCTET STRING
410
     * }</pre>
D
duke 已提交
411 412
     * <p>
     * Authority key identifiers are not parsed by the
413
     * {@code X509CertSelector}.  Instead, the values are
D
duke 已提交
414 415
     * compared using a byte-by-byte comparison.
     * <p>
416 417 418
     * When the {@code keyIdentifier} field of
     * {@code AuthorityKeyIdentifier} is populated, the value is
     * usually taken from the {@code SubjectKeyIdentifier} extension
D
duke 已提交
419
     * in the issuer's certificate.  Note, however, that the result of
420 421 422
     * {@code X509Certificate.getExtensionValue(<SubjectKeyIdentifier Object
     * Identifier>)} on the issuer's certificate may NOT be used
     * directly as the input to {@code setAuthorityKeyIdentifier}.
D
duke 已提交
423 424 425 426
     * This is because the SubjectKeyIdentifier contains
     * only a KeyIdentifier OCTET STRING, and not a SEQUENCE of
     * KeyIdentifier, GeneralNames, and CertificateSerialNumber.
     * In order to use the extension value of the issuer certificate's
427
     * {@code SubjectKeyIdentifier}
D
duke 已提交
428
     * extension, it will be necessary to extract the value of the embedded
429
     * {@code KeyIdentifier} OCTET STRING, then DER encode this OCTET
D
duke 已提交
430 431 432 433 434 435 436 437
     * STRING inside a SEQUENCE.
     * For more details on SubjectKeyIdentifier, see
     * {@link #setSubjectKeyIdentifier(byte[] subjectKeyID)}.
     * <p>
     * Note also that the byte array supplied here is cloned to protect against
     * subsequent modifications.
     *
     * @param authorityKeyID the authority key identifier
438
     *        (or {@code null})
D
duke 已提交
439 440 441 442 443 444
     * @see #getAuthorityKeyIdentifier
     */
    public void setAuthorityKeyIdentifier(byte[] authorityKeyID) {
        if (authorityKeyID == null) {
            this.authorityKeyID = null;
        } else {
445
            this.authorityKeyID = authorityKeyID.clone();
D
duke 已提交
446 447 448 449 450 451
        }
    }

    /**
     * Sets the certificateValid criterion. The specified date must fall
     * within the certificate validity period for the
452
     * {@code X509Certificate}. If {@code null}, no certificateValid
D
duke 已提交
453 454
     * check will be done.
     * <p>
455
     * Note that the {@code Date} supplied here is cloned to protect
D
duke 已提交
456 457
     * against subsequent modifications.
     *
458
     * @param certValid the {@code Date} to check (or {@code null})
D
duke 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471
     * @see #getCertificateValid
     */
    public void setCertificateValid(Date certValid) {
        if (certValid == null) {
            certificateValid = null;
        } else {
            certificateValid = (Date)certValid.clone();
        }
    }

    /**
     * Sets the privateKeyValid criterion. The specified date must fall
     * within the private key validity period for the
472
     * {@code X509Certificate}. If {@code null}, no privateKeyValid
D
duke 已提交
473 474
     * check will be done.
     * <p>
475
     * Note that the {@code Date} supplied here is cloned to protect
D
duke 已提交
476 477
     * against subsequent modifications.
     *
478 479
     * @param privateKeyValid the {@code Date} to check (or
     *                        {@code null})
D
duke 已提交
480 481 482 483 484 485 486 487 488 489 490 491
     * @see #getPrivateKeyValid
     */
    public void setPrivateKeyValid(Date privateKeyValid) {
        if (privateKeyValid == null) {
            this.privateKeyValid = null;
        } else {
            this.privateKeyValid = (Date)privateKeyValid.clone();
        }
    }

    /**
     * Sets the subjectPublicKeyAlgID criterion. The
492 493
     * {@code X509Certificate} must contain a subject public key
     * with the specified algorithm. If {@code null}, no
D
duke 已提交
494 495 496
     * subjectPublicKeyAlgID check will be done.
     *
     * @param oid The object identifier (OID) of the algorithm to check
497
     *            for (or {@code null}). An OID is represented by a
D
duke 已提交
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
     *            set of nonnegative integers separated by periods.
     * @throws IOException if the OID is invalid, such as
     * the first component being not 0, 1 or 2 or the second component
     * being greater than 39.
     *
     * @see #getSubjectPublicKeyAlgID
     */
    public void setSubjectPublicKeyAlgID(String oid) throws IOException {
        if (oid == null) {
            subjectPublicKeyAlgID = null;
        } else {
            subjectPublicKeyAlgID = new ObjectIdentifier(oid);
        }
    }

    /**
     * Sets the subjectPublicKey criterion. The
515 516
     * {@code X509Certificate} must contain the specified subject public
     * key. If {@code null}, no subjectPublicKey check will be done.
D
duke 已提交
517
     *
518
     * @param key the subject public key to check for (or {@code null})
D
duke 已提交
519 520 521 522 523 524 525 526 527 528 529 530 531
     * @see #getSubjectPublicKey
     */
    public void setSubjectPublicKey(PublicKey key) {
        if (key == null) {
            subjectPublicKey = null;
            subjectPublicKeyBytes = null;
        } else {
            subjectPublicKey = key;
            subjectPublicKeyBytes = key.getEncoded();
        }
    }

    /**
532 533
     * Sets the subjectPublicKey criterion. The {@code X509Certificate}
     * must contain the specified subject public key. If {@code null},
D
duke 已提交
534 535 536 537 538
     * no subjectPublicKey check will be done.
     * <p>
     * Because this method allows the public key to be specified as a byte
     * array, it may be used for unknown key types.
     * <p>
539
     * If {@code key} is not {@code null}, it should contain a
D
duke 已提交
540 541
     * single DER encoded SubjectPublicKeyInfo structure, as defined in X.509.
     * The ASN.1 notation for this structure is as follows.
542
     * <pre>{@code
D
duke 已提交
543 544 545 546 547 548 549 550 551 552
     * SubjectPublicKeyInfo  ::=  SEQUENCE  {
     *   algorithm            AlgorithmIdentifier,
     *   subjectPublicKey     BIT STRING  }
     *
     * AlgorithmIdentifier  ::=  SEQUENCE  {
     *   algorithm               OBJECT IDENTIFIER,
     *   parameters              ANY DEFINED BY algorithm OPTIONAL  }
     *                              -- contains a value of the type
     *                              -- registered for use with the
     *                              -- algorithm object identifier value
553
     * }</pre>
D
duke 已提交
554 555 556 557 558
     * <p>
     * Note that the byte array supplied here is cloned to protect against
     * subsequent modifications.
     *
     * @param key a byte array containing the subject public key in ASN.1 DER
559
     *            form (or {@code null})
D
duke 已提交
560 561 562 563 564 565 566 567 568
     * @throws IOException if an encoding error occurs (incorrect form for
     * subject public key)
     * @see #getSubjectPublicKey
     */
    public void setSubjectPublicKey(byte[] key) throws IOException {
        if (key == null) {
            subjectPublicKey = null;
            subjectPublicKeyBytes = null;
        } else {
569
            subjectPublicKeyBytes = key.clone();
D
duke 已提交
570 571 572 573 574
            subjectPublicKey = X509Key.parse(new DerValue(subjectPublicKeyBytes));
        }
    }

    /**
575 576 577
     * Sets the keyUsage criterion. The {@code X509Certificate}
     * must allow the specified keyUsage values. If {@code null}, no
     * keyUsage check will be done. Note that an {@code X509Certificate}
D
duke 已提交
578 579 580 581 582 583 584 585
     * that has no keyUsage extension implicitly allows all keyUsage values.
     * <p>
     * Note that the boolean array supplied here is cloned to protect against
     * subsequent modifications.
     *
     * @param keyUsage a boolean array in the same format as the boolean
     *                 array returned by
     * {@link X509Certificate#getKeyUsage() X509Certificate.getKeyUsage()}.
586
     *                 Or {@code null}.
D
duke 已提交
587 588 589 590 591 592
     * @see #getKeyUsage
     */
    public void setKeyUsage(boolean[] keyUsage) {
        if (keyUsage == null) {
            this.keyUsage = null;
        } else {
593
            this.keyUsage = keyUsage.clone();
D
duke 已提交
594 595 596 597
        }
    }

    /**
598
     * Sets the extendedKeyUsage criterion. The {@code X509Certificate}
D
duke 已提交
599
     * must allow the specified key purposes in its extended key usage
600
     * extension. If {@code keyPurposeSet} is empty or {@code null},
D
duke 已提交
601
     * no extendedKeyUsage check will be done. Note that an
602
     * {@code X509Certificate} that has no extendedKeyUsage extension
D
duke 已提交
603 604
     * implicitly allows all key purposes.
     * <p>
605
     * Note that the {@code Set} is cloned to protect against
D
duke 已提交
606 607
     * subsequent modifications.
     *
608 609
     * @param keyPurposeSet a {@code Set} of key purpose OIDs in string
     * format (or {@code null}). Each OID is represented by a set of
D
duke 已提交
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
     * nonnegative integers separated by periods.
     * @throws IOException if the OID is invalid, such as
     * the first component being not 0, 1 or 2 or the second component
     * being greater than 39.
     * @see #getExtendedKeyUsage
     */
    public void setExtendedKeyUsage(Set<String> keyPurposeSet) throws IOException {
        if ((keyPurposeSet == null) || keyPurposeSet.isEmpty()) {
            this.keyPurposeSet = null;
            keyPurposeOIDSet = null;
        } else {
            this.keyPurposeSet =
                Collections.unmodifiableSet(new HashSet<String>(keyPurposeSet));
            keyPurposeOIDSet = new HashSet<ObjectIdentifier>();
            for (String s : this.keyPurposeSet) {
                keyPurposeOIDSet.add(new ObjectIdentifier(s));
            }
        }
    }

    /**
     * Enables/disables matching all of the subjectAlternativeNames
     * specified in the {@link #setSubjectAlternativeNames
     * setSubjectAlternativeNames} or {@link #addSubjectAlternativeName
     * addSubjectAlternativeName} methods. If enabled,
635
     * the {@code X509Certificate} must contain all of the
D
duke 已提交
636
     * specified subject alternative names. If disabled, the
637
     * {@code X509Certificate} must contain at least one of the
D
duke 已提交
638 639
     * specified subject alternative names.
     *
640
     * <p>The matchAllNames flag is {@code true} by default.
D
duke 已提交
641
     *
642 643
     * @param matchAllNames if {@code true}, the flag is enabled;
     * if {@code false}, the flag is disabled.
D
duke 已提交
644 645 646 647 648 649 650 651
     * @see #getMatchAllSubjectAltNames
     */
    public void setMatchAllSubjectAltNames(boolean matchAllNames) {
        this.matchAllSubjectAltNames = matchAllNames;
    }

    /**
     * Sets the subjectAlternativeNames criterion. The
652
     * {@code X509Certificate} must contain all or at least one of the
D
duke 已提交
653 654 655 656 657 658 659 660 661
     * specified subjectAlternativeNames, depending on the value of
     * the matchAllNames flag (see {@link #setMatchAllSubjectAltNames
     * setMatchAllSubjectAltNames}).
     * <p>
     * This method allows the caller to specify, with a single method call,
     * the complete set of subject alternative names for the
     * subjectAlternativeNames criterion. The specified value replaces
     * the previous value for the subjectAlternativeNames criterion.
     * <p>
662 663
     * The {@code names} parameter (if not {@code null}) is a
     * {@code Collection} with one
D
duke 已提交
664
     * entry for each name to be included in the subject alternative name
665 666 667
     * criterion. Each entry is a {@code List} whose first entry is an
     * {@code Integer} (the name type, 0-8) and whose second
     * entry is a {@code String} or a byte array (the name, in
D
duke 已提交
668
     * string or ASN.1 DER encoded form, respectively).
669
     * There can be multiple names of the same type. If {@code null}
D
duke 已提交
670 671 672
     * is supplied as the value for this argument, no
     * subjectAlternativeNames check will be performed.
     * <p>
673 674
     * Each subject alternative name in the {@code Collection}
     * may be specified either as a {@code String} or as an ASN.1 encoded
D
duke 已提交
675 676 677 678 679 680 681 682 683 684
     * byte array. For more details about the formats used, see
     * {@link #addSubjectAlternativeName(int type, String name)
     * addSubjectAlternativeName(int type, String name)} and
     * {@link #addSubjectAlternativeName(int type, byte [] name)
     * addSubjectAlternativeName(int type, byte [] name)}.
     * <p>
     * <strong>Note:</strong> for distinguished names, specify the byte
     * array form instead of the String form. See the note in
     * {@link #addSubjectAlternativeName(int, String)} for more information.
     * <p>
685
     * Note that the {@code names} parameter can contain duplicate
D
duke 已提交
686
     * names (same name and name type), but they may be removed from the
687
     * {@code Collection} of names returned by the
D
duke 已提交
688 689
     * {@link #getSubjectAlternativeNames getSubjectAlternativeNames} method.
     * <p>
690
     * Note that a deep copy is performed on the {@code Collection} to
D
duke 已提交
691 692
     * protect against subsequent modifications.
     *
693
     * @param names a {@code Collection} of names (or {@code null})
D
duke 已提交
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
     * @throws IOException if a parsing error occurs
     * @see #getSubjectAlternativeNames
     */
    public void setSubjectAlternativeNames(Collection<List<?>> names)
            throws IOException {
        if (names == null) {
            subjectAlternativeNames = null;
            subjectAlternativeGeneralNames = null;
        } else {
            if (names.isEmpty()) {
                subjectAlternativeNames = null;
                subjectAlternativeGeneralNames = null;
                return;
            }
            Set<List<?>> tempNames = cloneAndCheckNames(names);
            // Ensure that we either set both of these or neither
            subjectAlternativeGeneralNames = parseNames(tempNames);
            subjectAlternativeNames = tempNames;
        }
    }

    /**
     * Adds a name to the subjectAlternativeNames criterion. The
717
     * {@code X509Certificate} must contain all or at least one
D
duke 已提交
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
     * of the specified subjectAlternativeNames, depending on the value of
     * the matchAllNames flag (see {@link #setMatchAllSubjectAltNames
     * setMatchAllSubjectAltNames}).
     * <p>
     * This method allows the caller to add a name to the set of subject
     * alternative names.
     * The specified name is added to any previous value for the
     * subjectAlternativeNames criterion. If the specified name is a
     * duplicate, it may be ignored.
     * <p>
     * The name is provided in string format.
     * <a href="http://www.ietf.org/rfc/rfc822.txt">RFC 822</a>, DNS, and URI
     * names use the well-established string formats for those types (subject to
     * the restrictions included in RFC 3280). IPv4 address names are
     * supplied using dotted quad notation. OID address names are represented
     * as a series of nonnegative integers separated by periods. And
     * directory names (distinguished names) are supplied in RFC 2253 format.
     * No standard string format is defined for otherNames, X.400 names,
     * EDI party names, IPv6 address names, or any other type of names. They
     * should be specified using the
     * {@link #addSubjectAlternativeName(int type, byte [] name)
     * addSubjectAlternativeName(int type, byte [] name)}
     * method.
     * <p>
     * <strong>Note:</strong> for distinguished names, use
     * {@linkplain #addSubjectAlternativeName(int, byte[])} instead.
     * This method should not be relied on as it can fail to match some
     * certificates because of a loss of encoding information in the RFC 2253
     * String form of some distinguished names.
     *
     * @param type the name type (0-8, as specified in
     *             RFC 3280, section 4.2.1.7)
750
     * @param name the name in string form (not {@code null})
D
duke 已提交
751 752 753 754 755 756 757 758 759
     * @throws IOException if a parsing error occurs
     */
    public void addSubjectAlternativeName(int type, String name)
            throws IOException {
        addSubjectAlternativeNameInternal(type, name);
    }

    /**
     * Adds a name to the subjectAlternativeNames criterion. The
760
     * {@code X509Certificate} must contain all or at least one
D
duke 已提交
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
     * of the specified subjectAlternativeNames, depending on the value of
     * the matchAllNames flag (see {@link #setMatchAllSubjectAltNames
     * setMatchAllSubjectAltNames}).
     * <p>
     * This method allows the caller to add a name to the set of subject
     * alternative names.
     * The specified name is added to any previous value for the
     * subjectAlternativeNames criterion. If the specified name is a
     * duplicate, it may be ignored.
     * <p>
     * The name is provided as a byte array. This byte array should contain
     * the DER encoded name, as it would appear in the GeneralName structure
     * defined in RFC 3280 and X.509. The encoded byte array should only contain
     * the encoded value of the name, and should not include the tag associated
     * with the name in the GeneralName structure. The ASN.1 definition of this
     * structure appears below.
777
     * <pre>{@code
D
duke 已提交
778 779 780 781 782 783 784 785 786 787
     *  GeneralName ::= CHOICE {
     *       otherName                       [0]     OtherName,
     *       rfc822Name                      [1]     IA5String,
     *       dNSName                         [2]     IA5String,
     *       x400Address                     [3]     ORAddress,
     *       directoryName                   [4]     Name,
     *       ediPartyName                    [5]     EDIPartyName,
     *       uniformResourceIdentifier       [6]     IA5String,
     *       iPAddress                       [7]     OCTET STRING,
     *       registeredID                    [8]     OBJECT IDENTIFIER}
788
     * }</pre>
D
duke 已提交
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
     * <p>
     * Note that the byte array supplied here is cloned to protect against
     * subsequent modifications.
     *
     * @param type the name type (0-8, as listed above)
     * @param name a byte array containing the name in ASN.1 DER encoded form
     * @throws IOException if a parsing error occurs
     */
    public void addSubjectAlternativeName(int type, byte[] name)
            throws IOException {
        // clone because byte arrays are modifiable
        addSubjectAlternativeNameInternal(type, name.clone());
    }

    /**
     * A private method that adds a name (String or byte array) to the
805
     * subjectAlternativeNames criterion. The {@code X509Certificate}
D
duke 已提交
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
     * must contain the specified subjectAlternativeName.
     *
     * @param type the name type (0-8, as specified in
     *             RFC 3280, section 4.2.1.7)
     * @param name the name in string or byte array form
     * @throws IOException if a parsing error occurs
     */
    private void addSubjectAlternativeNameInternal(int type, Object name)
            throws IOException {
        // First, ensure that the name parses
        GeneralNameInterface tempName = makeGeneralNameInterface(type, name);
        if (subjectAlternativeNames == null) {
            subjectAlternativeNames = new HashSet<List<?>>();
        }
        if (subjectAlternativeGeneralNames == null) {
            subjectAlternativeGeneralNames = new HashSet<GeneralNameInterface>();
        }
        List<Object> list = new ArrayList<Object>(2);
        list.add(Integer.valueOf(type));
        list.add(name);
        subjectAlternativeNames.add(list);
        subjectAlternativeGeneralNames.add(tempName);
    }

    /**
     * Parse an argument of the form passed to setSubjectAlternativeNames,
832 833
     * returning a {@code Collection} of
     * {@code GeneralNameInterface}s.
D
duke 已提交
834 835 836 837
     * Throw an IllegalArgumentException or a ClassCastException
     * if the argument is malformed.
     *
     * @param names a Collection with one entry per name.
838
     *              Each entry is a {@code List} whose first entry
D
duke 已提交
839 840 841 842 843
     *              is an Integer (the name type, 0-8) and whose second
     *              entry is a String or a byte array (the name, in
     *              string or ASN.1 DER encoded form, respectively).
     *              There can be multiple names of the same type. Null is
     *              not an acceptable value.
844
     * @return a Set of {@code GeneralNameInterface}s
D
duke 已提交
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
     * @throws IOException if a parsing error occurs
     */
    private static Set<GeneralNameInterface> parseNames(Collection<List<?>> names) throws IOException {
        Set<GeneralNameInterface> genNames = new HashSet<GeneralNameInterface>();
        for (List<?> nameList : names) {
            if (nameList.size() != 2) {
                throw new IOException("name list size not 2");
            }
            Object o =  nameList.get(0);
            if (!(o instanceof Integer)) {
                throw new IOException("expected an Integer");
            }
            int nameType = ((Integer)o).intValue();
            o = nameList.get(1);
            genNames.add(makeGeneralNameInterface(nameType, o));
        }

        return genNames;
    }

    /**
     * Compare for equality two objects of the form passed to
     * setSubjectAlternativeNames (or X509CRLSelector.setIssuerNames).
868 869
     * Throw an {@code IllegalArgumentException} or a
     * {@code ClassCastException} if one of the objects is malformed.
D
duke 已提交
870 871 872 873 874
     *
     * @param object1 a Collection containing the first object to compare
     * @param object2 a Collection containing the second object to compare
     * @return true if the objects are equal, false otherwise
     */
875
    static boolean equalNames(Collection<?> object1, Collection<?> object2) {
D
duke 已提交
876 877 878 879 880 881 882
        if ((object1 == null) || (object2 == null)) {
            return object1 == object2;
        }
        return object1.equals(object2);
    }

    /**
883
     * Make a {@code GeneralNameInterface} out of a name type (0-8) and an
D
duke 已提交
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
     * Object that may be a byte array holding the ASN.1 DER encoded
     * name or a String form of the name.  Except for X.509
     * Distinguished Names, the String form of the name must not be the
     * result from calling toString on an existing GeneralNameInterface
     * implementing class.  The output of toString is not compatible
     * with the String constructors for names other than Distinguished
     * Names.
     *
     * @param type name type (0-8)
     * @param name name as ASN.1 Der-encoded byte array or String
     * @return a GeneralNameInterface name
     * @throws IOException if a parsing error occurs
     */
    static GeneralNameInterface makeGeneralNameInterface(int type, Object name)
            throws IOException {
        GeneralNameInterface result;
        if (debug != null) {
            debug.println("X509CertSelector.makeGeneralNameInterface("
                + type + ")...");
        }

        if (name instanceof String) {
            if (debug != null) {
                debug.println("X509CertSelector.makeGeneralNameInterface() "
                    + "name is String: " + name);
            }
            switch (type) {
            case NAME_RFC822:
                result = new RFC822Name((String)name);
                break;
            case NAME_DNS:
                result = new DNSName((String)name);
                break;
            case NAME_DIRECTORY:
                result = new X500Name((String)name);
                break;
            case NAME_URI:
                result = new URIName((String)name);
                break;
            case NAME_IP:
                result = new IPAddressName((String)name);
                break;
            case NAME_OID:
                result = new OIDName((String)name);
                break;
            default:
                throw new IOException("unable to parse String names of type "
                                      + type);
            }
            if (debug != null) {
                debug.println("X509CertSelector.makeGeneralNameInterface() "
                    + "result: " + result.toString());
            }
        } else if (name instanceof byte[]) {
            DerValue val = new DerValue((byte[]) name);
            if (debug != null) {
                debug.println
                    ("X509CertSelector.makeGeneralNameInterface() is byte[]");
            }

            switch (type) {
            case NAME_ANY:
                result = new OtherName(val);
                break;
            case NAME_RFC822:
                result = new RFC822Name(val);
                break;
            case NAME_DNS:
                result = new DNSName(val);
                break;
            case NAME_X400:
                result = new X400Address(val);
                break;
            case NAME_DIRECTORY:
                result = new X500Name(val);
                break;
            case NAME_EDI:
                result = new EDIPartyName(val);
                break;
            case NAME_URI:
                result = new URIName(val);
                break;
            case NAME_IP:
                result = new IPAddressName(val);
                break;
            case NAME_OID:
                result = new OIDName(val);
                break;
            default:
                throw new IOException("unable to parse byte array names of "
                    + "type " + type);
            }
            if (debug != null) {
                debug.println("X509CertSelector.makeGeneralNameInterface() result: "
                    + result.toString());
            }
        } else {
            if (debug != null) {
                debug.println("X509CertSelector.makeGeneralName() input name "
                    + "not String or byte array");
            }
            throw new IOException("name not String or byte array");
        }
        return result;
    }


    /**
992
     * Sets the name constraints criterion. The {@code X509Certificate}
D
duke 已提交
993 994 995 996 997 998 999 1000
     * must have subject and subject alternative names that
     * meet the specified name constraints.
     * <p>
     * The name constraints are specified as a byte array. This byte array
     * should contain the DER encoded form of the name constraints, as they
     * would appear in the NameConstraints structure defined in RFC 3280
     * and X.509. The ASN.1 definition of this structure appears below.
     *
1001
     * <pre>{@code
D
duke 已提交
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
     *  NameConstraints ::= SEQUENCE {
     *       permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
     *       excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
     *
     *  GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
     *
     *  GeneralSubtree ::= SEQUENCE {
     *       base                    GeneralName,
     *       minimum         [0]     BaseDistance DEFAULT 0,
     *       maximum         [1]     BaseDistance OPTIONAL }
     *
     *  BaseDistance ::= INTEGER (0..MAX)
     *
     *  GeneralName ::= CHOICE {
     *       otherName                       [0]     OtherName,
     *       rfc822Name                      [1]     IA5String,
     *       dNSName                         [2]     IA5String,
     *       x400Address                     [3]     ORAddress,
     *       directoryName                   [4]     Name,
     *       ediPartyName                    [5]     EDIPartyName,
     *       uniformResourceIdentifier       [6]     IA5String,
     *       iPAddress                       [7]     OCTET STRING,
     *       registeredID                    [8]     OBJECT IDENTIFIER}
1025
     * }</pre>
D
duke 已提交
1026 1027 1028 1029 1030 1031 1032 1033
     * <p>
     * Note that the byte array supplied here is cloned to protect against
     * subsequent modifications.
     *
     * @param bytes a byte array containing the ASN.1 DER encoding of
     *              a NameConstraints extension to be used for checking
     *              name constraints. Only the value of the extension is
     *              included, not the OID or criticality flag. Can be
1034
     *              {@code null},
D
duke 已提交
1035 1036 1037 1038 1039 1040 1041 1042 1043
     *              in which case no name constraints check will be performed.
     * @throws IOException if a parsing error occurs
     * @see #getNameConstraints
     */
    public void setNameConstraints(byte[] bytes) throws IOException {
        if (bytes == null) {
            ncBytes = null;
            nc = null;
        } else {
1044
            ncBytes = bytes.clone();
D
duke 已提交
1045 1046 1047 1048 1049 1050
            nc = new NameConstraintsExtension(FALSE, bytes);
        }
    }

    /**
     * Sets the basic constraints constraint. If the value is greater than or
1051
     * equal to zero, {@code X509Certificates} must include a
D
duke 已提交
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
     * basicConstraints extension with
     * a pathLen of at least this value. If the value is -2, only end-entity
     * certificates are accepted. If the value is -1, no check is done.
     * <p>
     * This constraint is useful when building a certification path forward
     * (from the target toward the trust anchor. If a partial path has been
     * built, any candidate certificate must have a maxPathLen value greater
     * than or equal to the number of certificates in the partial path.
     *
     * @param minMaxPathLen the value for the basic constraints constraint
     * @throws IllegalArgumentException if the value is less than -2
     * @see #getBasicConstraints
     */
    public void setBasicConstraints(int minMaxPathLen) {
        if (minMaxPathLen < -2) {
            throw new IllegalArgumentException("basic constraints less than -2");
        }
        basicConstraints = minMaxPathLen;
    }

    /**
1073
     * Sets the policy constraint. The {@code X509Certificate} must
D
duke 已提交
1074
     * include at least one of the specified policies in its certificate
1075 1076 1077 1078
     * policies extension. If {@code certPolicySet} is empty, then the
     * {@code X509Certificate} must include at least some specified policy
     * in its certificate policies extension. If {@code certPolicySet} is
     * {@code null}, no policy check will be performed.
D
duke 已提交
1079
     * <p>
1080
     * Note that the {@code Set} is cloned to protect against
D
duke 已提交
1081 1082
     * subsequent modifications.
     *
1083 1084
     * @param certPolicySet a {@code Set} of certificate policy OIDs in
     *                      string format (or {@code null}). Each OID is
D
duke 已提交
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
     *                      represented by a set of nonnegative integers
     *                    separated by periods.
     * @throws IOException if a parsing error occurs on the OID such as
     * the first component is not 0, 1 or 2 or the second component is
     * greater than 39.
     * @see #getPolicy
     */
    public void setPolicy(Set<String> certPolicySet) throws IOException {
        if (certPolicySet == null) {
            policySet = null;
            policy = null;
        } else {
            // Snapshot set and parse it
            Set<String> tempSet = Collections.unmodifiableSet
                                        (new HashSet<String>(certPolicySet));
            /* Convert to Vector of ObjectIdentifiers */
            Iterator<String> i = tempSet.iterator();
            Vector<CertificatePolicyId> polIdVector = new Vector<CertificatePolicyId>();
            while (i.hasNext()) {
                Object o = i.next();
                if (!(o instanceof String)) {
                    throw new IOException("non String in certPolicySet");
                }
                polIdVector.add(new CertificatePolicyId(new ObjectIdentifier(
                  (String)o)));
            }
            // If everything went OK, make the changes
            policySet = tempSet;
            policy = new CertificatePolicySet(polIdVector);
        }
    }

    /**
1118
     * Sets the pathToNames criterion. The {@code X509Certificate} must
D
duke 已提交
1119 1120 1121 1122
     * not include name constraints that would prohibit building a
     * path to the specified names.
     * <p>
     * This method allows the caller to specify, with a single method call,
1123
     * the complete set of names which the {@code X509Certificates}'s
D
duke 已提交
1124 1125 1126 1127 1128 1129 1130 1131
     * name constraints must permit. The specified value replaces
     * the previous value for the pathToNames criterion.
     * <p>
     * This constraint is useful when building a certification path forward
     * (from the target toward the trust anchor. If a partial path has been
     * built, any candidate certificate must not include name constraints that
     * would prohibit building a path to any of the names in the partial path.
     * <p>
1132 1133
     * The {@code names} parameter (if not {@code null}) is a
     * {@code Collection} with one
D
duke 已提交
1134
     * entry for each name to be included in the pathToNames
1135 1136 1137
     * criterion. Each entry is a {@code List} whose first entry is an
     * {@code Integer} (the name type, 0-8) and whose second
     * entry is a {@code String} or a byte array (the name, in
D
duke 已提交
1138
     * string or ASN.1 DER encoded form, respectively).
1139
     * There can be multiple names of the same type. If {@code null}
D
duke 已提交
1140 1141 1142
     * is supplied as the value for this argument, no
     * pathToNames check will be performed.
     * <p>
1143 1144
     * Each name in the {@code Collection}
     * may be specified either as a {@code String} or as an ASN.1 encoded
D
duke 已提交
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
     * byte array. For more details about the formats used, see
     * {@link #addPathToName(int type, String name)
     * addPathToName(int type, String name)} and
     * {@link #addPathToName(int type, byte [] name)
     * addPathToName(int type, byte [] name)}.
     * <p>
     * <strong>Note:</strong> for distinguished names, specify the byte
     * array form instead of the String form. See the note in
     * {@link #addPathToName(int, String)} for more information.
     * <p>
1155
     * Note that the {@code names} parameter can contain duplicate
D
duke 已提交
1156
     * names (same name and name type), but they may be removed from the
1157
     * {@code Collection} of names returned by the
D
duke 已提交
1158 1159
     * {@link #getPathToNames getPathToNames} method.
     * <p>
1160
     * Note that a deep copy is performed on the {@code Collection} to
D
duke 已提交
1161 1162
     * protect against subsequent modifications.
     *
1163 1164
     * @param names a {@code Collection} with one entry per name
     *              (or {@code null})
D
duke 已提交
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
     * @throws IOException if a parsing error occurs
     * @see #getPathToNames
     */
    public void setPathToNames(Collection<List<?>> names) throws IOException {
        if ((names == null) || names.isEmpty()) {
            pathToNames = null;
            pathToGeneralNames = null;
        } else {
            Set<List<?>> tempNames = cloneAndCheckNames(names);
            pathToGeneralNames = parseNames(tempNames);
            // Ensure that we either set both of these or neither
            pathToNames = tempNames;
        }
    }

    // called from CertPathHelper
    void setPathToNamesInternal(Set<GeneralNameInterface> names) {
        // set names to non-null dummy value
        // this breaks getPathToNames()
        pathToNames = Collections.<List<?>>emptySet();
        pathToGeneralNames = names;
    }

    /**
1189
     * Adds a name to the pathToNames criterion. The {@code X509Certificate}
D
duke 已提交
1190 1191 1192 1193
     * must not include name constraints that would prohibit building a
     * path to the specified name.
     * <p>
     * This method allows the caller to add a name to the set of names which
1194
     * the {@code X509Certificates}'s name constraints must permit.
D
duke 已提交
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
     * The specified name is added to any previous value for the
     * pathToNames criterion.  If the name is a duplicate, it may be ignored.
     * <p>
     * The name is provided in string format. RFC 822, DNS, and URI names
     * use the well-established string formats for those types (subject to
     * the restrictions included in RFC 3280). IPv4 address names are
     * supplied using dotted quad notation. OID address names are represented
     * as a series of nonnegative integers separated by periods. And
     * directory names (distinguished names) are supplied in RFC 2253 format.
     * No standard string format is defined for otherNames, X.400 names,
     * EDI party names, IPv6 address names, or any other type of names. They
     * should be specified using the
     * {@link #addPathToName(int type, byte [] name)
     * addPathToName(int type, byte [] name)} method.
     * <p>
     * <strong>Note:</strong> for distinguished names, use
     * {@linkplain #addPathToName(int, byte[])} instead.
     * This method should not be relied on as it can fail to match some
     * certificates because of a loss of encoding information in the RFC 2253
     * String form of some distinguished names.
     *
     * @param type the name type (0-8, as specified in
     *             RFC 3280, section 4.2.1.7)
     * @param name the name in string form
     * @throws IOException if a parsing error occurs
     */
    public void addPathToName(int type, String name) throws IOException {
        addPathToNameInternal(type, name);
    }

    /**
1226
     * Adds a name to the pathToNames criterion. The {@code X509Certificate}
D
duke 已提交
1227 1228 1229 1230
     * must not include name constraints that would prohibit building a
     * path to the specified name.
     * <p>
     * This method allows the caller to add a name to the set of names which
1231
     * the {@code X509Certificates}'s name constraints must permit.
D
duke 已提交
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
     * The specified name is added to any previous value for the
     * pathToNames criterion. If the name is a duplicate, it may be ignored.
     * <p>
     * The name is provided as a byte array. This byte array should contain
     * the DER encoded name, as it would appear in the GeneralName structure
     * defined in RFC 3280 and X.509. The ASN.1 definition of this structure
     * appears in the documentation for
     * {@link #addSubjectAlternativeName(int type, byte [] name)
     * addSubjectAlternativeName(int type, byte [] name)}.
     * <p>
     * Note that the byte array supplied here is cloned to protect against
     * subsequent modifications.
     *
     * @param type the name type (0-8, as specified in
     *             RFC 3280, section 4.2.1.7)
     * @param name a byte array containing the name in ASN.1 DER encoded form
     * @throws IOException if a parsing error occurs
     */
    public void addPathToName(int type, byte [] name) throws IOException {
        // clone because byte arrays are modifiable
        addPathToNameInternal(type, name.clone());
    }

    /**
     * A private method that adds a name (String or byte array) to the
1257
     * pathToNames criterion. The {@code X509Certificate} must contain
D
duke 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
     * the specified pathToName.
     *
     * @param type the name type (0-8, as specified in
     *             RFC 3280, section 4.2.1.7)
     * @param name the name in string or byte array form
     * @throws IOException if an encoding error occurs (incorrect form for DN)
     */
    private void addPathToNameInternal(int type, Object name)
            throws IOException {
        // First, ensure that the name parses
        GeneralNameInterface tempName = makeGeneralNameInterface(type, name);
        if (pathToGeneralNames == null) {
            pathToNames = new HashSet<List<?>>();
            pathToGeneralNames = new HashSet<GeneralNameInterface>();
        }
        List<Object> list = new ArrayList<Object>(2);
        list.add(Integer.valueOf(type));
        list.add(name);
        pathToNames.add(list);
        pathToGeneralNames.add(tempName);
    }

    /**
     * Returns the certificateEquals criterion. The specified
1282 1283 1284
     * {@code X509Certificate} must be equal to the
     * {@code X509Certificate} passed to the {@code match} method.
     * If {@code null}, this check is not applied.
D
duke 已提交
1285
     *
1286
     * @return the {@code X509Certificate} to match (or {@code null})
D
duke 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295
     * @see #setCertificate
     */
    public X509Certificate getCertificate() {
        return x509Cert;
    }

    /**
     * Returns the serialNumber criterion. The specified serial number
     * must match the certificate serial number in the
1296
     * {@code X509Certificate}. If {@code null}, any certificate
D
duke 已提交
1297 1298 1299
     * serial number will do.
     *
     * @return the certificate serial number to match
1300
     *                (or {@code null})
D
duke 已提交
1301 1302 1303 1304 1305 1306 1307
     * @see #setSerialNumber
     */
    public BigInteger getSerialNumber() {
        return serialNumber;
    }

    /**
1308
     * Returns the issuer criterion as an {@code X500Principal}. This
D
duke 已提交
1309
     * distinguished name must match the issuer distinguished name in the
1310
     * {@code X509Certificate}. If {@code null}, the issuer criterion
D
duke 已提交
1311 1312 1313
     * is disabled and any issuer distinguished name will do.
     *
     * @return the required issuer distinguished name as X500Principal
1314
     *         (or {@code null})
D
duke 已提交
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
     * @since 1.5
     */
    public X500Principal getIssuer() {
        return issuer;
    }

    /**
     * <strong>Denigrated</strong>, use {@linkplain #getIssuer()} or
     * {@linkplain #getIssuerAsBytes()} instead. This method should not be
     * relied on as it can fail to match some certificates because of a loss of
     * encoding information in the RFC 2253 String form of some distinguished
     * names.
     * <p>
1328
     * Returns the issuer criterion as a {@code String}. This
D
duke 已提交
1329
     * distinguished name must match the issuer distinguished name in the
1330
     * {@code X509Certificate}. If {@code null}, the issuer criterion
D
duke 已提交
1331 1332
     * is disabled and any issuer distinguished name will do.
     * <p>
1333
     * If the value returned is not {@code null}, it is a
D
duke 已提交
1334 1335 1336
     * distinguished name, in RFC 2253 format.
     *
     * @return the required issuer distinguished name in RFC 2253 format
1337
     *         (or {@code null})
D
duke 已提交
1338 1339 1340 1341 1342 1343 1344 1345
     */
    public String getIssuerAsString() {
        return (issuer == null ? null : issuer.getName());
    }

    /**
     * Returns the issuer criterion as a byte array. This distinguished name
     * must match the issuer distinguished name in the
1346
     * {@code X509Certificate}. If {@code null}, the issuer criterion
D
duke 已提交
1347 1348
     * is disabled and any issuer distinguished name will do.
     * <p>
1349
     * If the value returned is not {@code null}, it is a byte
D
duke 已提交
1350 1351 1352 1353 1354 1355 1356 1357 1358
     * array containing a single DER encoded distinguished name, as defined in
     * X.501. The ASN.1 notation for this structure is supplied in the
     * documentation for
     * {@link #setIssuer(byte [] issuerDN) setIssuer(byte [] issuerDN)}.
     * <p>
     * Note that the byte array returned is cloned to protect against
     * subsequent modifications.
     *
     * @return a byte array containing the required issuer distinguished name
1359
     *         in ASN.1 DER format (or {@code null})
D
duke 已提交
1360 1361 1362 1363 1364 1365 1366
     * @throws IOException if an encoding error occurs
     */
    public byte[] getIssuerAsBytes() throws IOException {
        return (issuer == null ? null: issuer.getEncoded());
    }

    /**
1367
     * Returns the subject criterion as an {@code X500Principal}. This
D
duke 已提交
1368
     * distinguished name must match the subject distinguished name in the
1369
     * {@code X509Certificate}. If {@code null}, the subject criterion
D
duke 已提交
1370 1371 1372
     * is disabled and any subject distinguished name will do.
     *
     * @return the required subject distinguished name as X500Principal
1373
     *         (or {@code null})
D
duke 已提交
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
     * @since 1.5
     */
    public X500Principal getSubject() {
        return subject;
    }

    /**
     * <strong>Denigrated</strong>, use {@linkplain #getSubject()} or
     * {@linkplain #getSubjectAsBytes()} instead. This method should not be
     * relied on as it can fail to match some certificates because of a loss of
     * encoding information in the RFC 2253 String form of some distinguished
     * names.
     * <p>
1387
     * Returns the subject criterion as a {@code String}. This
D
duke 已提交
1388
     * distinguished name must match the subject distinguished name in the
1389
     * {@code X509Certificate}. If {@code null}, the subject criterion
D
duke 已提交
1390 1391
     * is disabled and any subject distinguished name will do.
     * <p>
1392
     * If the value returned is not {@code null}, it is a
D
duke 已提交
1393 1394 1395
     * distinguished name, in RFC 2253 format.
     *
     * @return the required subject distinguished name in RFC 2253 format
1396
     *         (or {@code null})
D
duke 已提交
1397 1398 1399 1400 1401 1402 1403 1404
     */
    public String getSubjectAsString() {
        return (subject == null ? null : subject.getName());
    }

    /**
     * Returns the subject criterion as a byte array. This distinguished name
     * must match the subject distinguished name in the
1405
     * {@code X509Certificate}. If {@code null}, the subject criterion
D
duke 已提交
1406 1407
     * is disabled and any subject distinguished name will do.
     * <p>
1408
     * If the value returned is not {@code null}, it is a byte
D
duke 已提交
1409 1410 1411 1412 1413 1414 1415 1416 1417
     * array containing a single DER encoded distinguished name, as defined in
     * X.501. The ASN.1 notation for this structure is supplied in the
     * documentation for
     * {@link #setSubject(byte [] subjectDN) setSubject(byte [] subjectDN)}.
     * <p>
     * Note that the byte array returned is cloned to protect against
     * subsequent modifications.
     *
     * @return a byte array containing the required subject distinguished name
1418
     *         in ASN.1 DER format (or {@code null})
D
duke 已提交
1419 1420 1421 1422 1423 1424 1425 1426
     * @throws IOException if an encoding error occurs
     */
    public byte[] getSubjectAsBytes() throws IOException {
        return (subject == null ? null : subject.getEncoded());
    }

    /**
     * Returns the subjectKeyIdentifier criterion. The
1427 1428
     * {@code X509Certificate} must contain a SubjectKeyIdentifier
     * extension with the specified value. If {@code null}, no
D
duke 已提交
1429 1430 1431 1432 1433
     * subjectKeyIdentifier check will be done.
     * <p>
     * Note that the byte array returned is cloned to protect against
     * subsequent modifications.
     *
1434
     * @return the key identifier (or {@code null})
D
duke 已提交
1435 1436 1437 1438 1439 1440
     * @see #setSubjectKeyIdentifier
     */
    public byte[] getSubjectKeyIdentifier() {
        if (subjectKeyID == null) {
            return null;
        }
1441
        return subjectKeyID.clone();
D
duke 已提交
1442 1443 1444 1445
    }

    /**
     * Returns the authorityKeyIdentifier criterion. The
1446 1447
     * {@code X509Certificate} must contain a AuthorityKeyIdentifier
     * extension with the specified value. If {@code null}, no
D
duke 已提交
1448 1449 1450 1451 1452
     * authorityKeyIdentifier check will be done.
     * <p>
     * Note that the byte array returned is cloned to protect against
     * subsequent modifications.
     *
1453
     * @return the key identifier (or {@code null})
D
duke 已提交
1454 1455 1456 1457 1458 1459
     * @see #setAuthorityKeyIdentifier
     */
    public byte[] getAuthorityKeyIdentifier() {
        if (authorityKeyID == null) {
          return null;
        }
1460
        return authorityKeyID.clone();
D
duke 已提交
1461 1462 1463 1464 1465
    }

    /**
     * Returns the certificateValid criterion. The specified date must fall
     * within the certificate validity period for the
1466
     * {@code X509Certificate}. If {@code null}, no certificateValid
D
duke 已提交
1467 1468
     * check will be done.
     * <p>
1469
     * Note that the {@code Date} returned is cloned to protect against
D
duke 已提交
1470 1471
     * subsequent modifications.
     *
1472
     * @return the {@code Date} to check (or {@code null})
D
duke 已提交
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
     * @see #setCertificateValid
     */
    public Date getCertificateValid() {
        if (certificateValid == null) {
            return null;
        }
        return (Date)certificateValid.clone();
    }

    /**
     * Returns the privateKeyValid criterion. The specified date must fall
     * within the private key validity period for the
1485
     * {@code X509Certificate}. If {@code null}, no privateKeyValid
D
duke 已提交
1486 1487
     * check will be done.
     * <p>
1488
     * Note that the {@code Date} returned is cloned to protect against
D
duke 已提交
1489 1490
     * subsequent modifications.
     *
1491
     * @return the {@code Date} to check (or {@code null})
D
duke 已提交
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
     * @see #setPrivateKeyValid
     */
    public Date getPrivateKeyValid() {
        if (privateKeyValid == null) {
            return null;
        }
        return (Date)privateKeyValid.clone();
    }

    /**
     * Returns the subjectPublicKeyAlgID criterion. The
1503 1504
     * {@code X509Certificate} must contain a subject public key
     * with the specified algorithm. If {@code null}, no
D
duke 已提交
1505 1506 1507
     * subjectPublicKeyAlgID check will be done.
     *
     * @return the object identifier (OID) of the signature algorithm to check
1508
     *         for (or {@code null}). An OID is represented by a set of
D
duke 已提交
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
     *         nonnegative integers separated by periods.
     * @see #setSubjectPublicKeyAlgID
     */
    public String getSubjectPublicKeyAlgID() {
        if (subjectPublicKeyAlgID == null) {
            return null;
        }
        return subjectPublicKeyAlgID.toString();
    }

    /**
     * Returns the subjectPublicKey criterion. The
1521 1522
     * {@code X509Certificate} must contain the specified subject
     * public key. If {@code null}, no subjectPublicKey check will be done.
D
duke 已提交
1523
     *
1524
     * @return the subject public key to check for (or {@code null})
D
duke 已提交
1525 1526 1527 1528 1529 1530 1531
     * @see #setSubjectPublicKey
     */
    public PublicKey getSubjectPublicKey() {
        return subjectPublicKey;
    }

    /**
1532
     * Returns the keyUsage criterion. The {@code X509Certificate}
D
duke 已提交
1533 1534 1535 1536 1537 1538 1539 1540 1541
     * must allow the specified keyUsage values. If null, no keyUsage
     * check will be done.
     * <p>
     * Note that the boolean array returned is cloned to protect against
     * subsequent modifications.
     *
     * @return a boolean array in the same format as the boolean
     *                 array returned by
     * {@link X509Certificate#getKeyUsage() X509Certificate.getKeyUsage()}.
1542
     *                 Or {@code null}.
D
duke 已提交
1543 1544 1545 1546 1547 1548
     * @see #setKeyUsage
     */
    public boolean[] getKeyUsage() {
        if (keyUsage == null) {
            return null;
        }
1549
        return keyUsage.clone();
D
duke 已提交
1550 1551 1552
    }

    /**
1553
     * Returns the extendedKeyUsage criterion. The {@code X509Certificate}
D
duke 已提交
1554
     * must allow the specified key purposes in its extended key usage
1555 1556 1557
     * extension. If the {@code keyPurposeSet} returned is empty or
     * {@code null}, no extendedKeyUsage check will be done. Note that an
     * {@code X509Certificate} that has no extendedKeyUsage extension
D
duke 已提交
1558 1559
     * implicitly allows all key purposes.
     *
1560 1561
     * @return an immutable {@code Set} of key purpose OIDs in string
     * format (or {@code null})
D
duke 已提交
1562 1563 1564 1565 1566 1567 1568
     * @see #setExtendedKeyUsage
     */
    public Set<String> getExtendedKeyUsage() {
        return keyPurposeSet;
    }

    /**
1569
     * Indicates if the {@code X509Certificate} must contain all
D
duke 已提交
1570 1571 1572
     * or at least one of the subjectAlternativeNames
     * specified in the {@link #setSubjectAlternativeNames
     * setSubjectAlternativeNames} or {@link #addSubjectAlternativeName
1573 1574 1575 1576
     * addSubjectAlternativeName} methods. If {@code true},
     * the {@code X509Certificate} must contain all of the
     * specified subject alternative names. If {@code false}, the
     * {@code X509Certificate} must contain at least one of the
D
duke 已提交
1577 1578
     * specified subject alternative names.
     *
1579 1580 1581
     * @return {@code true} if the flag is enabled;
     * {@code false} if the flag is disabled. The flag is
     * {@code true} by default.
D
duke 已提交
1582 1583 1584 1585 1586 1587 1588 1589
     * @see #setMatchAllSubjectAltNames
     */
    public boolean getMatchAllSubjectAltNames() {
        return matchAllSubjectAltNames;
    }

    /**
     * Returns a copy of the subjectAlternativeNames criterion.
1590
     * The {@code X509Certificate} must contain all or at least one
D
duke 已提交
1591 1592 1593
     * of the specified subjectAlternativeNames, depending on the value
     * of the matchAllNames flag (see {@link #getMatchAllSubjectAltNames
     * getMatchAllSubjectAltNames}). If the value returned is
1594
     * {@code null}, no subjectAlternativeNames check will be performed.
D
duke 已提交
1595
     * <p>
1596 1597
     * If the value returned is not {@code null}, it is a
     * {@code Collection} with
D
duke 已提交
1598
     * one entry for each name to be included in the subject alternative name
1599 1600 1601
     * criterion. Each entry is a {@code List} whose first entry is an
     * {@code Integer} (the name type, 0-8) and whose second
     * entry is a {@code String} or a byte array (the name, in
D
duke 已提交
1602 1603
     * string or ASN.1 DER encoded form, respectively).
     * There can be multiple names of the same type.  Note that the
1604
     * {@code Collection} returned may contain duplicate names (same name
D
duke 已提交
1605 1606
     * and name type).
     * <p>
1607 1608
     * Each subject alternative name in the {@code Collection}
     * may be specified either as a {@code String} or as an ASN.1 encoded
D
duke 已提交
1609 1610 1611 1612 1613 1614
     * byte array. For more details about the formats used, see
     * {@link #addSubjectAlternativeName(int type, String name)
     * addSubjectAlternativeName(int type, String name)} and
     * {@link #addSubjectAlternativeName(int type, byte [] name)
     * addSubjectAlternativeName(int type, byte [] name)}.
     * <p>
1615
     * Note that a deep copy is performed on the {@code Collection} to
D
duke 已提交
1616 1617
     * protect against subsequent modifications.
     *
1618
     * @return a {@code Collection} of names (or {@code null})
D
duke 已提交
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
     * @see #setSubjectAlternativeNames
     */
    public Collection<List<?>> getSubjectAlternativeNames() {
        if (subjectAlternativeNames == null) {
            return null;
        }
        return cloneNames(subjectAlternativeNames);
    }

    /**
     * Clone an object of the form passed to
     * setSubjectAlternativeNames and setPathToNames.
1631
     * Throw a {@code RuntimeException} if the argument is malformed.
D
duke 已提交
1632 1633
     * <p>
     * This method wraps cloneAndCheckNames, changing any
1634
     * {@code IOException} into a {@code RuntimeException}. This
D
duke 已提交
1635 1636 1637
     * method should be used when the object being
     * cloned has already been checked, so there should never be any exceptions.
     *
1638 1639
     * @param names a {@code Collection} with one entry per name.
     *              Each entry is a {@code List} whose first entry
D
duke 已提交
1640 1641 1642 1643 1644
     *              is an Integer (the name type, 0-8) and whose second
     *              entry is a String or a byte array (the name, in
     *              string or ASN.1 DER encoded form, respectively).
     *              There can be multiple names of the same type. Null
     *              is not an acceptable value.
1645
     * @return a deep copy of the specified {@code Collection}
D
duke 已提交
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
     * @throws RuntimeException if a parsing error occurs
     */
    private static Set<List<?>> cloneNames(Collection<List<?>> names) {
        try {
            return cloneAndCheckNames(names);
        } catch (IOException e) {
            throw new RuntimeException("cloneNames encountered IOException: " +
                                       e.getMessage());
        }
    }

    /**
     * Clone and check an argument of the form passed to
     * setSubjectAlternativeNames and setPathToNames.
1660
     * Throw an {@code IOException} if the argument is malformed.
D
duke 已提交
1661
     *
1662 1663
     * @param names a {@code Collection} with one entry per name.
     *              Each entry is a {@code List} whose first entry
D
duke 已提交
1664 1665 1666 1667
     *              is an Integer (the name type, 0-8) and whose second
     *              entry is a String or a byte array (the name, in
     *              string or ASN.1 DER encoded form, respectively).
     *              There can be multiple names of the same type.
1668 1669
     *              {@code null} is not an acceptable value.
     * @return a deep copy of the specified {@code Collection}
D
duke 已提交
1670 1671 1672 1673 1674
     * @throws IOException if a parsing error occurs
     */
    private static Set<List<?>> cloneAndCheckNames(Collection<List<?>> names) throws IOException {
        // Copy the Lists and Collection
        Set<List<?>> namesCopy = new HashSet<List<?>>();
1675 1676 1677
        for (List<?> o : names)
        {
            namesCopy.add(new ArrayList<Object>(o));
D
duke 已提交
1678 1679 1680
        }

        // Check the contents of the Lists and clone any byte arrays
1681 1682 1683
        for (List<?> list : namesCopy) {
            @SuppressWarnings("unchecked") // See javadoc for parameter "names".
            List<Object> nameList = (List<Object>)list;
D
duke 已提交
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
            if (nameList.size() != 2) {
                throw new IOException("name list size not 2");
            }
            Object o = nameList.get(0);
            if (!(o instanceof Integer)) {
                throw new IOException("expected an Integer");
            }
            int nameType = ((Integer)o).intValue();
            if ((nameType < 0) || (nameType > 8)) {
                throw new IOException("name type not 0-8");
            }
            Object nameObject = nameList.get(1);
            if (!(nameObject instanceof byte[]) &&
                !(nameObject instanceof String)) {
                if (debug != null) {
                    debug.println("X509CertSelector.cloneAndCheckNames() "
                        + "name not byte array");
                }
                throw new IOException("name not byte array or String");
            }
            if (nameObject instanceof byte[]) {
                nameList.set(1, ((byte[]) nameObject).clone());
            }
        }
        return namesCopy;
    }

    /**
1712
     * Returns the name constraints criterion. The {@code X509Certificate}
D
duke 已提交
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
     * must have subject and subject alternative names that
     * meet the specified name constraints.
     * <p>
     * The name constraints are returned as a byte array. This byte array
     * contains the DER encoded form of the name constraints, as they
     * would appear in the NameConstraints structure defined in RFC 3280
     * and X.509. The ASN.1 notation for this structure is supplied in the
     * documentation for
     * {@link #setNameConstraints(byte [] bytes) setNameConstraints(byte [] bytes)}.
     * <p>
     * Note that the byte array returned is cloned to protect against
     * subsequent modifications.
     *
     * @return a byte array containing the ASN.1 DER encoding of
     *         a NameConstraints extension used for checking name constraints.
1728
     *         {@code null} if no name constraints check will be performed.
D
duke 已提交
1729 1730 1731 1732 1733 1734
     * @see #setNameConstraints
     */
    public byte[] getNameConstraints() {
        if (ncBytes == null) {
            return null;
        } else {
1735
            return ncBytes.clone();
D
duke 已提交
1736 1737 1738 1739 1740
        }
    }

    /**
     * Returns the basic constraints constraint. If the value is greater than
1741
     * or equal to zero, the {@code X509Certificates} must include a
D
duke 已提交
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
     * basicConstraints extension with a pathLen of at least this value.
     * If the value is -2, only end-entity certificates are accepted. If
     * the value is -1, no basicConstraints check is done.
     *
     * @return the value for the basic constraints constraint
     * @see #setBasicConstraints
     */
    public int getBasicConstraints() {
        return basicConstraints;
    }

    /**
1754
     * Returns the policy criterion. The {@code X509Certificate} must
D
duke 已提交
1755
     * include at least one of the specified policies in its certificate policies
1756 1757 1758 1759
     * extension. If the {@code Set} returned is empty, then the
     * {@code X509Certificate} must include at least some specified policy
     * in its certificate policies extension. If the {@code Set} returned is
     * {@code null}, no policy check will be performed.
D
duke 已提交
1760
     *
1761 1762
     * @return an immutable {@code Set} of certificate policy OIDs in
     *         string format (or {@code null})
D
duke 已提交
1763 1764 1765 1766 1767 1768 1769 1770
     * @see #setPolicy
     */
    public Set<String> getPolicy() {
        return policySet;
    }

    /**
     * Returns a copy of the pathToNames criterion. The
1771
     * {@code X509Certificate} must not include name constraints that would
D
duke 已提交
1772
     * prohibit building a path to the specified names. If the value
1773
     * returned is {@code null}, no pathToNames check will be performed.
D
duke 已提交
1774
     * <p>
1775 1776
     * If the value returned is not {@code null}, it is a
     * {@code Collection} with one
D
duke 已提交
1777
     * entry for each name to be included in the pathToNames
1778 1779 1780
     * criterion. Each entry is a {@code List} whose first entry is an
     * {@code Integer} (the name type, 0-8) and whose second
     * entry is a {@code String} or a byte array (the name, in
D
duke 已提交
1781 1782
     * string or ASN.1 DER encoded form, respectively).
     * There can be multiple names of the same type. Note that the
1783
     * {@code Collection} returned may contain duplicate names (same
D
duke 已提交
1784 1785
     * name and name type).
     * <p>
1786 1787
     * Each name in the {@code Collection}
     * may be specified either as a {@code String} or as an ASN.1 encoded
D
duke 已提交
1788 1789 1790 1791 1792 1793
     * byte array. For more details about the formats used, see
     * {@link #addPathToName(int type, String name)
     * addPathToName(int type, String name)} and
     * {@link #addPathToName(int type, byte [] name)
     * addPathToName(int type, byte [] name)}.
     * <p>
1794
     * Note that a deep copy is performed on the {@code Collection} to
D
duke 已提交
1795 1796
     * protect against subsequent modifications.
     *
1797
     * @return a {@code Collection} of names (or {@code null})
D
duke 已提交
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
     * @see #setPathToNames
     */
    public Collection<List<?>> getPathToNames() {
        if (pathToNames == null) {
            return null;
        }
        return cloneNames(pathToNames);
    }

    /**
1808
     * Return a printable representation of the {@code CertSelector}.
D
duke 已提交
1809
     *
1810 1811
     * @return a {@code String} describing the contents of the
     *         {@code CertSelector}
D
duke 已提交
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
     */
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("X509CertSelector: [\n");
        if (x509Cert != null) {
            sb.append("  Certificate: " + x509Cert.toString() + "\n");
        }
        if (serialNumber != null) {
            sb.append("  Serial Number: " + serialNumber.toString() + "\n");
        }
        if (issuer != null) {
            sb.append("  Issuer: " + getIssuerAsString() + "\n");
        }
        if (subject != null) {
            sb.append("  Subject: " + getSubjectAsString() + "\n");
        }
        sb.append("  matchAllSubjectAltNames flag: "
                  + String.valueOf(matchAllSubjectAltNames) + "\n");
        if (subjectAlternativeNames != null) {
            sb.append("  SubjectAlternativeNames:\n");
            Iterator<List<?>> i = subjectAlternativeNames.iterator();
            while (i.hasNext()) {
                List<?> list = i.next();
                sb.append("    type " + list.get(0) +
                          ", name " + list.get(1) + "\n");
            }
        }
        if (subjectKeyID != null) {
            HexDumpEncoder enc = new HexDumpEncoder();
            sb.append("  Subject Key Identifier: " +
                      enc.encodeBuffer(subjectKeyID) + "\n");
        }
        if (authorityKeyID != null) {
            HexDumpEncoder enc = new HexDumpEncoder();
            sb.append("  Authority Key Identifier: " +
                      enc.encodeBuffer(authorityKeyID) + "\n");
        }
        if (certificateValid != null) {
            sb.append("  Certificate Valid: " +
                      certificateValid.toString() + "\n");
        }
        if (privateKeyValid != null) {
            sb.append("  Private Key Valid: " +
                      privateKeyValid.toString() + "\n");
        }
        if (subjectPublicKeyAlgID != null) {
            sb.append("  Subject Public Key AlgID: " +
                      subjectPublicKeyAlgID.toString() + "\n");
        }
        if (subjectPublicKey != null) {
            sb.append("  Subject Public Key: " +
                      subjectPublicKey.toString() + "\n");
        }
        if (keyUsage != null) {
            sb.append("  Key Usage: " + keyUsageToString(keyUsage) + "\n");
        }
        if (keyPurposeSet != null) {
            sb.append("  Extended Key Usage: " +
                      keyPurposeSet.toString() + "\n");
        }
        if (policy != null) {
            sb.append("  Policy: " + policy.toString() + "\n");
        }
        if (pathToGeneralNames != null) {
            sb.append("  Path to names:\n");
            Iterator<GeneralNameInterface> i = pathToGeneralNames.iterator();
            while (i.hasNext()) {
                sb.append("    " + i.next() + "\n");
            }
        }
        sb.append("]");
        return sb.toString();
    }

    // Copied from sun.security.x509.KeyUsageExtension
    // (without calling the superclass)
    /**
     * Returns a printable representation of the KeyUsage.
     */
    private static String keyUsageToString(boolean[] k) {
        String s = "KeyUsage [\n";
        try {
            if (k[0]) {
                s += "  DigitalSignature\n";
            }
            if (k[1]) {
                s += "  Non_repudiation\n";
            }
            if (k[2]) {
                s += "  Key_Encipherment\n";
            }
            if (k[3]) {
                s += "  Data_Encipherment\n";
            }
            if (k[4]) {
                s += "  Key_Agreement\n";
            }
            if (k[5]) {
                s += "  Key_CertSign\n";
            }
            if (k[6]) {
                s += "  Crl_Sign\n";
            }
            if (k[7]) {
                s += "  Encipher_Only\n";
            }
            if (k[8]) {
                s += "  Decipher_Only\n";
            }
        } catch (ArrayIndexOutOfBoundsException ex) {}

        s += "]\n";

        return (s);
    }

    /**
     * Returns an Extension object given any X509Certificate and extension oid.
1930
     * Throw an {@code IOException} if the extension byte value is
D
duke 已提交
1931 1932
     * malformed.
     *
1933 1934
     * @param cert a {@code X509Certificate}
     * @param extId an {@code integer} which specifies the extension index.
D
duke 已提交
1935 1936 1937 1938 1939 1940
     * Currently, the supported extensions are as follows:
     * index 0 - PrivateKeyUsageExtension
     * index 1 - SubjectAlternativeNameExtension
     * index 2 - NameConstraintsExtension
     * index 3 - CertificatePoliciesExtension
     * index 4 - ExtendedKeyUsageExtension
1941
     * @return an {@code Extension} object whose real type is as specified
D
duke 已提交
1942
     * by the extension oid.
1943
     * @throws IOException if cannot construct the {@code Extension}
D
duke 已提交
1944
     * object with the extension encoding retrieved from the passed in
1945
     * {@code X509Certificate}.
D
duke 已提交
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
     */
    private static Extension getExtensionObject(X509Certificate cert, int extId)
            throws IOException {
        if (cert instanceof X509CertImpl) {
            X509CertImpl impl = (X509CertImpl)cert;
            switch (extId) {
            case PRIVATE_KEY_USAGE_ID:
                return impl.getPrivateKeyUsageExtension();
            case SUBJECT_ALT_NAME_ID:
                return impl.getSubjectAlternativeNameExtension();
            case NAME_CONSTRAINTS_ID:
                return impl.getNameConstraintsExtension();
            case CERT_POLICIES_ID:
                return impl.getCertificatePoliciesExtension();
            case EXTENDED_KEY_USAGE_ID:
                return impl.getExtendedKeyUsageExtension();
            default:
                return null;
            }
        }
        byte[] rawExtVal = cert.getExtensionValue(EXTENSION_OIDS[extId]);
        if (rawExtVal == null) {
            return null;
        }
        DerInputStream in = new DerInputStream(rawExtVal);
        byte[] encoded = in.getOctetString();
        switch (extId) {
        case PRIVATE_KEY_USAGE_ID:
            try {
                return new PrivateKeyUsageExtension(FALSE, encoded);
            } catch (CertificateException ex) {
                throw new IOException(ex.getMessage());
            }
        case SUBJECT_ALT_NAME_ID:
            return new SubjectAlternativeNameExtension(FALSE, encoded);
        case NAME_CONSTRAINTS_ID:
            return new NameConstraintsExtension(FALSE, encoded);
        case CERT_POLICIES_ID:
            return new CertificatePoliciesExtension(FALSE, encoded);
        case EXTENDED_KEY_USAGE_ID:
            return new ExtendedKeyUsageExtension(FALSE, encoded);
        default:
            return null;
        }
    }

    /**
1993
     * Decides whether a {@code Certificate} should be selected.
D
duke 已提交
1994
     *
1995 1996 1997
     * @param cert the {@code Certificate} to be checked
     * @return {@code true} if the {@code Certificate} should be
     *         selected, {@code false} otherwise
D
duke 已提交
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
     */
    public boolean match(Certificate cert) {
        if (!(cert instanceof X509Certificate)) {
            return false;
        }
        X509Certificate xcert = (X509Certificate)cert;

        if (debug != null) {
            debug.println("X509CertSelector.match(SN: "
                + (xcert.getSerialNumber()).toString(16) + "\n  Issuer: "
                + xcert.getIssuerDN() + "\n  Subject: " + xcert.getSubjectDN()
                + ")");
        }

        /* match on X509Certificate */
        if (x509Cert != null) {
            if (!x509Cert.equals(xcert)) {
                if (debug != null) {
                    debug.println("X509CertSelector.match: "
                        + "certs don't match");
                }
                return false;
            }
        }

        /* match on serial number */
        if (serialNumber != null) {
            if (!serialNumber.equals(xcert.getSerialNumber())) {
                if (debug != null) {
                    debug.println("X509CertSelector.match: "
                        + "serial numbers don't match");
                }
                return false;
            }
        }

        /* match on issuer name */
        if (issuer != null) {
            if (!issuer.equals(xcert.getIssuerX500Principal())) {
                if (debug != null) {
                    debug.println("X509CertSelector.match: "
                        + "issuer DNs don't match");
                }
                return false;
            }
        }

        /* match on subject name */
        if (subject != null) {
            if (!subject.equals(xcert.getSubjectX500Principal())) {
                if (debug != null) {
                    debug.println("X509CertSelector.match: "
                        + "subject DNs don't match");
                }
                return false;
            }
        }

        /* match on certificate validity range */
        if (certificateValid != null) {
            try {
                xcert.checkValidity(certificateValid);
            } catch (CertificateException e) {
                if (debug != null) {
                    debug.println("X509CertSelector.match: "
                        + "certificate not within validity period");
                }
                return false;
            }
        }

        /* match on subject public key */
        if (subjectPublicKeyBytes != null) {
            byte[] certKey = xcert.getPublicKey().getEncoded();
            if (!Arrays.equals(subjectPublicKeyBytes, certKey)) {
                if (debug != null) {
                    debug.println("X509CertSelector.match: "
                        + "subject public keys don't match");
                }
                return false;
            }
        }

        boolean result = matchBasicConstraints(xcert)
                      && matchKeyUsage(xcert)
                      && matchExtendedKeyUsage(xcert)
                      && matchSubjectKeyID(xcert)
                      && matchAuthorityKeyID(xcert)
                      && matchPrivateKeyValid(xcert)
                      && matchSubjectPublicKeyAlgID(xcert)
                      && matchPolicy(xcert)
                      && matchSubjectAlternativeNames(xcert)
                      && matchPathToNames(xcert)
                      && matchNameConstraints(xcert);

        if (result && (debug != null)) {
            debug.println("X509CertSelector.match returning: true");
        }
        return result;
    }

    /* match on subject key identifier extension value */
    private boolean matchSubjectKeyID(X509Certificate xcert) {
        if (subjectKeyID == null) {
            return true;
        }
        try {
            byte[] extVal = xcert.getExtensionValue("2.5.29.14");
            if (extVal == null) {
                if (debug != null) {
                    debug.println("X509CertSelector.match: "
                        + "no subject key ID extension");
                }
                return false;
            }
            DerInputStream in = new DerInputStream(extVal);
            byte[] certSubjectKeyID = in.getOctetString();
            if (certSubjectKeyID == null ||
                    !Arrays.equals(subjectKeyID, certSubjectKeyID)) {
                if (debug != null) {
                    debug.println("X509CertSelector.match: "
                        + "subject key IDs don't match");
                }
                return false;
            }
        } catch (IOException ex) {
            if (debug != null) {
                debug.println("X509CertSelector.match: "
                    + "exception in subject key ID check");
            }
            return false;
        }
        return true;
    }

    /* match on authority key identifier extension value */
    private boolean matchAuthorityKeyID(X509Certificate xcert) {
        if (authorityKeyID == null) {
            return true;
        }
        try {
            byte[] extVal = xcert.getExtensionValue("2.5.29.35");
            if (extVal == null) {
                if (debug != null) {
                    debug.println("X509CertSelector.match: "
                        + "no authority key ID extension");
                }
                return false;
            }
            DerInputStream in = new DerInputStream(extVal);
            byte[] certAuthKeyID = in.getOctetString();
            if (certAuthKeyID == null ||
                    !Arrays.equals(authorityKeyID, certAuthKeyID)) {
                if (debug != null) {
                    debug.println("X509CertSelector.match: "
                        + "authority key IDs don't match");
                }
                return false;
            }
        } catch (IOException ex) {
            if (debug != null) {
                debug.println("X509CertSelector.match: "
                    + "exception in authority key ID check");
            }
            return false;
        }
        return true;
    }

    /* match on private key usage range */
    private boolean matchPrivateKeyValid(X509Certificate xcert) {
        if (privateKeyValid == null) {
            return true;
        }
        PrivateKeyUsageExtension ext = null;
        try {
            ext = (PrivateKeyUsageExtension)
                getExtensionObject(xcert, PRIVATE_KEY_USAGE_ID);
            if (ext != null) {
                ext.valid(privateKeyValid);
            }
        } catch (CertificateExpiredException e1) {
            if (debug != null) {
                String time = "n/a";
                try {
2183
                    Date notAfter = ext.get(PrivateKeyUsageExtension.NOT_AFTER);
D
duke 已提交
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
                    time = notAfter.toString();
                } catch (CertificateException ex) {
                    // not able to retrieve notAfter value
                }
                debug.println("X509CertSelector.match: private key usage not "
                    + "within validity date; ext.NOT_After: "
                    + time + "; X509CertSelector: "
                    + this.toString());
                e1.printStackTrace();
            }
            return false;
        } catch (CertificateNotYetValidException e2) {
            if (debug != null) {
                String time = "n/a";
                try {
2199
                    Date notBefore = ext.get(PrivateKeyUsageExtension.NOT_BEFORE);
D
duke 已提交
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
                    time = notBefore.toString();
                } catch (CertificateException ex) {
                    // not able to retrieve notBefore value
                }
                debug.println("X509CertSelector.match: private key usage not "
                    + "within validity date; ext.NOT_BEFORE: "
                    + time + "; X509CertSelector: "
                    + this.toString());
                e2.printStackTrace();
            }
            return false;
        } catch (IOException e4) {
            if (debug != null) {
                debug.println("X509CertSelector.match: IOException in "
                    + "private key usage check; X509CertSelector: "
                    + this.toString());
                e4.printStackTrace();
            }
            return false;
        }
        return true;
    }

    /* match on subject public key algorithm OID */
    private boolean matchSubjectPublicKeyAlgID(X509Certificate xcert) {
        if (subjectPublicKeyAlgID == null) {
            return true;
        }
        try {
            byte[] encodedKey = xcert.getPublicKey().getEncoded();
            DerValue val = new DerValue(encodedKey);
            if (val.tag != DerValue.tag_Sequence) {
                throw new IOException("invalid key format");
            }

            AlgorithmId algID = AlgorithmId.parse(val.data.getDerValue());
            if (debug != null) {
                debug.println("X509CertSelector.match: subjectPublicKeyAlgID = "
                    + subjectPublicKeyAlgID + ", xcert subjectPublicKeyAlgID = "
                    + algID.getOID());
            }
2241
            if (!subjectPublicKeyAlgID.equals((Object)algID.getOID())) {
D
duke 已提交
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
                if (debug != null) {
                    debug.println("X509CertSelector.match: "
                        + "subject public key alg IDs don't match");
                }
                return false;
            }
        } catch (IOException e5) {
            if (debug != null) {
                debug.println("X509CertSelector.match: IOException in subject "
                    + "public key algorithm OID check");
            }
            return false;
        }
        return true;
    }

    /* match on key usage extension value */
    private boolean matchKeyUsage(X509Certificate xcert) {
        if (keyUsage == null) {
            return true;
        }
        boolean[] certKeyUsage = xcert.getKeyUsage();
        if (certKeyUsage != null) {
            for (int keyBit = 0; keyBit < keyUsage.length; keyBit++) {
                if (keyUsage[keyBit] &&
                    ((keyBit >= certKeyUsage.length) || !certKeyUsage[keyBit])) {
                    if (debug != null) {
                        debug.println("X509CertSelector.match: "
                            + "key usage bits don't match");
                    }
                    return false;
                }
            }
        }
        return true;
    }

    /* match on extended key usage purpose OIDs */
    private boolean matchExtendedKeyUsage(X509Certificate xcert) {
        if ((keyPurposeSet == null) || keyPurposeSet.isEmpty()) {
            return true;
        }
        try {
            ExtendedKeyUsageExtension ext =
                (ExtendedKeyUsageExtension)getExtensionObject(xcert,
                                                EXTENDED_KEY_USAGE_ID);
            if (ext != null) {
                Vector<ObjectIdentifier> certKeyPurposeVector =
2290
                    ext.get(ExtendedKeyUsageExtension.USAGES);
D
duke 已提交
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
                if (!certKeyPurposeVector.contains(ANY_EXTENDED_KEY_USAGE)
                        && !certKeyPurposeVector.containsAll(keyPurposeOIDSet)) {
                    if (debug != null) {
                        debug.println("X509CertSelector.match: cert failed "
                            + "extendedKeyUsage criterion");
                    }
                    return false;
                }
            }
        } catch (IOException ex) {
            if (debug != null) {
                debug.println("X509CertSelector.match: "
                    + "IOException in extended key usage check");
            }
            return false;
        }
        return true;
    }

    /* match on subject alternative name extension names */
    private boolean matchSubjectAlternativeNames(X509Certificate xcert) {
        if ((subjectAlternativeNames == null) || subjectAlternativeNames.isEmpty()) {
            return true;
        }
        try {
            SubjectAlternativeNameExtension sanExt =
                (SubjectAlternativeNameExtension) getExtensionObject(xcert,
                                                      SUBJECT_ALT_NAME_ID);
            if (sanExt == null) {
                if (debug != null) {
                  debug.println("X509CertSelector.match: "
                      + "no subject alternative name extension");
                }
                return false;
            }
2326 2327
            GeneralNames certNames =
                    sanExt.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
D
duke 已提交
2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
            Iterator<GeneralNameInterface> i =
                                subjectAlternativeGeneralNames.iterator();
            while (i.hasNext()) {
                GeneralNameInterface matchName = i.next();
                boolean found = false;
                for (Iterator<GeneralName> t = certNames.iterator();
                                                t.hasNext() && !found; ) {
                    GeneralNameInterface certName = (t.next()).getName();
                    found = certName.equals(matchName);
                }
                if (!found && (matchAllSubjectAltNames || !i.hasNext())) {
                    if (debug != null) {
                      debug.println("X509CertSelector.match: subject alternative "
                          + "name " + matchName + " not found");
                    }
                    return false;
                } else if (found && !matchAllSubjectAltNames) {
                    break;
                }
            }
        } catch (IOException ex) {
            if (debug != null)
                debug.println("X509CertSelector.match: IOException in subject "
                    + "alternative name check");
            return false;
        }
        return true;
    }

    /* match on name constraints */
    private boolean matchNameConstraints(X509Certificate xcert) {
        if (nc == null) {
            return true;
        }
        try {
            if (!nc.verify(xcert)) {
                if (debug != null) {
                    debug.println("X509CertSelector.match: "
                        + "name constraints not satisfied");
                }
                return false;
            }
        } catch (IOException e) {
            if (debug != null) {
                debug.println("X509CertSelector.match: "
                    + "IOException in name constraints check");
            }
            return false;
        }
        return true;
    }

    /* match on policy OIDs */
    private boolean matchPolicy(X509Certificate xcert) {
        if (policy == null) {
            return true;
        }
        try {
            CertificatePoliciesExtension ext = (CertificatePoliciesExtension)
                getExtensionObject(xcert, CERT_POLICIES_ID);
            if (ext == null) {
                if (debug != null) {
                  debug.println("X509CertSelector.match: "
                      + "no certificate policy extension");
                }
                return false;
            }
2395
            List<PolicyInformation> policies = ext.get(CertificatePoliciesExtension.POLICIES);
D
duke 已提交
2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
            /*
             * Convert the Vector of PolicyInformation to a Vector
             * of CertificatePolicyIds for easier comparison.
             */
            List<CertificatePolicyId> policyIDs = new ArrayList<CertificatePolicyId>(policies.size());
            for (PolicyInformation info : policies) {
                policyIDs.add(info.getPolicyIdentifier());
            }
            if (policy != null) {
                boolean foundOne = false;
                /*
                 * if the user passes in an empty policy Set, then
                 * we just want to make sure that the candidate certificate
                 * has some policy OID in its CertPoliciesExtension
                 */
                if (policy.getCertPolicyIds().isEmpty()) {
                    if (policyIDs.isEmpty()) {
                        if (debug != null) {
                            debug.println("X509CertSelector.match: "
                                + "cert failed policyAny criterion");
                        }
                        return false;
                    }
                } else {
                    for (CertificatePolicyId id : policy.getCertPolicyIds()) {
                        if (policyIDs.contains(id)) {
                            foundOne = true;
                            break;
                        }
                    }
                    if (!foundOne) {
                        if (debug != null) {
                            debug.println("X509CertSelector.match: "
                                + "cert failed policyAny criterion");
                        }
                        return false;
                    }
                }
            }
        } catch (IOException ex) {
            if (debug != null) {
                debug.println("X509CertSelector.match: "
                    + "IOException in certificate policy ID check");
            }
            return false;
        }
        return true;
    }

    /* match on pathToNames */
    private boolean matchPathToNames(X509Certificate xcert) {
        if (pathToGeneralNames == null) {
            return true;
        }
        try {
            NameConstraintsExtension ext = (NameConstraintsExtension)
                getExtensionObject(xcert, NAME_CONSTRAINTS_ID);
            if (ext == null) {
                return true;
            }
2456
            if ((debug != null) && Debug.isOn("certpath")) {
D
duke 已提交
2457 2458 2459 2460 2461 2462 2463 2464
                debug.println("X509CertSelector.match pathToNames:\n");
                Iterator<GeneralNameInterface> i =
                                        pathToGeneralNames.iterator();
                while (i.hasNext()) {
                    debug.println("    " + i.next() + "\n");
                }
            }

2465 2466 2467 2468
            GeneralSubtrees permitted =
                    ext.get(NameConstraintsExtension.PERMITTED_SUBTREES);
            GeneralSubtrees excluded =
                    ext.get(NameConstraintsExtension.EXCLUDED_SUBTREES);
D
duke 已提交
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585
            if (excluded != null) {
                if (matchExcluded(excluded) == false) {
                    return false;
                }
            }
            if (permitted != null) {
                if (matchPermitted(permitted) == false) {
                    return false;
                }
            }
        } catch (IOException ex) {
            if (debug != null) {
                debug.println("X509CertSelector.match: "
                    + "IOException in name constraints check");
            }
            return false;
        }
        return true;
    }

    private boolean matchExcluded(GeneralSubtrees excluded) {
        /*
         * Enumerate through excluded and compare each entry
         * to all pathToNames. If any pathToName is within any of the
         * subtrees listed in excluded, return false.
         */
        for (Iterator<GeneralSubtree> t = excluded.iterator(); t.hasNext(); ) {
            GeneralSubtree tree = t.next();
            GeneralNameInterface excludedName = tree.getName().getName();
            Iterator<GeneralNameInterface> i = pathToGeneralNames.iterator();
            while (i.hasNext()) {
                GeneralNameInterface pathToName = i.next();
                if (excludedName.getType() == pathToName.getType()) {
                    switch (pathToName.constrains(excludedName)) {
                    case GeneralNameInterface.NAME_WIDENS:
                    case GeneralNameInterface.NAME_MATCH:
                        if (debug != null) {
                            debug.println("X509CertSelector.match: name constraints "
                                + "inhibit path to specified name");
                            debug.println("X509CertSelector.match: excluded name: " +
                                pathToName);
                        }
                        return false;
                    default:
                    }
                }
            }
        }
        return true;
    }

    private boolean matchPermitted(GeneralSubtrees permitted) {
        /*
         * Enumerate through pathToNames, checking that each pathToName
         * is in at least one of the subtrees listed in permitted.
         * If not, return false. However, if no subtrees of a given type
         * are listed, all names of that type are permitted.
         */
        Iterator<GeneralNameInterface> i = pathToGeneralNames.iterator();
        while (i.hasNext()) {
            GeneralNameInterface pathToName = i.next();
            Iterator<GeneralSubtree> t = permitted.iterator();
            boolean permittedNameFound = false;
            boolean nameTypeFound = false;
            String names = "";
            while (t.hasNext() && !permittedNameFound) {
                GeneralSubtree tree = t.next();
                GeneralNameInterface permittedName = tree.getName().getName();
                if (permittedName.getType() == pathToName.getType()) {
                    nameTypeFound = true;
                    names = names + "  " + permittedName;
                    switch (pathToName.constrains(permittedName)) {
                    case GeneralNameInterface.NAME_WIDENS:
                    case GeneralNameInterface.NAME_MATCH:
                        permittedNameFound = true;
                        break;
                    default:
                    }
                }
            }
            if (!permittedNameFound && nameTypeFound) {
                if (debug != null)
                  debug.println("X509CertSelector.match: " +
                            "name constraints inhibit path to specified name; " +
                            "permitted names of type " + pathToName.getType() +
                            ": " + names);
                return false;
            }
        }
        return true;
    }

    /* match on basic constraints */
    private boolean matchBasicConstraints(X509Certificate xcert) {
        if (basicConstraints == -1) {
            return true;
        }
        int maxPathLen = xcert.getBasicConstraints();
        if (basicConstraints == -2) {
            if (maxPathLen != -1) {
                if (debug != null) {
                    debug.println("X509CertSelector.match: not an EE cert");
                }
                return false;
            }
        } else {
            if (maxPathLen < basicConstraints) {
                if (debug != null) {
                    debug.println("X509CertSelector.match: maxPathLen too small ("
                        + maxPathLen + " < " + basicConstraints + ")");
                }
                return false;
            }
        }
        return true;
    }

2586 2587
    @SuppressWarnings("unchecked") // Safe casts assuming clone() works correctly
    private static <T> Set<T> cloneSet(Set<T> set) {
D
duke 已提交
2588
        if (set instanceof HashSet) {
2589 2590
            Object clone = ((HashSet<T>)set).clone();
            return (Set<T>)clone;
D
duke 已提交
2591
        } else {
2592
            return new HashSet<T>(set);
D
duke 已提交
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
        }
    }

    /**
     * Returns a copy of this object.
     *
     * @return the copy
     */
    public Object clone() {
        try {
            X509CertSelector copy = (X509CertSelector)super.clone();
            // Must clone these because addPathToName et al. modify them
            if (subjectAlternativeNames != null) {
                copy.subjectAlternativeNames =
2607
                        cloneSet(subjectAlternativeNames);
D
duke 已提交
2608
                copy.subjectAlternativeGeneralNames =
2609
                        cloneSet(subjectAlternativeGeneralNames);
D
duke 已提交
2610 2611
            }
            if (pathToGeneralNames != null) {
2612 2613
                copy.pathToNames = cloneSet(pathToNames);
                copy.pathToGeneralNames = cloneSet(pathToGeneralNames);
D
duke 已提交
2614 2615 2616 2617
            }
            return copy;
        } catch (CloneNotSupportedException e) {
            /* Cannot happen */
2618
            throw new InternalError(e.toString(), e);
D
duke 已提交
2619 2620 2621
        }
    }
}