Example usage for java.security.cert PKIXBuilderParameters PKIXBuilderParameters

List of usage examples for java.security.cert PKIXBuilderParameters PKIXBuilderParameters

Introduction

In this page you can find the example usage for java.security.cert PKIXBuilderParameters PKIXBuilderParameters.

Prototype

public PKIXBuilderParameters(KeyStore keystore, CertSelector targetConstraints)
        throws KeyStoreException, InvalidAlgorithmParameterException 

Source Link

Document

Creates an instance of PKIXBuilderParameters that populates the set of most-trusted CAs from the trusted certificate entries contained in the specified KeyStore .

Usage

From source file:Main.java

public static CertPathParameters getCertPathParameters() throws InvalidAlgorithmParameterException {
    if ((rootCertificateSS == null) || (theCertSelector == null) || (builder == null)) {
        throw new RuntimeException("Call initCertPathSSCertChain prior to buildCertPath");
    }/*from   w  w w  .j  ava 2s  . c  o  m*/
    PKIXBuilderParameters buildParams = new PKIXBuilderParameters(
            Collections.singleton(new TrustAnchor(rootCertificateSS, null)), theCertSelector);

    buildParams.addCertStore(store);
    buildParams.setRevocationEnabled(false);

    return buildParams;

}

From source file:ch.admin.vbs.cube.core.webservice.CubeSSLSocketFactory.java

/**
 * Create a new SSL socket factory.//from ww w  .jav a  2  s  . c  o m
 * 
 * @param keyStoreBuilder
 *            the key store builder
 * @param trustStore
 *            the trust store
 * @param checkRevocation
 *            <code>true</code> if certificate revocations should be
 *            checked, else <code>false</code>
 * @throws WebServiceException
 *             if the creation failed
 */
