java.security.cert.CertPathBuilderSpi#java.security.cert.CertPathBuilderException源码实例Demo

下面列出了java.security.cert.CertPathBuilderSpi#java.security.cert.CertPathBuilderException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: nomulus   文件: SslClientInitializerTest.java
@Test
public void testFailure_defaultTrustManager_rejectSelfSignedCert() throws Exception {
  SelfSignedCaCertificate ssc = SelfSignedCaCertificate.create(SSL_HOST);
  LocalAddress localAddress =
      new LocalAddress("DEFAULT_TRUST_MANAGER_REJECT_SELF_SIGNED_CERT_" + sslProvider);
  nettyRule.setUpServer(localAddress, getServerHandler(false, ssc.key(), ssc.cert()));
  SslClientInitializer<LocalChannel> sslClientInitializer =
      new SslClientInitializer<>(
          sslProvider, hostProvider, portProvider, ImmutableList.of(), null, null);
  nettyRule.setUpClient(localAddress, sslClientInitializer);
  // The connection is now terminated, both the client side and the server side should get
  // exceptions.
  nettyRule.assertThatClientRootCause().isInstanceOf(CertPathBuilderException.class);
  nettyRule.assertThatServerRootCause().isInstanceOf(SSLException.class);
  assertThat(nettyRule.getClientChannel().isActive()).isFalse();
}
 
@Test
public void testNoValidationPossible() throws Exception {

    //trust chain incl intermediate certificates (root + intermediates)
    Collection<? extends Certificate> rootCas;
    final File trustedCas = getAbsoluteFilePathFromClassPath("chain-ca.pem");
    try(FileInputStream trin = new FileInputStream(trustedCas)) {
        rootCas =  (Collection<? extends Certificate>) CertificateFactory.getInstance("X.509").generateCertificates(trin);
    }
    
    Assert.assertEquals(rootCas.size(), 2);

    //certificate chain to validate (client cert + intermediates but without root)
    Collection<? extends Certificate> certsToValidate;
    final File certs = getAbsoluteFilePathFromClassPath("crl/revoked.crt.pem");
    try(FileInputStream trin = new FileInputStream(certs)) {
        certsToValidate =  (Collection<? extends Certificate>) CertificateFactory.getInstance("X.509").generateCertificates(trin);
    }
    
    Assert.assertEquals(certsToValidate.size(), 2);

    CertificateValidator validator = new CertificateValidator(rootCas.toArray(new X509Certificate[0]), Collections.emptyList());
    validator.setDate(CRL_DATE);
    try {
        validator.validate(certsToValidate.toArray(new X509Certificate[0]));
        Assert.fail();
    } catch (CertificateException e) {
        Assert.assertTrue(e.getCause() instanceof CertPathBuilderException);
        Assert.assertTrue(e.getCause().getMessage().contains("unable to find valid certification path to requested target"));
    }
}
 
@Test
public void testClassifyCertPathBuilderException()
{
    LdapTlsHandshakeException e = new LdapTlsHandshakeException( "msg",
        new Exception( new CertPathBuilderException( "foo" ) ) );
    assertThat( e.getMessage(), equalTo( "msg, reason: Failed to build certification path: foo" ) );
}
 
@Test
public void testClassifyCertPathBuilderException()
{
    LdapTlsHandshakeFailCause classification = LdapTlsHandshakeExceptionClassifier
        .classify( new Exception( new CertPathBuilderException( "foo" ) ) );
    assertThat( classification.getReason(), equalTo( ( Reason ) LdapApiReason.NO_VALID_CERTIFICATION_PATH ) );
    assertThat( classification.getReasonPhrase(), equalTo( "Failed to build certification path" ) );
    assertThat( classification.getRootCause(), instanceOf( CertPathBuilderException.class ) );
}
 
源代码5 项目: r2cloud   文件: Util.java
private static String getShortMessageToLog(Throwable e) {
	if (e.getCause() != null) {
		return getShortMessageToLog(e.getCause());
	}
	if (e instanceof IOException) {
		return e.getMessage();
	}
	if (e instanceof UnresolvedAddressException) {
		return e.toString();
	}
	if (e instanceof CertPathBuilderException) {
		return e.getMessage();
	}
	return null;
}
 
