Example #1
0
  private X509Certificate[] doBuild(X509Certificate[] chain, Collection otherCerts)
      throws CertificateException {
    try {
      PKIXBuilderParameters params = (PKIXBuilderParameters) parameterTemplate.clone();
      setDate(params);

      // setup target constraints
      X509CertSelector selector = new X509CertSelector();
      selector.setCertificate(chain[0]);
      params.setTargetCertConstraints(selector);

      // setup CertStores
      Collection certs = new ArrayList();
      certs.addAll(Arrays.asList(chain));
      if (otherCerts != null) {
        certs.addAll(otherCerts);
      }
      CertStore store =
          CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs));
      params.addCertStore(store);

      // do the build
      CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
      PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder.build(params);

      return toArray(result.getCertPath(), result.getTrustAnchor());
    } catch (GeneralSecurityException e) {
      throw new ValidatorException("PKIX path building failed: " + e.toString(), e);
    }
  }
  protected X509CertSelector doConversion(
      X500Name issuer, BigInteger serialNumber, byte[] subjectKeyIdentifier) {
    X509CertSelector selector = new X509CertSelector();

    if (issuer != null) {
      try {
        selector.setIssuer(issuer.getEncoded());
      } catch (IOException e) {
        throw new IllegalArgumentException("unable to convert issuer: " + e.getMessage());
      }
    }

    if (serialNumber != null) {
      selector.setSerialNumber(serialNumber);
    }

    if (subjectKeyIdentifier != null) {
      try {
        selector.setSubjectKeyIdentifier(new DEROctetString(subjectKeyIdentifier).getEncoded());
      } catch (IOException e) {
        throw new IllegalArgumentException("unable to convert issuer: " + e.getMessage());
      }
    }

    return selector;
  }
  /**
   * Search the given Set of TrustAnchor's for one that is the issuer of the given X509 certificate.
   * Uses the specified provider for signature verification, or the default provider if null.
   *
   * @param cert the X509 certificate
   * @param trustAnchors a Set of TrustAnchor's
   * @param sigProvider the provider to use for signature verification
   * @return the <code>TrustAnchor</code> object if found or <code>null</code> if not.
   * @throws AnnotatedException if a TrustAnchor was found but the signature verification on the
   *     given certificate has thrown an exception.
   */
  protected static TrustAnchor findTrustAnchor(
      X509Certificate cert, Set trustAnchors, String sigProvider) throws AnnotatedException {
    TrustAnchor trust = null;
    PublicKey trustPublicKey = null;
    Exception invalidKeyEx = null;

    X509CertSelector certSelectX509 = new X509CertSelector();
    X500Principal certIssuer = getEncodedIssuerPrincipal(cert);

    try {
      certSelectX509.setSubject(certIssuer.getEncoded());
    } catch (IOException ex) {
      throw new AnnotatedException("Cannot set subject search criteria for trust anchor.", ex);
    }

    Iterator iter = trustAnchors.iterator();
    while (iter.hasNext() && trust == null) {
      trust = (TrustAnchor) iter.next();
      if (trust.getTrustedCert() != null) {
        if (certSelectX509.match(trust.getTrustedCert())) {
          trustPublicKey = trust.getTrustedCert().getPublicKey();
        } else {
          trust = null;
        }
      } else if (trust.getCAName() != null && trust.getCAPublicKey() != null) {
        try {
          X500Principal caName = new X500Principal(trust.getCAName());
          if (certIssuer.equals(caName)) {
            trustPublicKey = trust.getCAPublicKey();
          } else {
            trust = null;
          }
        } catch (IllegalArgumentException ex) {
          trust = null;
        }
      } else {
        trust = null;
      }

      if (trustPublicKey != null) {
        try {
          verifyX509Certificate(cert, trustPublicKey, sigProvider);
        } catch (Exception ex) {
          invalidKeyEx = ex;
          trust = null;
          trustPublicKey = null;
        }
      }
    }

    if (trust == null && invalidKeyEx != null) {
      throw new AnnotatedException(
          "TrustAnchor found but certificate validation failed.", invalidKeyEx);
    }

    return trust;
  }
