Java Code Examples for java.security.cert.PKIXBuilderParameters#addCertStore()

The following examples show how to use java.security.cert.PKIXBuilderParameters#addCertStore() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KeyManagementUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static void validateCertificateChain(KeyStore ks, List<X509Certificate> inCerts, boolean enableRevocation) {
    // Initial chain validation, to be enhanced as needed
    try {
        X509CertSelector certSelect = new X509CertSelector();
        certSelect.setCertificate(inCerts.get(0));
        PKIXBuilderParameters pbParams = new PKIXBuilderParameters(ks, certSelect);
        pbParams.addCertStore(CertStore.getInstance("Collection",
                                                    new CollectionCertStoreParameters(inCerts)));
        pbParams.setMaxPathLength(-1);
        pbParams.setRevocationEnabled(false);
        CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams);
        pbParams.setRevocationEnabled(enableRevocation);
        CertPath certPath = buildResult.getCertPath();
        CertPathValidator.getInstance("PKIX").validate(certPath, pbParams);
    } catch (Exception ex) {
        LOG.warning("Certificate path validation error");
        throw new JoseException(ex);
    }
}
 
Example 2
Source File: SSLUtilBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Return the initialization parameters for the TrustManager.
 * Currently, only the default <code>PKIX</code> is supported.
 *
 * @param crlf The path to the CRL file.
 * @param trustStore The configured TrustStore.
 * @param revocationEnabled Should the JSSE provider perform revocation
 *                          checks? Ignored if {@code crlf} is non-null.
 *                          Configuration of revocation checks are expected
 *                          to be via proprietary JSSE provider methods.
 * @return The parameters including the CRLs and TrustStore.
 * @throws Exception An error occurred
 */
protected CertPathParameters getParameters(String crlf, KeyStore trustStore,
        boolean revocationEnabled) throws Exception {

    PKIXBuilderParameters xparams =
            new PKIXBuilderParameters(trustStore, new X509CertSelector());
    if (crlf != null && crlf.length() > 0) {
        Collection<? extends CRL> crls = getCRLs(crlf);
        CertStoreParameters csp = new CollectionCertStoreParameters(crls);
        CertStore store = CertStore.getInstance("Collection", csp);
        xparams.addCertStore(store);
        xparams.setRevocationEnabled(true);
    } else {
        xparams.setRevocationEnabled(revocationEnabled);
    }
    xparams.setMaxPathLength(sslHostConfig.getCertificateVerificationDepth());
    return xparams;
}
 
Example 3
Source File: BuildEEBasicConstraints.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example 4
Source File: BuildEEBasicConstraints.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example 5
Source File: BuildEEBasicConstraints.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example 6
Source File: KeystoreTestUtils.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * This method will validate a chain of certificates. It is provided as an alternative to the certificate chain
 * validation mechanisms that are under test. This method is intended to be used as a comparative benchmark against
 * other validation methods.
 *
 * The first certificate in the chain is expected to be the end-entity certificate.
 *
 * The last certificate in the chain is expected to be the root CA certificate.
 *
 * @param chain A certificate chain (cannot be null or empty).
 * @return CertPathBuilderResult result of validation.
 * @throws Exception When the chain is not valid.
 */