源代码6 项目: j2objc   文件: MyCertPathBuilderSpi.java
public CertPathBuilderResult engineBuild(CertPathParameters params)
        throws CertPathBuilderException, InvalidAlgorithmParameterException {
    swi++;
    if ((params == null) && ((swi %2 ) != 0)) {
        throw new CertPathBuilderException("Null parameter");
    }
    return null;
}
 
源代码7 项目: j2objc   文件: CertPathBuilderSpiTest.java
/**
 * Test for <code>CertPathBuilderSpi</code> constructor Assertion:
 * constructs CertPathBuilderSpi
 */
public void testCertPathBuilderSpi01() throws CertPathBuilderException,
        InvalidAlgorithmParameterException {
    CertPathBuilderSpi certPathBuilder = new MyCertPathBuilderSpi();
    CertPathParameters cpp = null;
    try {
        certPathBuilder.engineBuild(cpp);
        fail("CertPathBuilderException must be thrown");
    } catch (CertPathBuilderException e) {
    }
    CertPathBuilderResult cpbResult = certPathBuilder.engineBuild(cpp);
    assertNull("Not null CertPathBuilderResult", cpbResult);
}
 
源代码8 项目: j2objc   文件: CertPathBuilderExceptionTest.java
/**
 * Test for <code>CertPathBuilderException(String)</code> constructor
 * Assertion: constructs CertPathBuilderException when <code>msg</code> is
 * null
 */
public void testCertPathBuilderException03() {
    String msg = null;
    CertPathBuilderException tE = new CertPathBuilderException(msg);
    assertNull("getMessage() must return null.", tE.getMessage());
    assertNull("getCause() must return null", tE.getCause());
}
 
源代码9 项目: j2objc   文件: CertPathBuilderExceptionTest.java
/**
 * Test for <code>CertPathBuilderException(Throwable)</code> constructor
 * Assertion: constructs CertPathBuilderException when <code>cause</code>
 * is null
 */
public void testCertPathBuilderException04() {
    Throwable cause = null;
    CertPathBuilderException tE = new CertPathBuilderException(cause);
    assertNull("getMessage() must return null.", tE.getMessage());
    assertNull("getCause() must return null", tE.getCause());
}
 
源代码10 项目: j2objc   文件: CertPathBuilderExceptionTest.java
/**
 * Test for <code>CertPathBuilderException(Throwable)</code> constructor
 * Assertion: constructs CertPathBuilderException when <code>cause</code>
 * is not null
 */
public void testCertPathBuilderException05() {
    CertPathBuilderException tE = new CertPathBuilderException(tCause);
    if (tE.getMessage() != null) {
        String toS = tCause.toString();
        String getM = tE.getMessage();
        assertTrue("getMessage() should contain ".concat(toS), (getM
                .indexOf(toS) != -1));
    }
    assertNotNull("getCause() must not return null", tE.getCause());
    assertEquals("getCause() must return ".concat(tCause.toString()), tE
            .getCause(), tCause);
}
 
源代码11 项目: j2objc   文件: CertPathBuilderExceptionTest.java
/**
 * Test for <code>CertPathBuilderException(String, Throwable)</code>
 * constructor Assertion: constructs CertPathBuilderException when
 * <code>cause</code> is not null <code>msg</code> is null
 */
public void testCertPathBuilderException08() {
    CertPathBuilderException tE = new CertPathBuilderException(null, tCause);
    if (tE.getMessage() != null) {
        String toS = tCause.toString();
        String getM = tE.getMessage();
        assertTrue("getMessage() must should ".concat(toS), (getM
                .indexOf(toS) != -1));
    }
    assertNotNull("getCause() must not return null", tE.getCause());
    assertEquals("getCause() must return ".concat(tCause.toString()), tE
            .getCause(), tCause);
}
 
源代码12 项目: xipki   文件: CaManagerQueryExecutor.java
private static List<X509Cert> buildCertChain(X509Cert targetCert,
    List<X509Cert> certs) throws CaMgmtException {
  X509Cert[] certchain;
  try {
    certchain = X509Util.buildCertPath(targetCert, certs, false);
  } catch (CertPathBuilderException ex) {
    throw new CaMgmtException(ex);
  }

  if (certchain == null || certs.size() != certchain.length) {
    throw new CaMgmtException("could not build certchain containing all specified certs");
  }
  return Arrays.asList(certchain);
}
 