Example #4
0
  private void testExceptions() throws Exception {
    byte[] enc = {(byte) 0, (byte) 2, (byte) 3, (byte) 4, (byte) 5};
    MyCertPath mc = new MyCertPath(enc);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ByteArrayInputStream is;
    byte[] arr;

    ObjectOutputStream oOut = new ObjectOutputStream(os);
    oOut.writeObject(mc);
    oOut.flush();
    oOut.close();

    try {
      CertificateFactory cFac = CertificateFactory.getInstance("X.509", "BC");
      arr = os.toByteArray();
      is = new ByteArrayInputStream(arr);
      cFac.generateCertPath(is);
    } catch (CertificateException e) {
      // ignore okay
    }

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List certCol = new ArrayList();

    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certA)));
    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certB)));
    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certC)));
    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certD)));

    CertPathBuilder pathBuilder = CertPathBuilder.getInstance("PKIX", "BC");
    X509CertSelector select = new X509CertSelector();
    select.setSubject(((X509Certificate) certCol.get(0)).getSubjectX500Principal().getEncoded());

    Set trustanchors = new HashSet();
    trustanchors.add(
        new TrustAnchor(
            (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(rootCertBin)), null));

    CertStore certStore =
        CertStore.getInstance("Collection", new CollectionCertStoreParameters(certCol));

    PKIXBuilderParameters params = new PKIXBuilderParameters(trustanchors, select);
    params.addCertStore(certStore);

    try {
      CertPathBuilderResult result = pathBuilder.build(params);
      CertPath path = result.getCertPath();
      fail("found cert path in circular set");
    } catch (CertPathBuilderException e) {
      // expected
    }
  }
  /*
   * Retrieves all end-entity certificates which satisfy constraints
   * and requirements specified in the parameters and PKIX state.
   */
  private Collection getMatchingEECerts(ReverseState currentState)
      throws CertStoreException, CertificateException, IOException {

    /*
     * Compose a CertSelector to filter out
     * certs which do not satisfy requirements.
     *
     * First, retrieve clone of current target cert constraints,
     * and then add more selection criteria based on current validation state.
     */
    X509CertSelector sel = (X509CertSelector) buildParams.getTargetCertConstraints();

    /*
     * Match on issuer (subject of previous cert)
     */
    CertPathHelper.setIssuer(sel, currentState.subjectDN);

    /*
     * Match on certificate validity date.
     */
    sel.setCertificateValid(date);

    /*
     * Policy processing optimizations
     */
    if (currentState.explicitPolicy == 0) sel.setPolicy(getMatchingPolicies());

    /*
     * If previous cert has a subject key identifier extension,
     * use it to match on authority key identifier extension.
     */
    /*if (currentState.subjKeyId != null) {
    AuthorityKeyIdentifierExtension authKeyId = new AuthorityKeyIdentifierExtension(
    	(KeyIdentifier) currentState.subjKeyId.get(SubjectKeyIdentifierExtension.KEY_ID),
    	null, null);
    sel.setAuthorityKeyIdentifier(authKeyId.getExtensionValue());
         }*/

    /*
     * Require EE certs
     */
    sel.setBasicConstraints(-2);

    /* Retrieve matching certs from CertStores */
    HashSet eeCerts = new HashSet();
    addMatchingCerts(sel, buildParams.getCertStores(), eeCerts);

    if (debug != null) {
      debug.println("ReverseBuilder.getMatchingEECerts got " + eeCerts.size() + " certs.");
    }
    return eeCerts;
  }