public CertPathBuilderResult testChain( X509Certificate[] chain ) throws Exception
{
    // Create the selector that specifies the starting certificate
    X509CertSelector selector = new X509CertSelector();
    selector.setCertificate( chain[0] );

    // Create the trust anchors (set of root CA certificates)
    Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
    trustAnchors.add(new TrustAnchor(chain[ chain.length - 1], 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
    Set<java.security.cert.Certificate> intermediateCerts = new HashSet<>();
    for (int i=1; i<chain.length -1; i++)
    {
        intermediateCerts.add( chain[ i ] );
    }

    CertStore intermediateCertStore = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(intermediateCerts));
    pkixParams.addCertStore(intermediateCertStore);

    // Build and verify the certification chain
    CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
    PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder
            .build(pkixParams);

    return result;
}
 
Example 7
Source File: NoExtensions.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void doBuild(X509Certificate userCert) throws Exception {
        // get the set of trusted CA certificates (only one in this instance)
        HashSet trustAnchors = new HashSet();
        X509Certificate trustedCert = getTrustedCertificate();
        trustAnchors.add(new TrustAnchor(trustedCert, null));

        // put together a CertStore (repository of the certificates and CRLs)
        ArrayList certs = new ArrayList();
        certs.add(trustedCert);
        certs.add(userCert);
        CollectionCertStoreParameters certStoreParams = new CollectionCertStoreParameters(certs);
        CertStore certStore = CertStore.getInstance("Collection", certStoreParams);

        // specify the target certificate via a CertSelector
        X509CertSelector certSelector = new X509CertSelector();
        certSelector.setCertificate(userCert);
        certSelector.setSubject(userCert.getSubjectDN().getName()); // seems to be required

        // build a valid cerificate path
        CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX", "SUN");
        PKIXBuilderParameters certPathBuilderParams = new PKIXBuilderParameters(trustAnchors, certSelector);
        certPathBuilderParams.addCertStore(certStore);
        certPathBuilderParams.setRevocationEnabled(false);
        CertPathBuilderResult result = certPathBuilder.build(certPathBuilderParams);

        // get and show cert path
        CertPath certPath = result.getCertPath();
//        System.out.println(certPath.toString());
    }
 
Example 8
Source File: BuildEEBasicConstraints.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example 9
Source File: NoExtensions.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void doBuild(X509Certificate userCert) throws Exception {
        // get the set of trusted CA certificates (only one in this instance)
        HashSet trustAnchors = new HashSet();
        X509Certificate trustedCert = getTrustedCertificate();
        trustAnchors.add(new TrustAnchor(trustedCert, null));

        // put together a CertStore (repository of the certificates and CRLs)
        ArrayList certs = new ArrayList();
        certs.add(trustedCert);
        certs.add(userCert);
        CollectionCertStoreParameters certStoreParams = new CollectionCertStoreParameters(certs);
        CertStore certStore = CertStore.getInstance("Collection", certStoreParams);

        // specify the target certificate via a CertSelector
        X509CertSelector certSelector = new X509CertSelector();
        certSelector.setCertificate(userCert);
        certSelector.setSubject(userCert.getSubjectDN().getName()); // seems to be required

        // build a valid cerificate path
        CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX", "SUN");
        PKIXBuilderParameters certPathBuilderParams = new PKIXBuilderParameters(trustAnchors, certSelector);
        certPathBuilderParams.addCertStore(certStore);
        certPathBuilderParams.setRevocationEnabled(false);
        CertPathBuilderResult result = certPathBuilder.build(certPathBuilderParams);

        // get and show cert path
        CertPath certPath = result.getCertPath();
//        System.out.println(certPath.toString());
    }
 
Example 10
Source File: NoExtensions.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private void doBuild(X509Certificate userCert) throws Exception {
        // get the set of trusted CA certificates (only one in this instance)
        HashSet trustAnchors = new HashSet();
        X509Certificate trustedCert = getTrustedCertificate();
        trustAnchors.add(new TrustAnchor(trustedCert, null));

        // put together a CertStore (repository of the certificates and CRLs)
        ArrayList certs = new ArrayList();
        certs.add(trustedCert);
        certs.add(userCert);
        CollectionCertStoreParameters certStoreParams = new CollectionCertStoreParameters(certs);
        CertStore certStore = CertStore.getInstance("Collection", certStoreParams);

        // specify the target certificate via a CertSelector
        X509CertSelector certSelector = new X509CertSelector();
        certSelector.setCertificate(userCert);
        certSelector.setSubject(userCert.getSubjectDN().getName()); // seems to be required

        // build a valid cerificate path
        CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX", "SUN");
        PKIXBuilderParameters certPathBuilderParams = new PKIXBuilderParameters(trustAnchors, certSelector);
        certPathBuilderParams.addCertStore(certStore);
        certPathBuilderParams.setRevocationEnabled(false);
        CertPathBuilderResult result = certPathBuilder.build(certPathBuilderParams);

        // get and show cert path
        CertPath certPath = result.getCertPath();
//        System.out.println(certPath.toString());
    }
 
Example 11
Source File: NoExtensions.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private void doBuild(X509Certificate userCert) throws Exception {
        // get the set of trusted CA certificates (only one in this instance)
        HashSet trustAnchors = new HashSet();
        X509Certificate trustedCert = getTrustedCertificate();
        trustAnchors.add(new TrustAnchor(trustedCert, null));

        // put together a CertStore (repository of the certificates and CRLs)
        ArrayList certs = new ArrayList();
        certs.add(trustedCert);
        certs.add(userCert);
        CollectionCertStoreParameters certStoreParams = new CollectionCertStoreParameters(certs);
        CertStore certStore = CertStore.getInstance("Collection", certStoreParams);

        // specify the target certificate via a CertSelector
        X509CertSelector certSelector = new X509CertSelector();
        certSelector.setCertificate(userCert);
        certSelector.setSubject(userCert.getSubjectDN().getName()); // seems to be required

        // build a valid cerificate path
        CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX", "SUN");
        PKIXBuilderParameters certPathBuilderParams = new PKIXBuilderParameters(trustAnchors, certSelector);
        certPathBuilderParams.addCertStore(certStore);
        certPathBuilderParams.setRevocationEnabled(false);
        CertPathBuilderResult result = certPathBuilder.build(certPathBuilderParams);

        // get and show cert path
        CertPath certPath = result.getCertPath();
//        System.out.println(certPath.toString());
    }
 
Example 12
Source File: NoExtensions.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private void doBuild(X509Certificate userCert) throws Exception {
        // get the set of trusted CA certificates (only one in this instance)
        HashSet trustAnchors = new HashSet();
        X509Certificate trustedCert = getTrustedCertificate();
        trustAnchors.add(new TrustAnchor(trustedCert, null));

        // put together a CertStore (repository of the certificates and CRLs)
        ArrayList certs = new ArrayList();
        certs.add(trustedCert);
        certs.add(userCert);
        CollectionCertStoreParameters certStoreParams = new CollectionCertStoreParameters(certs);
        CertStore certStore = CertStore.getInstance("Collection", certStoreParams);

        // specify the target certificate via a CertSelector
        X509CertSelector certSelector = new X509CertSelector();
        certSelector.setCertificate(userCert);
        certSelector.setSubject(userCert.getSubjectDN().getName()); // seems to be required

        // build a valid cerificate path
        CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX", "SUN");
        PKIXBuilderParameters certPathBuilderParams = new PKIXBuilderParameters(trustAnchors, certSelector);
        certPathBuilderParams.addCertStore(certStore);
        certPathBuilderParams.setRevocationEnabled(false);
        CertPathBuilderResult result = certPathBuilder.build(certPathBuilderParams);

        // get and show cert path
        CertPath certPath = result.getCertPath();
//        System.out.println(certPath.toString());
    }
 
Example 13
Source File: CertificateValidationUtil.java    From opc-ua-stack with Apache License 2.0 5 votes vote down vote up
public static void validateTrustChain(X509Certificate certificate,
                                      List<X509Certificate> chain,
                                      Set<X509Certificate> trustedCertificates,
                                      Set<X509Certificate> authorityCertificates) throws UaException {

    boolean certificateTrusted = trustedCertificates.stream()
            .anyMatch(c -> Arrays.equals(certificate.getSignature(), c.getSignature()));

    if (certificateTrusted) return;

    try {
        Set<TrustAnchor> trustAnchors = new HashSet<>();
        authorityCertificates.forEach(ca -> trustAnchors.add(new TrustAnchor(ca, null)));

        X509CertSelector selector = new X509CertSelector();
        selector.setCertificate(certificate);

        PKIXBuilderParameters params = new PKIXBuilderParameters(trustAnchors, selector);

        params.setRevocationEnabled(false);

        CertStore intermediateCertStore =
                CertStore.getInstance("Collection", new CollectionCertStoreParameters(chain));

        params.addCertStore(intermediateCertStore);

        CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");

        PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder.build(params);

        LOGGER.debug("Validated certificate chain: {}", result.getCertPath());
    } catch (Throwable t) {
        throw new UaException(StatusCodes.Bad_SecurityChecksFailed);
    }
}
 
Example 14
Source File: NoExtensions.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private void doBuild(X509Certificate userCert) throws Exception {
        // get the set of trusted CA certificates (only one in this instance)
        HashSet trustAnchors = new HashSet();
        X509Certificate trustedCert = getTrustedCertificate();
        trustAnchors.add(new TrustAnchor(trustedCert, null));

        // put together a CertStore (repository of the certificates and CRLs)
        ArrayList certs = new ArrayList();
        certs.add(trustedCert);
        certs.add(userCert);
        CollectionCertStoreParameters certStoreParams = new CollectionCertStoreParameters(certs);
        CertStore certStore = CertStore.getInstance("Collection", certStoreParams);

        // specify the target certificate via a CertSelector
        X509CertSelector certSelector = new X509CertSelector();
        certSelector.setCertificate(userCert);
        certSelector.setSubject(userCert.getSubjectDN().getName()); // seems to be required

        // build a valid cerificate path
        CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX", "SUN");
        PKIXBuilderParameters certPathBuilderParams = new PKIXBuilderParameters(trustAnchors, certSelector);
        certPathBuilderParams.addCertStore(certStore);
        certPathBuilderParams.setRevocationEnabled(false);
        CertPathBuilderResult result = certPathBuilder.build(certPathBuilderParams);

        // get and show cert path
        CertPath certPath = result.getCertPath();
//        System.out.println(certPath.toString());
    }
 
Example 15
Source File: BuildEEBasicConstraints.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example 16
Source File: BuildEEBasicConstraints.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example 17
Source File: SecurityInInterceptor.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
/**
 * 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.
}
 
Example 18
Source File: NoExtensions.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void doBuild(X509Certificate userCert) throws Exception {
        // get the set of trusted CA certificates (only one in this instance)
        HashSet trustAnchors = new HashSet();
        X509Certificate trustedCert = getTrustedCertificate();
        trustAnchors.add(new TrustAnchor(trustedCert, null));

        // put together a CertStore (repository of the certificates and CRLs)
        ArrayList certs = new ArrayList();
        certs.add(trustedCert);
        certs.add(userCert);
        CollectionCertStoreParameters certStoreParams = new CollectionCertStoreParameters(certs);
        CertStore certStore = CertStore.getInstance("Collection", certStoreParams);

        // specify the target certificate via a CertSelector
        X509CertSelector certSelector = new X509CertSelector();
        certSelector.setCertificate(userCert);
        certSelector.setSubject(userCert.getSubjectDN().getName()); // seems to be required

        // build a valid cerificate path
        CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX", "SUN");
        PKIXBuilderParameters certPathBuilderParams = new PKIXBuilderParameters(trustAnchors, certSelector);
        certPathBuilderParams.addCertStore(certStore);
        certPathBuilderParams.setRevocationEnabled(false);
        CertPathBuilderResult result = certPathBuilder.build(certPathBuilderParams);

        // get and show cert path
        CertPath certPath = result.getCertPath();
//        System.out.println(certPath.toString());
    }
 
Example 19
Source File: CertPathPKIXTrustEvaluator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates the set of PKIX builder parameters to use when building the cert path builder.
 * 
 * @param validationInfo PKIX validation information
 * @param untrustedCredential credential to be validated
 * 
 * @return PKIX builder params
 * 
 * @throws GeneralSecurityException thrown if the parameters can not be created
 */
protected PKIXBuilderParameters getPKIXBuilderParameters(PKIXValidationInformation validationInfo,
        X509Credential untrustedCredential) throws GeneralSecurityException {
    Set<TrustAnchor> trustAnchors = getTrustAnchors(validationInfo);
    if (trustAnchors == null || trustAnchors.isEmpty()) {
        throw new GeneralSecurityException(
                "Unable to validate X509 certificate, no trust anchors found in the PKIX validation information");
    }

    X509CertSelector selector = new X509CertSelector();
    selector.setCertificate(untrustedCredential.getEntityCertificate());

    log.trace("Adding trust anchors to PKIX validator parameters");
    PKIXBuilderParameters params = new PKIXBuilderParameters(trustAnchors, selector);

    Integer effectiveVerifyDepth = getEffectiveVerificationDepth(validationInfo);
    log.trace("Setting max verification depth to: {} ", effectiveVerifyDepth);
    params.setMaxPathLength(effectiveVerifyDepth);

    CertStore certStore = buildCertStore(validationInfo, untrustedCredential);
    params.addCertStore(certStore);

    boolean isForceRevocationEnabled = false;
    boolean forcedRevocation = false;
    boolean policyMappingInhibited = false;
    boolean anyPolicyInhibited = false;
    Set<String> initialPolicies = null;
    if (options instanceof CertPathPKIXValidationOptions) {
       CertPathPKIXValidationOptions certpathOptions = (CertPathPKIXValidationOptions) options;
       isForceRevocationEnabled = certpathOptions.isForceRevocationEnabled();
       forcedRevocation = certpathOptions.isRevocationEnabled();
       policyMappingInhibited = certpathOptions.isPolicyMappingInhibited();
       anyPolicyInhibited = certpathOptions.isAnyPolicyInhibited();
       initialPolicies = certpathOptions.getInitialPolicies();
    }
    
    if (isForceRevocationEnabled) {
        log.trace("PKIXBuilderParameters#setRevocationEnabled is being forced to: {}", forcedRevocation);
        params.setRevocationEnabled(forcedRevocation);
    } else {
        if (storeContainsCRLs(certStore)) {
            log.trace("At least one CRL was present in cert store, enabling revocation checking");
            params.setRevocationEnabled(true);
        } else {
            log.trace("No CRLs present in cert store, disabling revocation checking");
            params.setRevocationEnabled(false);
        }
    }

    params.setPolicyMappingInhibited(policyMappingInhibited);
    params.setAnyPolicyInhibited(anyPolicyInhibited);

    if (initialPolicies != null && !initialPolicies.isEmpty()) {
        log.debug("PKIXBuilderParameters#setInitialPolicies is being set to: {}", initialPolicies.toString());
        params.setInitialPolicies(initialPolicies);
        params.setExplicitPolicyRequired(true);
    }

    log.trace("PKIXBuilderParameters successfully created: {}", params.toString());

    return params;
}
 
Example 20
Source File: AbstractTrustStore.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private CertPathParameters getParameters(KeyStore trustStore)
{
    try
    {
        final PKIXBuilderParameters parameters = new PKIXBuilderParameters(trustStore, new X509CertSelector());
        parameters.setRevocationEnabled(_certificateRevocationCheckEnabled);
        if (_certificateRevocationCheckEnabled)
        {
            if (_certificateRevocationListUrl != null)
            {
                parameters.addCertStore(
                        CertStore.getInstance("Collection", new CollectionCertStoreParameters(getCRLs())));
            }
            final PKIXRevocationChecker revocationChecker = (PKIXRevocationChecker) CertPathBuilder
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm()).getRevocationChecker();
            final Set<PKIXRevocationChecker.Option> options = new HashSet<>();
            if (_certificateRevocationCheckOfOnlyEndEntityCertificates)
            {
                options.add(PKIXRevocationChecker.Option.ONLY_END_ENTITY);
            }
            if (_certificateRevocationCheckWithPreferringCertificateRevocationList)
            {
                options.add(PKIXRevocationChecker.Option.PREFER_CRLS);
            }
            if (_certificateRevocationCheckWithNoFallback)
            {
                options.add(PKIXRevocationChecker.Option.NO_FALLBACK);
            }
            if (_certificateRevocationCheckWithIgnoringSoftFailures)
            {
                options.add(PKIXRevocationChecker.Option.SOFT_FAIL);
            }
            revocationChecker.setOptions(options);
            parameters.addCertPathChecker(revocationChecker);
        }
        return parameters;
    }
    catch (NoSuchAlgorithmException | KeyStoreException | InvalidAlgorithmParameterException e)
    {
        throw new IllegalConfigurationException("Cannot create trust manager factory parameters for truststore '" +
                getName() + "' :" + e, e);
    }
}