源代码13 项目: wildfly-camel   文件: SecurityInInterceptor.java
/**
 * Based on https://svn.apache.org/repos/asf/cxf/tags/cxf-2.4.1/distribution/src/main/release/samples/sts_issue_operation/src/main/java/demo/sts/provider/cert/CertificateVerifier.java
 *
 * @param cert
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidAlgorithmParameterException
 * @throws CertPathBuilderException
 */
public void verifyCertificate(X509Certificate cert) throws CertificateException, NoSuchAlgorithmException,
        NoSuchProviderException, InvalidAlgorithmParameterException, CertPathBuilderException {
    // Prepare a set of trusted root CA certificates
    // and a set of intermediate certificates
    // Create the selector that specifies the starting certificate
    X509CertSelector selector = new X509CertSelector();
    selector.setCertificate(cert);

    // Create the trust anchors (set of root CA certificates)
    Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
    for (X509Certificate trustedRootCert : trustedRootCerts) {
        trustAnchors.add(new TrustAnchor(trustedRootCert, null));
    }

    // Configure the PKIX certificate builder algorithm parameters
    PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);

    // Disable CRL checks (this is done manually as additional step)
    pkixParams.setRevocationEnabled(false);

    // Specify a list of intermediate certificates
    CertStore intermediateCertStore = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(intermediateCerts));
    pkixParams.addCertStore(intermediateCertStore);

    // Build and verify the certification chain
    CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
    builder.build(pkixParams);
    // Attempt to build the certification chain and verify it

    // Check whether the certificate is revoked by the CRL
    // given in its CRL distribution point extension
    // CRLVerifier.verifyCertificateCRLs(cert);

    // The chain is verified.
}
 
源代码14 项目: Spark   文件: SparkExceptionsTrustManager.java
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    // if end entity certificate is on the exception list then pass checks
    try {
        if (!isFirstCertExempted(chain)) {
            // else exempted certificate can be higher in chain, in this case certificate list have to be build
            validatePath(chain);
        }
    } catch (NoSuchAlgorithmException | KeyStoreException | InvalidAlgorithmParameterException
            | CertPathValidatorException | CertPathBuilderException e) {
        Log.warning("Cannot build certificate chain", e);
        throw new CertificateException("Cannot build certificate chain");
    }
}
 
源代码15 项目: Spark   文件: SparkExceptionsTrustManager.java
/**
 * Validate certificate path. As it is exception, no checks against revocation or time validity are done but path
 * still have to be validated in order to find connection between certificate presented by server and root CA in
 * KeyStore
 * 
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws InvalidAlgorithmParameterException
 * @throws CertPathValidatorException
 * @throws CertPathBuilderException
 * @throws CertificateException
 */
private void validatePath(X509Certificate[] chain)
        throws NoSuchAlgorithmException, KeyStoreException, InvalidAlgorithmParameterException,
        CertPathValidatorException, CertPathBuilderException, CertificateException {

    CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX");
    CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX");
    X509CertSelector certSelector = new X509CertSelector();
    certSelector.setCertificate(chain[chain.length - 1]);
    // checks against time validity aren't done here as it exceptions list
    certSelector.setCertificateValid(null);
    PKIXBuilderParameters parameters = new PKIXBuilderParameters(allStore, certSelector);
    // no checks against revocation as it is exception
    parameters.setRevocationEnabled(false);

    CertPathBuilderResult pathResult = certPathBuilder.build(parameters);
    CertPath certPath = pathResult.getCertPath();
    PKIXCertPathValidatorResult validationResult = (PKIXCertPathValidatorResult) certPathValidator
            .validate(certPath, parameters);
    X509Certificate trustedCert = validationResult.getTrustAnchor().getTrustedCert();

    if (trustedCert == null) {
        throw new CertificateException("Certificate path failed");
    } else {
        Log.debug("ClientTrustManager: Trusted CA: " + trustedCert.getSubjectDN());
    }

}
 