Example #6
0
  private void validateChain(List<Certificate> chain, Certificate cert) {

    List<Certificate> certs = new ArrayList<Certificate>();
    List<Certificate> root = new ArrayList<Certificate>();

    Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();

    certs.add(cert); // adding for self signed certs
    certs.addAll(chain);

    for (Certificate c : certs) {
      if (!(c instanceof X509Certificate))
        throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");

      X509Certificate xCert = (X509Certificate) c;

      Principal subject = xCert.getSubjectDN();
      Principal issuer = xCert.getIssuerDN();

      if (issuer != null && subject.equals(issuer)) {
        root.add(c);
        anchors.add(new TrustAnchor(xCert, null));
      }
    }

    if (root.size() == 0)
      throw new IllegalArgumentException("No root certificates found for certificate chain", null);

    X509CertSelector target = new X509CertSelector();
    target.setCertificate((X509Certificate) cert);

    PKIXBuilderParameters params = null;
    try {
      params = new PKIXBuilderParameters(anchors, target);
      params.setRevocationEnabled(false);
      params.addCertStore(
          CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)));
      CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
      builder.build(params);

    } catch (InvalidAlgorithmParameterException e) {
      throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (CertPathBuilderException e) {
      throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchAlgorithmException e) {
      throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchProviderException e) {
      throw new CloudRuntimeException("No provider for certificate validation", e);
    }
  }
