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

The following examples show how to use java.security.cert.PKIXBuilderParameters#setRevocationEnabled() . 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: SSLUtils.java    From ssltest with Apache License 2.0 6 votes vote down vote up
/**
 * Return the initialization parameters for the TrustManager.
 * Currently, only the default <code>PKIX</code> is supported.
 *
 * @param algorithm The algorithm to get parameters for.
 * @param crlFilename The path to the CRL file.
 * @param maxCertificateChainLength Optional maximum cert chain length.
 * @param trustStore The configured TrustStore.
 *
 * @return The parameters including the TrustStore and any CRLs.
 *
 * @throws InvalidAlgorithmParameterException
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws CRLException
 * @throws NoSuchAlgorithmException
 */
protected static CertPathParameters getParameters(String algorithm,
                                                  String crlFilename,
                                                  Integer maxCertificateChainLength,
                                                  KeyStore trustStore)
    throws KeyStoreException, InvalidAlgorithmParameterException, CRLException, CertificateException, IOException, NoSuchAlgorithmException
{
    CertPathParameters params = null;
    if("PKIX".equalsIgnoreCase(algorithm)) {
        PKIXBuilderParameters xparams =
            new PKIXBuilderParameters(trustStore, new X509CertSelector());
        Collection<? extends CRL> crls = getCRLs(crlFilename);
        CertStoreParameters csp = new CollectionCertStoreParameters(crls);
        CertStore store = CertStore.getInstance("Collection", csp);
        xparams.addCertStore(store);
        xparams.setRevocationEnabled(true);

        if(maxCertificateChainLength != null)
            xparams.setMaxPathLength(maxCertificateChainLength.intValue());

        params = xparams;
    } else {
        throw new CRLException("CRLs not supported for type: " + algorithm);
    }
    return params;
}
 
Example 2
Source File: BuildOddSel.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void createParams() throws Exception {
    TrustAnchor anchor = new TrustAnchor(getCertFromFile("sun.cer"), null);
    Set anchors = Collections.singleton(anchor);
    // Create odd CertSelector
    sel = new OddSel();
    params = new PKIXBuilderParameters(anchors, sel);
    params.setRevocationEnabled(false);
}
 
Example 3
Source File: SparkExceptionsTrustManager.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
    }

}
 
Example 4
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 5
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 6
Source File: BuildOddSel.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void createParams() throws Exception {
    TrustAnchor anchor = new TrustAnchor(getCertFromFile("sun.cer"), null);
    Set anchors = Collections.singleton(anchor);
    // Create odd CertSelector
    sel = new OddSel();
    params = new PKIXBuilderParameters(anchors, sel);
    params.setRevocationEnabled(false);
}
 
Example 7
Source File: BuildOddSel.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void createParams() throws Exception {
    TrustAnchor anchor = new TrustAnchor(getCertFromFile("sun.cer"), null);
    Set anchors = Collections.singleton(anchor);
    // Create odd CertSelector
    sel = new OddSel();
    params = new PKIXBuilderParameters(anchors, sel);
    params.setRevocationEnabled(false);
}
 
Example 8
Source File: NoExtensions.java    From openjdk-8 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 9
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 10
Source File: BuildEEBasicConstraints.java    From jdk8u60 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 11
Source File: BuildOddSel.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void createParams() throws Exception {
    TrustAnchor anchor = new TrustAnchor(getCertFromFile("sun.cer"), null);
    Set anchors = Collections.singleton(anchor);
    // Create odd CertSelector
    sel = new OddSel();
    params = new PKIXBuilderParameters(anchors, sel);
    params.setRevocationEnabled(false);
}
 
Example 12
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 13
Source File: BuildOddSel.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void createParams() throws Exception {
    TrustAnchor anchor = new TrustAnchor(getCertFromFile("sun.cer"), null);
    Set anchors = Collections.singleton(anchor);
    // Create odd CertSelector
    sel = new OddSel();
    params = new PKIXBuilderParameters(anchors, sel);
    params.setRevocationEnabled(false);
}
 
Example 14
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 15
Source File: BuildOddSel.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void createParams() throws Exception {
    TrustAnchor anchor = new TrustAnchor(getCertFromFile("sun.cer"), null);
    Set anchors = Collections.singleton(anchor);
    // Create odd CertSelector
    sel = new OddSel();
    params = new PKIXBuilderParameters(anchors, sel);
    params.setRevocationEnabled(false);
}
 