public static LdapTlsHandshakeFailCause classify( Throwable cause, X509Certificate certificate )
{
    LdapTlsHandshakeFailCause failCause = new LdapTlsHandshakeFailCause();
    failCause.setCause( cause );

    Throwable rootCause = ExceptionUtils.getRootCause( cause );
    failCause.setRootCause( rootCause );

    if ( rootCause instanceof CertificateExpiredException )
    {
        failCause.setReason( BasicReason.EXPIRED );
        failCause.setReasonPhrase( "Certificate expired" );
    }
    else if ( rootCause instanceof CertificateNotYetValidException )
    {
        failCause.setReason( BasicReason.NOT_YET_VALID );
        failCause.setReasonPhrase( "Certificate not yet valid" );
    }
    else if ( rootCause instanceof CertPathBuilderException )
    {
        failCause.setReason( LdapApiReason.NO_VALID_CERTIFICATION_PATH );
        failCause.setReasonPhrase( "Failed to build certification path" );
        if ( certificate != null )
        {
            X500Principal issuerX500Principal = certificate.getIssuerX500Principal();
            X500Principal subjectX500Principal = certificate.getSubjectX500Principal();
            if ( issuerX500Principal.equals( subjectX500Principal ) )
            {
                failCause.setReason( LdapApiReason.SELF_SIGNED );
                failCause.setReasonPhrase( "Self signed certificate" );
            }
        }
    }
    else if ( rootCause instanceof CertPathValidatorException )
    {
        CertPathValidatorException cpve = ( CertPathValidatorException ) rootCause;
        failCause.setReason( cpve.getReason() );
        failCause.setReasonPhrase( "Failed to verify certification path" );
    }
    else
    {
        failCause.setReason( BasicReason.UNSPECIFIED );
        failCause.setReasonPhrase( "Unspecified" );
    }

    return failCause;
}
 
源代码17 项目: j2objc   文件: CertPathBuilderExceptionTest.java
/**
 * Test for <code>CertPathBuilderException()</code> constructor Assertion:
 * constructs CertPathBuilderException with no detail message
 */
public void testCertPathBuilderException01() {
    CertPathBuilderException tE = new CertPathBuilderException();
    assertNull("getMessage() must return null.", tE.getMessage());
    assertNull("getCause() must return null", tE.getCause());
}
 
源代码18 项目: j2objc   文件: CertPathBuilderExceptionTest.java
/**
 * Test for <code>CertPathBuilderException(String, Throwable)</code>
 * constructor Assertion: constructs CertPathBuilderException when
 * <code>cause</code> is null <code>msg</code> is null
 */
public void testCertPathBuilderException06() {
    CertPathBuilderException tE = new CertPathBuilderException(null, null);
    assertNull("getMessage() must return null", tE.getMessage());
    assertNull("getCause() must return null", tE.getCause());
}
 
源代码19 项目: xipki   文件: X509Util.java
/**
 * Build the certificate path. Cross certificate will not be considered.
 * @param targetCert certificate for which the certificate path will be built
 * @param certs collection of certificates.
 * @param includeTargetCert whether to include {@code targetCert} in the result.
 * @return the certificate path
 * @throws CertPathBuilderException
 *           If cannot build a valid certificate path.
 */
public static X509Cert[] buildCertPath(X509Cert targetCert,
    Collection<X509Cert> certs, boolean includeTargetCert)
        throws CertPathBuilderException {
  Args.notNull(targetCert, "cert");
  List<X509Cert> certChain = new LinkedList<>();
  certChain.add(targetCert);
  try {
    if (certs != null && !targetCert.isSelfSigned()) {
      while (true) {
        X509Cert caCert = getCaCertOf(certChain.get(certChain.size() - 1), certs);
        if (caCert == null) {
          break;
        }
        certChain.add(caCert);
        if (caCert.isSelfSigned()) {
          // reaches root self-signed certificate
          break;
        }
      }
    }
  } catch (CertificateEncodingException ex) {
    LOG.warn("CertificateEncodingException: {}", ex.getMessage());
  }

  final int n = certChain.size();
  if (n == 1) {
    return includeTargetCert ? certChain.toArray(new X509Cert[0]) : null;
  }

  // check the basicConstrains
  int minPathLen;
  int targetPathLen = targetCert.getBasicConstraints();
  if (targetPathLen != -1) {
    // targetCert is non-CA
    minPathLen = 0;
  } else {
    if (targetPathLen == Integer.MAX_VALUE) {
      minPathLen = 1;
    } else {
      minPathLen = targetPathLen + 1;
    }
  }

  for (int i = 1; i < n; i++) {
    int pathLen = certChain.get(i).getBasicConstraints();
    if (pathLen < minPathLen) {
      throw new CertPathBuilderException("PathLen too small of certificate "
          + certChain.get(i).getSubject().toString());
    } else {
      minPathLen = 1 + (pathLen == Integer.MAX_VALUE ? minPathLen : pathLen);
    }
  }

  if (!includeTargetCert) {
    certChain.remove(0);
  }

  return certChain.toArray(new X509Cert[0]);
}
 