Example #7
0
  private void checkCircProcessing() throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");

    X509Certificate caCert =
        (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(circCA));
    X509Certificate crlCaCert =
        (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(circCRLCA));
    X509CRL crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(circCRL));

    List list = new ArrayList();

    list.add(caCert);
    list.add(crlCaCert);
    list.add(crl);

    CertStoreParameters ccsp = new CollectionCertStoreParameters(list);
    CertStore store = CertStore.getInstance("Collection", ccsp);

    Date validDate = new Date(crl.getThisUpdate().getTime() + 60 * 60 * 1000);

    // validating path
    List certchain = new ArrayList();

    certchain.add(crlCaCert);
    CertPath cp = CertificateFactory.getInstance("X.509", "BC").generateCertPath(certchain);

    Set trust = new HashSet();
    trust.add(new TrustAnchor(caCert, null));

    CertPathValidator cpv = CertPathValidator.getInstance("PKIX", "BC");
    // PKIXParameters param = new PKIXParameters(trust);

    PKIXBuilderParameters param = new PKIXBuilderParameters(trust, null);
    X509CertSelector certSelector = new X509CertSelector();
    certSelector.setCertificate(crlCaCert);
    param.setTargetCertConstraints(certSelector);
    param.addCertStore(store);
    param.setRevocationEnabled(true);
    param.setDate(validDate);

    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, param);
  }
  /*
   * Retrieves all CA certificates which satisfy constraints
   * and requirements specified in the parameters and PKIX state.
   */
  private Collection getMatchingCACerts(ReverseState currentState)
      throws CertificateException, CertStoreException, IOException {

    /*
     * Compose a CertSelector to filter out
     * certs which do not satisfy requirements.
     */
    X509CertSelector sel = new X509CertSelector();

    /*
     * Match on issuer (subject of previous cert)
     */
    CertPathHelper.setIssuer(sel, currentState.subjectDN);

    /*
     * Match on certificate validity date.
     */
    sel.setCertificateValid(date);

    /*
     * Match on target subject name (checks that current cert's
     * name constraints permit it to certify target).
     * (4 is the integer type for DIRECTORY name).
     */
    sel.addPathToName(4, targetCertSelector.getSubjectAsBytes());

    /*
     * Policy processing optimizations
     */
    if (currentState.explicitPolicy == 0) sel.setPolicy(getMatchingPolicies());

    /*
     * If previous cert has a subject key identifier extension,
     * use it to match on authority key identifier extension.
     */
    /*if (currentState.subjKeyId != null) {
    AuthorityKeyIdentifierExtension authKeyId = new AuthorityKeyIdentifierExtension(
    	(KeyIdentifier) currentState.subjKeyId.get(SubjectKeyIdentifierExtension.KEY_ID),
    			null, null);
    sel.setAuthorityKeyIdentifier(authKeyId.getExtensionValue());
         }*/

    /*
     * Require CA certs
     */
    sel.setBasicConstraints(0);

    /* Retrieve matching certs from CertStores */
    ArrayList reverseCerts = new ArrayList();
    addMatchingCerts(sel, buildParams.getCertStores(), reverseCerts);

    /* Sort remaining certs using name constraints */
    Collections.sort(reverseCerts, new PKIXCertComparator());

    if (debug != null)
      debug.println("ReverseBuilder.getMatchingCACerts got " + reverseCerts.size() + " certs.");
    return reverseCerts;
  }
  // controlla che il certificato del firmatario sia affidabile controllando la sua catena di
  // certificati
  // valida il certificato X509 del firmatario usando il built-in PKIX support messo a disposizione
  // da java
  // caricando il keystore contenente i certificati degli enti certificatori autorizzati dallo stato
  // italiano
  private PKIXCertPathBuilderResult isTrustedSigner(SignerInformation signer)
      throws FirmapiuException {
    // genera la lista di certificati da controllare  per generare la catena dei certificati del
    // firmatario
    // TODO quali certificati carica esattamente?
    Collection<?> certCollection = certStore.getMatches(signer.getSID());
    Iterator<?> certIt = certCollection.iterator();
    X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
    List<X509Certificate> chain = new LinkedList<X509Certificate>();
    JcaX509CertificateConverter certConverter =
        new JcaX509CertificateConverter().setProvider(this.bcProvName);
    try {
      X509Certificate x509cert = certConverter.getCertificate(cert);
      chain.add(x509cert);
      while (certIt.hasNext()) {
        x509cert = certConverter.getCertificate((X509CertificateHolder) certIt.next());
        chain.add(x509cert);
      }
    } catch (CertificateException e) {
      new FirmapiuException(CERT_DEFAULT_ERROR, e);
    }

    // carica i certificati presenti nel token crittografico passato come parametro
    KeyStore anchors = this.token.loadKeyStore(null);
    X509CertSelector target = new X509CertSelector();
    target.setCertificate(chain.get(0));
    PKIXBuilderParameters params;
    CertPathBuilder builder;
    try {
      params = new PKIXBuilderParameters(anchors, target);
      // disabilita il controllo delle CRL
      params.setRevocationEnabled(false);
      // se il certificato รจ scaduto cerca di generare lo stesso la catena dei certificati
      try {
        X509Certificate x509cert = certConverter.getCertificate(cert);
        // long before=x509cert.getNotBefore().getTime();
        long after = x509cert.getNotAfter().getTime();
        after -= 10;
        params.setDate(new Date(after));
      } catch (CertificateException e) {
        throw new FirmapiuException(CERT_KEYSTORE_DEFAULT_ERROR, e);
      }
      CertStoreParameters intermediates = new CollectionCertStoreParameters(chain);
      params.addCertStore(CertStore.getInstance("Collection", intermediates));
      params.setSigProvider(this.bcProvName);
      builder = CertPathBuilder.getInstance("PKIX", this.bcProvName);
    } catch (KeyStoreException | InvalidAlgorithmParameterException e) {
      throw new FirmapiuException(CERT_KEYSTORE_DEFAULT_ERROR, e);
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
      throw new FirmapiuException(DEFAULT_ERROR, e);
    }
    /*
     * If build() returns successfully, the certificate is valid. More details
     * about the valid path can be obtained through the PKIXBuilderResult.
     * If no valid path can be found, a CertPathBuilderException is thrown.
     */
    try {
      return (PKIXCertPathBuilderResult) builder.build(params);
    } catch (CertPathBuilderException e) {
      throw new FirmapiuException(VERIFY_SIGNER_CERTPATH_ERROR, e);
    } catch (InvalidAlgorithmParameterException e) {
      throw new FirmapiuException(DEFAULT_ERROR, e);
    }
  } // fine metodo
  /**
   * Search the given Set of TrustAnchor's for one that is the issuer of the given X509 certificate.
   *
   * @param cert the X509 certificate
   * @param params with trust anchors
   * @return the <code>TrustAnchor</code> object if found or <code>null</code> if not.
   * @exception CertPathValidatorException if a TrustAnchor was found but the signature verification
   *     on the given certificate has thrown an exception. This Exception can be obtainted with
   *     <code>getCause()</code> method.
   */
  static final TrustAnchor findTrustAnchor(
      X509Certificate cert, CertPath certPath, int index, PKIXParameters params)
      throws CertPathValidatorException {
    // If we have a trust anchor index, use it.
    if (params instanceof IndexedPKIXParameters) {
      IndexedPKIXParameters indexed = (IndexedPKIXParameters) params;
      return indexed.findTrustAnchor(cert, certPath, index);
    }

    Iterator iter = params.getTrustAnchors().iterator();
    TrustAnchor found = null;
    PublicKey trustPublicKey = null;
    Exception invalidKeyEx = null;

    X509CertSelector certSelectX509 = new X509CertSelector();

    try {
      certSelectX509.setSubject(getEncodedIssuerPrincipal(cert).getEncoded());
    } catch (IOException ex) {
      throw new CertPathValidatorException(ex);
    }

    byte[] certBytes = null;
    try {
      certBytes = cert.getEncoded();
    } catch (Exception e) {
      // ignore, just continue
    }
    while (iter.hasNext() && found == null) {
      found = (TrustAnchor) iter.next();
      X509Certificate foundCert = found.getTrustedCert();
      if (foundCert != null) {
        // If the trust anchor is identical to the certificate we're
        // done. Just return the anchor.
        // There is similar code in PKIXCertPathValidatorSpi.
        try {
          byte[] foundBytes = foundCert.getEncoded();
          if (certBytes != null && Arrays.equals(foundBytes, certBytes)) {
            return found;
          }
        } catch (Exception e) {
          // ignore, continue and verify the certificate
        }
        if (certSelectX509.match(foundCert)) {
          trustPublicKey = foundCert.getPublicKey();
        } else {
          found = null;
        }
      } else if (found.getCAName() != null && found.getCAPublicKey() != null) {
        try {
          X500Principal certIssuer = getEncodedIssuerPrincipal(cert);
          X500Principal caName = new X500Principal(found.getCAName());
          if (certIssuer.equals(caName)) {
            trustPublicKey = found.getCAPublicKey();
          } else {
            found = null;
          }
        } catch (IllegalArgumentException ex) {
          found = null;
        }
      } else {
        found = null;
      }

      if (trustPublicKey != null) {
        try {
          cert.verify(trustPublicKey);
        } catch (Exception ex) {
          invalidKeyEx = ex;
          found = null;
        }
      }
    }

    if (found == null && invalidKeyEx != null) {
      throw new CertPathValidatorException(
          "TrustAnchor found but certificate validation failed.", invalidKeyEx, certPath, index);
    }

    return found;
  }
  /**
   * Verifies a matching certificate.
   *
   * <p>This method executes any of the validation steps in the PKIX path validation algorithm which
   * were not satisfied via filtering out non-compliant certificates with certificate matching
   * rules.
   *
   * <p>If the last certificate is being verified (the one whose subject matches the target subject,
   * then the steps in Section 6.1.4 of the Certification Path Validation algorithm are NOT
   * executed, regardless of whether or not the last cert is an end-entity cert or not. This allows
   * callers to certify CA certs as well as EE certs.
   *
   * @param cert the certificate to be verified
   * @param currentState the current state against which the cert is verified
   * @param certPathList the certPathList generated thus far
   */
  void verifyCert(X509Certificate cert, State currState, List certPathList)
      throws GeneralSecurityException {
    if (debug != null)
      debug.println(
          "ReverseBuilder.verifyCert(SN: "
              + Debug.toHexString(cert.getSerialNumber())
              + "\n  Subject: "
              + cert.getSubjectX500Principal()
              + ")");

    ReverseState currentState = (ReverseState) currState;

    /* we don't perform any validation of the trusted cert */
    if (currentState.isInitial()) {
      return;
    }

    /*
     * check for looping - abort a loop if
     * ((we encounter the same certificate twice) AND
     * ((policyMappingInhibited = true) OR (no policy mapping
     * extensions can be found between the occurences of the same
     * certificate)))
     * in order to facilitate the check to see if there are
     * any policy mapping extensions found between the occurences
     * of the same certificate, we reverse the certpathlist first
     */
    if ((certPathList != null) && (!certPathList.isEmpty())) {
      List reverseCertList = new ArrayList();
      Iterator iter = certPathList.iterator();
      while (iter.hasNext()) {
        reverseCertList.add(0, iter.next());
      }

      Iterator cpListIter = reverseCertList.iterator();
      boolean policyMappingFound = false;
      while (cpListIter.hasNext()) {
        X509Certificate cpListCert = (X509Certificate) cpListIter.next();
        X509CertImpl cpListCertImpl = X509CertImpl.toImpl(cpListCert);
        PolicyMappingsExtension policyMappingsExt = cpListCertImpl.getPolicyMappingsExtension();
        if (policyMappingsExt != null) {
          policyMappingFound = true;
        }
        if (debug != null) debug.println("policyMappingFound = " + policyMappingFound);
        if (cert.equals(cpListCert)) {
          if ((buildParams.isPolicyMappingInhibited()) || (!policyMappingFound)) {
            if (debug != null) debug.println("loop detected!!");
            throw new CertPathValidatorException("loop detected");
          }
        }
      }
    }

    /* check if target cert */
    boolean finalCert = cert.getSubjectX500Principal().equals(targetSubjectDN);

    /* check if CA cert */
    boolean caCert = (cert.getBasicConstraints() != -1 ? true : false);

    /* if there are more certs to follow, verify certain constraints */
    if (!finalCert) {

      /* check if CA cert */
      if (!caCert) throw new CertPathValidatorException("cert is NOT a CA cert");

      /* If the certificate was not self-issued, verify that
       * remainingCerts is greater than zero
       */
      if ((currentState.remainingCACerts <= 0) && !X509CertImpl.isSelfIssued(cert)) {
        throw new CertPathValidatorException("pathLenConstraint violated, path too long");
      }

      /*
       * Check keyUsage extension (only if CA cert and not final cert)
       */
      KeyChecker.verifyCAKeyUsage(cert);

    } else {

      /*
       * If final cert, check that it satisfies specified target
       * constraints
       */
      if (targetCertSelector.match(cert) == false) {
        throw new CertPathValidatorException("target certificate " + "constraints check failed");
      }
    }

    /*
     * Check revocation.
     */
    if (buildParams.isRevocationEnabled()) {

      boolean crlSign = currentState.crlChecker.check(cert, currentState.pubKey, true);

      // if this cert can't vouch for the CRL on the next cert, and
      // if this wasn't the last cert in the chain, then we can't
      // keep going from here!
      // NOTE: if we ever add indirect/idp support, this will have
      // to change...
      if ((!crlSign) && (!finalCert))
        throw new CertPathValidatorException("cert can't vouch for crl");
    }

    /* Check name constraints if this is not a self-issued cert */
    if (finalCert || !X509CertImpl.isSelfIssued(cert)) {
      if (currentState.nc != null) {
        try {
          if (!currentState.nc.verify(cert)) {
            throw new CertPathValidatorException("name constraints check failed");
          }
        } catch (IOException ioe) {
          throw new CertPathValidatorException(ioe);
        }
      }
    }

    /*
     * Check policy
     */
    X509CertImpl certImpl = X509CertImpl.toImpl(cert);
    currentState.rootNode =
        PolicyChecker.processPolicies(
            currentState.certIndex,
            initPolicies,
            currentState.explicitPolicy,
            currentState.policyMapping,
            currentState.inhibitAnyPolicy,
            buildParams.getPolicyQualifiersRejected(),
            currentState.rootNode,
            certImpl,
            finalCert);

    /*
     * Check CRITICAL private extensions
     */
    Set unresolvedCritExts = cert.getCriticalExtensionOIDs();
    if (unresolvedCritExts == null) {
      unresolvedCritExts = Collections.EMPTY_SET;
    }
    Iterator i = currentState.userCheckers.iterator();
    while (i.hasNext()) {
      PKIXCertPathChecker checker = (PKIXCertPathChecker) i.next();
      checker.check(cert, unresolvedCritExts);
    }
    /*
     * Look at the remaining extensions and remove any ones we have
     * already checked. If there are any left, throw an exception!
     */
    if (!unresolvedCritExts.isEmpty()) {
      unresolvedCritExts.remove(PKIXExtensions.BasicConstraints_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.NameConstraints_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.CertificatePolicies_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.PolicyMappings_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.PolicyConstraints_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.InhibitAnyPolicy_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.SubjectAlternativeName_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.KeyUsage_Id.toString());
      unresolvedCritExts.remove(PKIXExtensions.ExtendedKeyUsage_Id.toString());

      if (!unresolvedCritExts.isEmpty())
        throw new CertificateException("Unrecognized critical extension(s)");
    }

    /*
     * Check signature.
     */
    if (buildParams.getSigProvider() != null) {
      cert.verify(currentState.pubKey, buildParams.getSigProvider());
    } else {
      cert.verify(currentState.pubKey);
    }
  }
 /**
  * Returns an instance of this from a <code>X509CertSelector</code>.
  *
  * @param selector A <code>X509CertSelector</code> instance.
  * @return An instance of an <code>X509CertStoreSelector</code>.
  * @exception IllegalArgumentException if selector is null or creation fails.
  */
 public static X509CertStoreSelector getInstance(X509CertSelector selector) {
   if (selector == null) {
     throw new IllegalArgumentException("cannot create from null selector");
   }
   X509CertStoreSelector cs = new X509CertStoreSelector();
   cs.setAuthorityKeyIdentifier(selector.getAuthorityKeyIdentifier());
   cs.setBasicConstraints(selector.getBasicConstraints());
   cs.setCertificate(selector.getCertificate());
   cs.setCertificateValid(selector.getCertificateValid());
   cs.setMatchAllSubjectAltNames(selector.getMatchAllSubjectAltNames());
   try {
     cs.setPathToNames(selector.getPathToNames());
     cs.setExtendedKeyUsage(selector.getExtendedKeyUsage());
     cs.setNameConstraints(selector.getNameConstraints());
     cs.setPolicy(selector.getPolicy());
     cs.setSubjectPublicKeyAlgID(selector.getSubjectPublicKeyAlgID());
     cs.setSubjectAlternativeNames(selector.getSubjectAlternativeNames());
   } catch (IOException e) {
     throw new IllegalArgumentException("error in passed in selector: " + e);
   }
   cs.setIssuer(selector.getIssuer());
   cs.setKeyUsage(selector.getKeyUsage());
   cs.setPrivateKeyValid(selector.getPrivateKeyValid());
   cs.setSerialNumber(selector.getSerialNumber());
   cs.setSubject(selector.getSubject());
   cs.setSubjectKeyIdentifier(selector.getSubjectKeyIdentifier());
   cs.setSubjectPublicKey(selector.getSubjectPublicKey());
   return cs;
 }