Example 16
Source File: ConstructorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void testCtorByPKIXBuilderParams(Set<X509Certificate> certSet)
        throws Exception {
    Set<TrustAnchor> taSet = makeTrustAnchorSet(certSet);
    Validator valOK;
    Validator valNoGood;
    X509Certificate[] chain = new X509Certificate[1];
    Set<X509Certificate> intermeds = new HashSet<>();

    // Case 7: Make a PKIXValidator with valid arguments
    // Expected result: Well-formed PKIXValidator object
    System.out.println("Constructor test 7: Valid inputs");

    // Set up the PKIXBuilderParameters
    X509CertSelector sel = new X509CertSelector();
    sel.setSubject("CN=User");
    PKIXBuilderParameters pbParams = new PKIXBuilderParameters(taSet, sel);
    pbParams.setRevocationEnabled(false);
    pbParams.setDate(new Date(1426399200000L)); // 03-15-2014 6:00:00 GMT

    valOK = Validator.getInstance(Validator.TYPE_PKIX,
            Validator.VAR_GENERIC, pbParams);

    // Convert our user cert from PEM format, then do the same for
    // its intermediate signer and add that as a helper for path building
    chain[0] = makeCertFromPEM(USER);
    intermeds.add(makeCertFromPEM(INTERMED));

    showValidatedChain(valOK, chain, intermeds);

    // Case 8: Make a PKIXValidator but provide a null PKIXBuilderParameters
    // Expected result: throw NullPointerException
    System.out.println("Constructor test 8: null params");
    try {
        valNoGood = Validator.getInstance(Validator.TYPE_PKIX,
                Validator.VAR_GENERIC, (PKIXBuilderParameters)null);
        // Throw something non Runtime-related to indicate we shouldn't
        // have succeeded on construction.
        throw new IOException(
                "Constructor did not throw NullPointerException");
    } catch (NullPointerException npe) {
        System.out.println("\tCaught RuntimeException (" + npe.toString() +
                ") [PASS])");
    }
}
 
Example 17
Source File: TrustManagerTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testOSCPOverride() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = TrustManagerTest.class.getResource("client-trust.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL url = SOAPService.WSDL_LOCATION;
    SOAPService service = new SOAPService(url, SOAPService.SERVICE);
    assertNotNull("Service is null", service);
    final Greeter port = service.getHttpsPort();
    assertNotNull("Port is null", port);

    updateAddressPort(port, PORT2);

    // Enable Async
    if (async) {
        ((BindingProvider)port).getRequestContext().put("use.async.http.conduit", true);
    }

    // Read truststore
    KeyStore ts = KeyStore.getInstance("JKS");
    try (InputStream trustStore =
        ClassLoaderUtils.getResourceAsStream("keys/cxfca.jks", TrustManagerTest.class)) {
        ts.load(trustStore, "password".toCharArray());
    }

    try {
        Security.setProperty("ocsp.enable", "true");

        PKIXBuilderParameters param = new PKIXBuilderParameters(ts, new X509CertSelector());
        param.setRevocationEnabled(true);

        TrustManagerFactory tmf  =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(new CertPathTrustManagerParameters(param));

        TLSClientParameters tlsParams = new TLSClientParameters();
        tlsParams.setTrustManagers(tmf.getTrustManagers());
        tlsParams.setDisableCNCheck(true);

        Client client = ClientProxy.getClient(port);
        HTTPConduit http = (HTTPConduit) client.getConduit();
        http.setTlsClientParameters(tlsParams);

        try {
            port.greetMe("Kitty");
            fail("Failure expected on an invalid OCSP responder URL");
        } catch (Exception ex) {
            // expected
        }

    } finally {
        Security.setProperty("ocsp.enable", "false");
    }

    ((java.io.Closeable)port).close();
    bus.shutdown(true);
}
 