源代码20 项目: xipki   文件: P11ContentSignerBuilder.java
public P11ContentSignerBuilder(P11CryptService cryptService, SecurityFactory securityFactory,
    P11IdentityId identityId, X509Cert[] certificateChain)
    throws XiSecurityException, P11TokenException {
  this.cryptService = Args.notNull(cryptService, "cryptService");
  this.securityFactory = Args.notNull(securityFactory, "securityFactory");
  this.identityId = Args.notNull(identityId, "identityId");

  P11Identity identity = cryptService.getIdentity(identityId);
  X509Cert signerCertInP11 = identity.getCertificate();
  PublicKey publicKeyInP11 = (signerCertInP11 != null) ? signerCertInP11.getPublicKey()
      : identity.getPublicKey();

  if (publicKeyInP11 == null) {
    throw new XiSecurityException("public key with " + identityId + " does not exist");
  }

  Set<X509Cert> caCerts = new HashSet<>();

  X509Cert cert;
  if (certificateChain != null && certificateChain.length > 0) {
    final int n = certificateChain.length;
    cert = certificateChain[0];
    if (n > 1) {
      for (int i = 1; i < n; i++) {
        caCerts.add(certificateChain[i]);
      }
    }
    this.publicKey = cert.getPublicKey();
  } else {
    this.publicKey = publicKeyInP11;
    cert = signerCertInP11;
  }

  if (cert != null) {
    X509Cert[] certsInKeystore = identity.certificateChain();
    if (certsInKeystore != null && certsInKeystore.length > 1) {
      for (int i = 1; i < certsInKeystore.length; i++) {
        caCerts.add(certsInKeystore[i]);
      }
    }

    try {
      this.certificateChain = X509Util.buildCertPath(cert, caCerts);
    } catch (CertPathBuilderException ex) {
      throw new XiSecurityException(ex);
    }
  } else {
    this.certificateChain = null;
  }
}
 
源代码21 项目: xipki   文件: KeypairWithCert.java
public static KeypairWithCert fromKeystore(KeyStore keystore,
    String keyname, char[] keyPassword, X509Cert[] certchain)
        throws XiSecurityException {
  Args.notNull(keyPassword, "keyPassword");

  try {

    String tmpKeyname = keyname;
    if (tmpKeyname == null) {
      Enumeration<String> aliases = keystore.aliases();
      while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keystore.isKeyEntry(alias)) {
          tmpKeyname = alias;
          break;
        }
      }
    } else {
      if (!keystore.isKeyEntry(tmpKeyname)) {
        throw new XiSecurityException("unknown key named " + tmpKeyname);
      }
    }

    PrivateKey key = (PrivateKey) keystore.getKey(tmpKeyname, keyPassword);

    if (!(key instanceof RSAPrivateKey || key instanceof DSAPrivateKey
        || key instanceof ECPrivateKey
        || key instanceof EdDSAKey || key instanceof XDHKey)) {
      throw new XiSecurityException("unsupported key " + key.getClass().getName());
    }

    Set<X509Cert> caCerts = new HashSet<>();

    X509Cert cert;
    if (certchain != null && certchain.length > 0) {
      cert = certchain[0];
      final int n = certchain.length;
      if (n > 1) {
        for (int i = 1; i < n; i++) {
          caCerts.add(certchain[i]);
        }
      }
    } else {
      cert = new X509Cert((X509Certificate) keystore.getCertificate(tmpKeyname));
    }

    Certificate[] certsInKeystore = keystore.getCertificateChain(tmpKeyname);
    if (certsInKeystore.length > 1) {
      for (int i = 1; i < certsInKeystore.length; i++) {
        caCerts.add(new X509Cert((X509Certificate) certsInKeystore[i]));
      }
    }

    X509Cert[] certificateChain = X509Util.buildCertPath(cert, caCerts);

    return new KeypairWithCert(key, certificateChain);
  } catch (KeyStoreException | NoSuchAlgorithmException
      | UnrecoverableKeyException | ClassCastException | CertPathBuilderException ex) {
    throw new XiSecurityException(ex.getMessage(), ex);
  }
}
 
源代码22 项目: Spark   文件: SparkTrustManager.java
/**
 * Validate certificate path
 * 
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws InvalidAlgorithmParameterException
 * @throws CertPathValidatorException
 * @throws CertPathBuilderException
 * @throws CertificateException
 */