public static SSLSocketFactory newSSLSocketFactory(KeyStore.Builder keyStoreBuilder, KeyStore trustStore,
        boolean checkRevocation) throws WebServiceException {
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance("NewSunX509");
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create key manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    KeyStoreBuilderParameters keyStoreBuilderParameters = new KeyStoreBuilderParameters(keyStoreBuilder);
    try {
        keyManagerFactory.init(keyStoreBuilderParameters);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "Unable to initialize key manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    TrustManagerFactory trustManagerFactory;
    try {
        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create trust manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    PKIXBuilderParameters pkixBuilderParameters;
    try {
        pkixBuilderParameters = new PKIXBuilderParameters(trustStore, null);
    } catch (KeyStoreException e) {
        String message = "The trust store is not initialized";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "The trust store does not contain any trusted certificate";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    } catch (NullPointerException e) {
        String message = "The trust store is null";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    pkixBuilderParameters.setRevocationEnabled(checkRevocation);
    CertPathTrustManagerParameters certPathTrustManagerParameters = new CertPathTrustManagerParameters(
            pkixBuilderParameters);
    try {
        trustManagerFactory.init(certPathTrustManagerParameters);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "Unable to initialize trust manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create SSL context";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    try {
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    } catch (KeyManagementException e) {
        String message = "Unable to initialize SSL context";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    return sslSocketFactory;
}

From source file:com.sk89q.mclauncher.security.X509KeyStore.java

/**
 * Verify that a given certificate is trusted.
 * //ww  w.j av a  2s.  com
 * @param chain certificate chain
 * @throws CertPathBuilderException thrown on verification error
 * @throws CertificateVerificationException thrown on any error
 */
public void verify(X509Certificate[] chain) throws CertificateVerificationException, CertPathBuilderException {
    try {
        X509CertSelector selector = new X509CertSelector();
        selector.setCertificate(chain[0]);

        // Root certificates
        Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
        for (X509Certificate rootCert : rootCerts) {
            trustAnchors.add(new TrustAnchor(rootCert, null));
        }

        PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);

        pkixParams.setRevocationEnabled(true);

        // Built-in intermediate certificates
        pkixParams.addCertStore(
                CertStore.getInstance("Collection", new CollectionCertStoreParameters(intermediateCerts)));

        // Additional intermediate certificates
        pkixParams.addCertStore(
                CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays.asList(chain))));

        CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
        builder.build(pkixParams); // Will error on failure to verify
    } catch (InvalidAlgorithmParameterException e) {
        throw new CertificateVerificationException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateVerificationException(e);
    }
}

From source file:com.vmware.identity.idm.IDPConfig.java

/**
 * Validate the chain is in the required order user's certificate first,
 * root CA certificate last including the case of only root CA is present.
 * Also validate that there is only one chain, which consists of all the
 * certificates listed./*from   w  w  w  . j  a  v a2 s.com*/
 */
private static boolean validateSingleX509CertChain(List<X509Certificate> chain)
        throws ExternalIDPExtraneousCertsInCertChainException, ExternalIDPCertChainInvalidTrustedPathException {
    final String ALGO_PKIX = "PKIX"; //for X.509

    final String CERTSTORE_PROVIDER_COLLECTION = "Collection";

    try {
        Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();
        anchors.add(new TrustAnchor(chain.get(chain.size() - 1), null));

        X509CertSelector targetCertSelector = new X509CertSelector();
        targetCertSelector.setCertificate(chain.get(0));

        CertStore builderStore = CertStore.getInstance(CERTSTORE_PROVIDER_COLLECTION,
                new CollectionCertStoreParameters(chain));

        PKIXBuilderParameters buildParams = new PKIXBuilderParameters(anchors, targetCertSelector);
        buildParams.addCertStore(builderStore);
        buildParams.setRevocationEnabled(false);

        CertPathBuilder pathBuilder = CertPathBuilder.getInstance(ALGO_PKIX);
        CertPathBuilderResult builderResult = pathBuilder.build(buildParams);

        if (chain.size() - 1 != builderResult.getCertPath().getCertificates().size()) {
            throw new ExternalIDPExtraneousCertsInCertChainException(chain);
        }
        return true;

    } catch (CertPathBuilderException cpbe) {
        throw new ExternalIDPCertChainInvalidTrustedPathException(cpbe.getMessage(), chain); // no need to chain the exception.
    } catch (GeneralSecurityException gse) {
        throw new ExternalIDPCertChainInvalidTrustedPathException(gse.getMessage(), chain);
    }
}

From source file:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java

/**
 * Create and init PKIXBuilderParameters for CertPathBuilder.
 *
 * @param endCert//from   w w w  .  j  a  v  a  2  s  .c  o  m
 *            the target user certificate to use for building certificate
 *            path
 * @return
 * @throws CertificatePathBuildingException
 */
private PKIXBuilderParameters CreatePKIXBuilderParameters(X509Certificate endCert)
        throws CertificatePathBuildingException {
    X509CertSelector targetConstraints = new X509CertSelector();
    targetConstraints.setCertificate(endCert);
    PKIXBuilderParameters params;

    try {
        params = new PKIXBuilderParameters(trustStore, targetConstraints);

        // Do not validate the certificate at cert path building stage.
        // This would result in unknown failures.
        params.setRevocationEnabled(false);
    } catch (KeyStoreException e) {
        throw new CertificatePathBuildingException(
                "Error creating PKIXBuilderParameters: Please check trust store" + e.getMessage(), e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new CertificatePathBuildingException("Error creating PKIXBuilderParameters:" + e.getMessage(), e);
    } catch (Throwable e) {
        // have this block in case a new type of error was thrown
        throw new CertificatePathBuildingException("Error creating PKIXBuilderParameters:" + e.getMessage(), e);
    }

    Collection<Object> certCollection = new ArrayList<Object>();
    // add trusted CAs to the collection
    addCertificateCandidates(endCert, certCollection);

    if (!certCollection.isEmpty()) {
        try {
            CertStore certStore = CertStore.getInstance("Collection",
                    new CollectionCertStoreParameters(certCollection));
            params.addCertStore(certStore);
        } catch (InvalidAlgorithmParameterException e) {
            throw new CertificatePathBuildingException(
                    "Error creating CertStore for PKIXBuilderParameters:" + e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            throw new CertificatePathBuildingException(
                    "Error creating CertStore for  PKIXBuilderParameters:" + e.getMessage(), e);
        }
    } else {
        logger.debug("Revocation check: CRL list empty");
    }
    return params;

}

From source file:org.apache.cloudstack.network.lb.CertServiceImpl.java

private void validateChain(List<Certificate> chain, Certificate cert) {

    List<Certificate> certs = new ArrayList<Certificate>();
    Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();

    certs.add(cert); // adding for self signed certs
    certs.addAll(chain);//from  w  w  w  .  jav a  2  s.c  o m

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

        X509Certificate xCert = (X509Certificate) c;

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

        anchors.add(new TrustAnchor(xCert, null));
    }

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

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

    } catch (InvalidAlgorithmParameterException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (CertPathBuilderException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchProviderException e) {
        throw new CloudRuntimeException("No provider for certificate validation", e);
    }

}

From source file:org.apache.cloudstack.network.ssl.CertServiceImpl.java

private void validateChain(final List<Certificate> chain, final Certificate cert) {

    final List<Certificate> certs = new ArrayList<Certificate>();
    final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();

    certs.add(cert); // adding for self signed certs
    certs.addAll(chain);//from ww w  .  j ava2s.c  om

    for (final Certificate c : certs) {
        if (!(c instanceof X509Certificate)) {
            throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");
        }
        final X509Certificate xCert = (X509Certificate) c;
        anchors.add(new TrustAnchor(xCert, null));
    }

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

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

    } catch (final InvalidAlgorithmParameterException | CertPathBuilderException | NoSuchAlgorithmException e) {
        throw new IllegalStateException("Invalid certificate chain", e);
    } catch (final NoSuchProviderException e) {
        throw new CloudRuntimeException("No provider for certificate validation", e);
    }

}

From source file:org.zuinnote.hadoop.office.format.common.util.CertificateChainVerificationUtil.java

public static boolean verifyCertificateChain(X509Certificate theCertificate,
        Set<X509Certificate> chainCertificates) throws CertificateException, NoSuchAlgorithmException,
        NoSuchProviderException, InvalidAlgorithmParameterException {

    // check if we can establish a trust chain
    if (isSelfSigned(theCertificate)) {
        LOG.error("Certificate is self-signed - no trust chain can be established with provided truststore");
        return false;
    }// w w  w .ja  v a 2 s  . c  om
    if (chainCertificates.size() < 2) {
        LOG.error(
                "One needs at least three certificates (including certificate used for signing to establish a trust chain. Please check that you included them");
        return false;
    }
    HashSet<X509Certificate> rootCertificates = new HashSet<>();
    HashSet<X509Certificate> subCertificates = new HashSet<>();
    subCertificates.add(theCertificate);
    for (X509Certificate currentCertificate : chainCertificates) {
        if (CertificateChainVerificationUtil.isSelfSigned(currentCertificate)) {
            LOG.debug("Root: " + currentCertificate.getSubjectDN().getName());
            rootCertificates.add(currentCertificate);
        } else {
            LOG.debug("Sub: " + currentCertificate.getSubjectDN().getName());
            subCertificates.add(currentCertificate);
        }
    }
    // Configure verification
    X509CertSelector selector = new X509CertSelector();
    selector.setCertificate(theCertificate);

    CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
    HashSet<TrustAnchor> trustAnchors = new HashSet<>();
    for (X509Certificate currentCertificate : rootCertificates) {
        trustAnchors.add(new TrustAnchor(currentCertificate, null));
    }

    PKIXBuilderParameters builderParams = new PKIXBuilderParameters(trustAnchors, selector);

    CertStore subCertStore = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(subCertificates), "BC");
    builderParams.addCertStore(subCertStore);

    try {
        PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder.build(builderParams);
        return true;
    } catch (CertPathBuilderException e) {
        LOG.error("Exception: ", e);
        LOG.error("Cannot verify certification chain for " + theCertificate.getSubjectX500Principal());
    }
    return false;
}