Example 18
Source File: CertificateValidator.java    From IoTgo_Android_App with MIT License 4 votes vote down vote up
public void validate(Certificate[] certChain) throws CertificateException
{
    try
    {
        ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
        for (Certificate item : certChain)
        {
            if (item == null)
                continue;
            
            if (!(item instanceof X509Certificate))
            {
                throw new IllegalStateException("Invalid certificate type in chain");
            }
            
            certList.add((X509Certificate)item);
        }

        if (certList.isEmpty())
        {
            throw new IllegalStateException("Invalid certificate chain");
            
        }

        X509CertSelector certSelect = new X509CertSelector();
        certSelect.setCertificate(certList.get(0));
        
        // Configure certification path builder parameters
        PKIXBuilderParameters pbParams = new PKIXBuilderParameters(_trustStore, certSelect);
        pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList)));

        // Set maximum certification path length
        pbParams.setMaxPathLength(_maxCertPathLength);

        // Enable revocation checking
        pbParams.setRevocationEnabled(true);

        // Set static Certificate Revocation List
        if (_crls != null && !_crls.isEmpty())
        {
            pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(_crls)));
        }

        // Enable On-Line Certificate Status Protocol (OCSP) support
        if (_enableOCSP)
        {
            Security.setProperty("ocsp.enable","true");
        }
        // Enable Certificate Revocation List Distribution Points (CRLDP) support
        if (_enableCRLDP)
        {
            System.setProperty("com.sun.security.enableCRLDP","true");
        }

        // Build certification path
        CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams);               
        
        // Validate certification path
        CertPathValidator.getInstance("PKIX").validate(buildResult.getCertPath(),pbParams);
    }
    catch (GeneralSecurityException gse)
    {
        LOG.debug(gse);
        throw new CertificateException("Unable to validate certificate: " + gse.getMessage(), gse);
    }
}
 
Example 19
Source File: CertificateValidator.java    From WebSocket-for-Android with Apache License 2.0 4 votes vote down vote up
public void validate(Certificate[] certChain) throws CertificateException
{
    try
    {
        ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
        for (Certificate item : certChain)
        {
            if (item == null)
                continue;

            if (!(item instanceof X509Certificate))
            {
                throw new IllegalStateException("Invalid certificate type in chain");
            }

            certList.add((X509Certificate)item);
        }

        if (certList.isEmpty())
        {
            throw new IllegalStateException("Invalid certificate chain");

        }

        X509CertSelector certSelect = new X509CertSelector();
        certSelect.setCertificate(certList.get(0));

        // Configure certification path builder parameters
        PKIXBuilderParameters pbParams = new PKIXBuilderParameters(_trustStore, certSelect);
        pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList)));

        // Set maximum certification path length
        pbParams.setMaxPathLength(_maxCertPathLength);

        // Enable revocation checking
        pbParams.setRevocationEnabled(true);

        // Set static Certificate Revocation List
        if (_crls != null && !_crls.isEmpty())
        {
            pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(_crls)));
        }

        // Enable On-Line Certificate Status Protocol (OCSP) support
        if (_enableOCSP)
        {
            Security.setProperty("ocsp.enable","true");
        }
        // Enable Certificate Revocation List Distribution Points (CRLDP) support
        if (_enableCRLDP)
        {
            System.setProperty("com.sun.security.enableCRLDP","true");
        }

        // Build certification path
        CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams);

        // Validate certification path
        CertPathValidator.getInstance("PKIX").validate(buildResult.getCertPath(),pbParams);
    }
    catch (GeneralSecurityException gse)
    {
        LOG.debug(gse);
        throw new CertificateException("Unable to validate certificate: " + gse.getMessage(), gse);
    }
}
 
Example 20
Source File: CertificateValidator.java    From cloudhopper-commons with Apache License 2.0 4 votes vote down vote up
public void validate(Certificate[] certChain) throws CertificateException {
    try {
        ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
        for (Certificate item : certChain) {
            if (item == null) continue;
            if (!(item instanceof X509Certificate)) {
                throw new IllegalStateException("Invalid certificate type in chain");
            }
            certList.add((X509Certificate)item);
        }

        if (certList.isEmpty()) {
            throw new IllegalStateException("Invalid certificate chain");
        }

        X509CertSelector certSelect = new X509CertSelector();
        certSelect.setCertificate(certList.get(0));
        
        // Configure certification path builder parameters
        PKIXBuilderParameters pbParams = new PKIXBuilderParameters(trustStore, certSelect);
        pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList)));

        // Set maximum certification path length
        pbParams.setMaxPathLength(maxCertPathLength);

        // Enable revocation checking
        pbParams.setRevocationEnabled(true);

        // Set static Certificate Revocation List
        if (crls != null && !crls.isEmpty()) {
            pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crls)));
        }

        // Enable On-Line Certificate Status Protocol (OCSP) support
        if (enableOCSP) {
            Security.setProperty("ocsp.enable","true");
        }
        // Enable Certificate Revocation List Distribution Points (CRLDP) support
        if (enableCRLDP) {
            System.setProperty("com.sun.security.enableCRLDP","true");
        }

        // Build certification path
        CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams);               
        
        // Validate certification path
        CertPathValidator.getInstance("PKIX").validate(buildResult.getCertPath(),pbParams);
    } catch (GeneralSecurityException gse) {
        logger.debug("", gse);
        throw new CertificateException("Unable to validate certificate: " + gse.getMessage(), gse);
    }
}