private void validatePath(X509Certificate[] chain)
        throws NoSuchAlgorithmException, KeyStoreException, InvalidAlgorithmParameterException,
        CertPathValidatorException, CertPathBuilderException, CertificateException {
    // PKIX algorithm is defined in rfc3280
    CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX");
    CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX");

    X509CertSelector certSelector = new X509CertSelector();

    // set last certificate (often root CA) from chain for CertSelector so trust store must contain it
    certSelector.setCertificate(chain[chain.length - 1]);

    // checks against time validity aren't done here as are already done in checkDateValidity (X509Certificate[]
    // chain)
    certSelector.setCertificateValid(null);
    // create parameters using trustStore as source of Trust Anchors and using X509CertSelector
    PKIXBuilderParameters parameters = new PKIXBuilderParameters(allStore, certSelector);

    // will use PKIXRevocationChecker (or nothing if revocation mechanisms are
    // disabled) instead of the default revocation checker
    parameters.setRevocationEnabled(false);   

    // if revoked certificates aren't accepted, but no revocation checks then only
    // certificates from blacklist will be rejected
    if (acceptRevoked == false) {
        
        // OCSP checking is done according to Java PKI Programmer's Guide, PKIXRevocationChecker was added in Java 8:
        // https://docs.oracle.com/javase/8/docs/technotes/guides/security/certpath/CertPathProgGuide.html#PKIXRevocationChecker
        PKIXRevocationChecker checker = (PKIXRevocationChecker) certPathBuilder.getRevocationChecker();

        EnumSet<PKIXRevocationChecker.Option> checkerOptions = EnumSet.noneOf(PKIXRevocationChecker.Option.class);
        // if soft fail isn't enabled then OCSP or CRL must pass validation, in case
        // when any of them cannot be validated verification will fail, if soft fail
        // is enabled then in case of network issues revocation checking is omitted
        if (allowSoftFail) {
            checkerOptions.add(PKIXRevocationChecker.Option.SOFT_FAIL);
        }
        // check OCSP, CRL serve as backup
        if (checkOCSP && checkCRL) {
            checker.setOptions(checkerOptions);
            parameters.addCertPathChecker(checker);
        } else if (!checkOCSP && checkCRL) {
            // check only CRL, if CRL fail then there is no fallback to OCSP
            checkerOptions.add(PKIXRevocationChecker.Option.PREFER_CRLS);
            checkerOptions.add(PKIXRevocationChecker.Option.NO_FALLBACK);
            checker.setOptions(checkerOptions);
            parameters.addCertPathChecker(checker);
        }
                    
    }
    
    try {
        CertPathBuilderResult pathResult = certPathBuilder.build(parameters);
        CertPath certPath = pathResult.getCertPath();

        PKIXCertPathValidatorResult validationResult = (PKIXCertPathValidatorResult) certPathValidator
                .validate(certPath, parameters);
        X509Certificate trustedCert = validationResult.getTrustAnchor().getTrustedCert();

        if (trustedCert == null) {
            throw new CertificateException("certificate path failed: Trusted CA is NULL");
        }
        // check if all certificates in path have Basic Constraints, only certificate that isn't required to have
        // this extension is last certificate: root CA
        for (int i = 0; i < chain.length - 1; i++) {
            checkBasicConstraints(chain[i]);
        }
    } catch (CertificateRevokedException e) {
        Log.warning("Certificate was revoked", e);
        for (X509Certificate cert : chain) {
            for (X509CRL crl : crlCollection) {
                if (crl.isRevoked(cert)) {
                    try {
                        addToBlackList(cert);
                    } catch (IOException | HeadlessException | InvalidNameException e1) {
                        Log.error("Couldn't move to the blacklist", e1);
                    }
                    break;
                }
            }
        }
        throw new CertificateException("Certificate was revoked");
    }
}
 
源代码23 项目: xipki   文件: X509Util.java
/**
 * Build the certificate path. Cross certificate will not be considered.
 * @param targetCert certificate for which the certificate path will be built
 * @param certs collection of certificates.
 * @return the certificate path
 * @throws CertPathBuilderException
 *           If cannot build a valid certificate path.
 */
public static X509Cert[] buildCertPath(X509Cert targetCert, Collection<X509Cert> certs)
    throws CertPathBuilderException {
  return buildCertPath(targetCert, certs, true);
}