Example usage for java.security.cert CertificateFactory generateCertPath

List of usage examples for java.security.cert CertificateFactory generateCertPath

Introduction

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

Prototype

public final CertPath generateCertPath(List<? extends Certificate> certificates) throws CertificateException 

Source Link

Document

Generates a CertPath object and initializes it with a List of Certificate s.

Usage

From source file:org.apache.synapse.transport.utils.sslcert.pathvalidation.CertificatePathValidator.java

/**
 * Certificate Path Validation process//from  w  ww . j av  a2 s  . com
 *
 * @throws CertificateVerificationException
 *          if validation process fails.
 */
public void validatePath() throws CertificateVerificationException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    CollectionCertStoreParameters params = new CollectionCertStoreParameters(fullCertChain);
    try {
        CertStore store = CertStore.getInstance("Collection", params, "BC");

        // create certificate path
        CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

        CertPath certPath = fact.generateCertPath(certChain);
        TrustAnchor trustAnchor = new TrustAnchor(fullCertChain.get(fullCertChain.size() - 1), null);
        Set<TrustAnchor> trust = Collections.singleton(trustAnchor);

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

        param.addCertPathChecker(pathChecker);
        param.setRevocationEnabled(false);
        param.addCertStore(store);
        param.setDate(new Date());

        validator.validate(certPath, param);

        log.debug("Certificate path validated");
    } catch (CertPathValidatorException e) {
        throw new CertificateVerificationException("Certificate Path Validation failed on "
                + "certificate number " + e.getIndex() + ", details: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new CertificateVerificationException("Certificate Path Validation failed", e);
    }
}

From source file:org.cesecore.util.CertTools.java

/**
 * Check the certificate with CA certificate.
 * /*from   w  w  w. j a v a  2  s . co  m*/
 * @param certificate cert to verify
 * @param caCertChain collection of X509Certificate
 * @return true if verified OK
 * @throws Exception if verification failed
 */
public static boolean verify(Certificate certificate, Collection<Certificate> caCertChain) throws Exception {
    try {
        ArrayList<Certificate> certlist = new ArrayList<Certificate>();
        // Create CertPath
        certlist.add(certificate);
        // Add other certs...
        CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
        java.security.cert.CertPath cp = cf.generateCertPath(certlist);

        // Create TrustAnchor. Since EJBCA use BouncyCastle provider, we assume
        // certificate already in correct order
        X509Certificate[] cac = (X509Certificate[]) caCertChain.toArray(new X509Certificate[] {});
        java.security.cert.TrustAnchor anchor = new java.security.cert.TrustAnchor(cac[0], null);
        // Set the PKIX parameters
        java.security.cert.PKIXParameters params = new java.security.cert.PKIXParameters(
                java.util.Collections.singleton(anchor));

        params.setRevocationEnabled(false);
        java.security.cert.CertPathValidator cpv = java.security.cert.CertPathValidator.getInstance("PKIX",
                "BC");
        java.security.cert.PKIXCertPathValidatorResult result = (java.security.cert.PKIXCertPathValidatorResult) cpv
                .validate(cp, params);
        if (log.isDebugEnabled()) {
            log.debug("Certificate verify result: " + result.toString());
        }
    } catch (java.security.cert.CertPathValidatorException cpve) {
        throw new Exception(
                "Invalid certificate or certificate not issued by specified CA: " + cpve.getMessage());
    } catch (Exception e) {
        throw new Exception("Error checking certificate chain: " + e.getMessage());
    }
    return true;
}

From source file:org.cesecore.util.CertTools.java

/**
 * Method to create certificate path and to check it's validity from a list of certificates. The list of certificates should only contain one root
 * certificate./*from w  w w  .ja  va 2 s  . com*/
 * 
 * @param certlist
 * @return the certificatepath with the root CA at the end
 * @throws CertPathValidatorException if the certificate chain can not be constructed
 * @throws InvalidAlgorithmParameterException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
public static List<Certificate> createCertChain(Collection<?> certlistin)
        throws CertPathValidatorException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchProviderException, CertificateException {
    final List<Certificate> returnval = new ArrayList<Certificate>();

    Collection<Certificate> certlist = orderCertificateChain(certlistin);

    // set certificate chain
    Certificate rootcert = null;
    ArrayList<Certificate> calist = new ArrayList<Certificate>();
    for (Certificate next : certlist) {
        if (CertTools.isSelfSigned(next)) {
            rootcert = next;
        } else {
            calist.add(next);
        }
    }

    if (calist.isEmpty()) {
        // only one root cert, no certchain
        returnval.add(rootcert);
    } else {
        // We need a bit special handling for CV certificates because those can not be handled using a PKIX CertPathValidator
        Certificate test = calist.get(0);
        if (test.getType().equals("CVC")) {
            if (calist.size() == 1) {
                returnval.add(test);
                returnval.add(rootcert);
            } else {
                throw new CertPathValidatorException(
                        "CVC certificate chain can not be of length longer than two.");
            }
        } else {
            // Normal X509 certificates
            HashSet<TrustAnchor> trustancors = new HashSet<TrustAnchor>();
            TrustAnchor trustanchor = null;
            trustanchor = new TrustAnchor((X509Certificate) rootcert, null);
            trustancors.add(trustanchor);

            // Create the parameters for the validator
            PKIXParameters params = new PKIXParameters(trustancors);

            // Disable CRL checking since we are not supplying any CRLs
            params.setRevocationEnabled(false);
            params.setDate(new Date());

            // Create the validator and validate the path
            CertPathValidator certPathValidator = CertPathValidator
                    .getInstance(CertPathValidator.getDefaultType(), "BC");
            CertificateFactory fact = CertTools.getCertificateFactory();
            CertPath certpath = fact.generateCertPath(calist);

            CertPathValidatorResult result = certPathValidator.validate(certpath, params);

            // Get the certificates validate in the path
            PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
            returnval.addAll(certpath.getCertificates());

            // Get the CA used to validate this path
            TrustAnchor ta = pkixResult.getTrustAnchor();
            X509Certificate cert = ta.getTrustedCert();
            returnval.add(cert);
        }
    }
    return returnval;
}

From source file:org.ejbca.util.CertTools.java

/**
 * Check the certificate with CA certificate.
 *
 * @param certificate cert to verify//from  w  w  w  .j a va2  s.  co m
 * @param caCertPath collection of X509Certificate
 * @return true if verified OK
 * @throws Exception if verification failed
 */
public static boolean verify(Certificate certificate, Collection<Certificate> caCertPath) throws Exception {
    try {
        ArrayList<Certificate> certlist = new ArrayList<Certificate>();
        // Create CertPath
        certlist.add(certificate);
        // Add other certs...         
        CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
        java.security.cert.CertPath cp = cf.generateCertPath(certlist);
        // Create TrustAnchor. Since EJBCA use BouncyCastle provider, we assume
        // certificate already in correct order
        X509Certificate[] cac = (X509Certificate[]) caCertPath.toArray(new X509Certificate[] {});
        java.security.cert.TrustAnchor anchor = new java.security.cert.TrustAnchor(cac[0], null);
        // Set the PKIX parameters
        java.security.cert.PKIXParameters params = new java.security.cert.PKIXParameters(
                java.util.Collections.singleton(anchor));
        params.setRevocationEnabled(false);
        java.security.cert.CertPathValidator cpv = java.security.cert.CertPathValidator.getInstance("PKIX",
                "BC");
        java.security.cert.PKIXCertPathValidatorResult result = (java.security.cert.PKIXCertPathValidatorResult) cpv
                .validate(cp, params);
        if (log.isDebugEnabled()) {
            log.debug("Certificate verify result: " + result.toString());
        }
    } catch (java.security.cert.CertPathValidatorException cpve) {
        throw new Exception(
                "Invalid certificate or certificate not issued by specified CA: " + cpve.getMessage());
    } catch (Exception e) {
        throw new Exception("Error checking certificate chain: " + e.getMessage());
    }
    return true;
}

From source file:org.ejbca.util.CertTools.java

/**
 * Method to create certificate path and to check it's validity from a list of certificates.
 * The list of certificates should only contain one root certificate.
 *
 * @param certlist//from  w w  w. j a  v  a2 s  .  com
 * @return the certificatepath with the root CA at the end, either collection of Certificate or byte[] (der encoded certs)
 * @throws CertPathValidatorException if the certificate chain can not be constructed
 * @throws InvalidAlgorithmParameterException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws CertificateException 
 */
public static Collection<Certificate> createCertChain(Collection<?> certlistin)
        throws CertPathValidatorException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchProviderException, CertificateException {
    ArrayList<Certificate> returnval = new ArrayList<Certificate>();

    Collection<Certificate> certlist = orderCertificateChain(certlistin);

    // set certificate chain
    Certificate rootcert = null;
    ArrayList<Certificate> calist = new ArrayList<Certificate>();
    Iterator<Certificate> iter = certlist.iterator();
    while (iter.hasNext()) {
        Certificate next = iter.next();
        if (CertTools.isSelfSigned(next)) {
            rootcert = next;
        } else {
            calist.add(next);
        }
    }

    if (calist.isEmpty()) {
        // only one root cert, no certchain
        returnval.add(rootcert);
    } else {
        // We need a bit special handling for CV certificates because those can not be handled using a PKIX CertPathValidator
        Certificate test = calist.get(0);
        if (test.getType().equals("CVC")) {
            if (calist.size() == 1) {
                returnval.add(test);
                returnval.add(rootcert);
            } else {
                throw new CertPathValidatorException(
                        "CVC certificate chain can not be of length longer than two.");
            }
        } else {
            // Normal X509 certificates
            HashSet<TrustAnchor> trustancors = new HashSet<TrustAnchor>();
            TrustAnchor trustanchor = null;
            trustanchor = new TrustAnchor((X509Certificate) rootcert, null);
            trustancors.add(trustanchor);

            // Create the parameters for the validator
            PKIXParameters params = new PKIXParameters(trustancors);

            // Disable CRL checking since we are not supplying any CRLs
            params.setRevocationEnabled(false);
            params.setDate(new Date());

            // Create the validator and validate the path
            CertPathValidator certPathValidator = CertPathValidator
                    .getInstance(CertPathValidator.getDefaultType(), "BC");
            CertificateFactory fact = CertTools.getCertificateFactory();
            CertPath certpath = fact.generateCertPath(calist);

            CertPathValidatorResult result = certPathValidator.validate(certpath, params);

            // Get the certificates validate in the path
            PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
            returnval.addAll(certpath.getCertificates());

            // Get the CA used to validate this path
            TrustAnchor ta = pkixResult.getTrustAnchor();
            X509Certificate cert = ta.getTrustedCert();
            returnval.add(cert);
        }
    }
    return returnval;
}

From source file:org.globus.gsi.trustmanager.TrustedCertPathFinder.java

private static CertPath isTrustedCert(KeyStore keyStore, X509Certificate x509Certificate,
        List<X509Certificate> trustedCertPath) throws CertPathValidatorException {
    X509CertSelector certSelector = new X509CertSelector();
    certSelector.setCertificate(x509Certificate);
    Collection<? extends Certificate> caCerts;
    try {/*from   w  w w . j  a  v  a2  s. co m*/
        caCerts = KeyStoreUtil.getTrustedCertificates(keyStore, certSelector);
    } catch (KeyStoreException e) {
        throw new CertPathValidatorException("Error accessing trusted certificate store", e);
    }
    if ((caCerts.size() > 0) && (x509Certificate.getBasicConstraints() != -1)) {

        trustedCertPath.add(x509Certificate);
        // JGLOBUS-92
        try {
            CertificateFactory certFac = CertificateFactory.getInstance("X.509");
            return certFac.generateCertPath(trustedCertPath);
        } catch (CertificateException e) {
            throw new CertPathValidatorException("Error generating trusted certificate path", e);
        }
    }
    return null;
}

From source file:org.globus.gsi.trustmanager.TrustedCertPathFinder.java

/**
 * Method that validates the provided cert path to find a trusted certificate in the certificate store.
 * <p/>//  w ww.ja va  2  s .c o  m
 * For each certificate i in certPath, it is expected that the i+1 certificate is the issuer of the certificate
 * path. See CertPath.
 * <p/>
 * For each certificate i in certpath, validate signature of certificate i get issuer of certificate i get
 * certificate i+i ensure that the certificate i+1 is issuer of certificate i If not, throw an exception for
 * illegal argument validate signature of i+1 Throw exception if it does not validate check if i+1 is a trusted
 * certificate in the trust store. If so return certpath until i+1 If not, continue; If all certificates in the
 * certpath have been checked and none exisits in trust store, check if trust store has certificate of issuer of
 * last certificate in CertPath. If so, return certPath + trusted certificate from trust store If not, throw
 * an exception for lack of valid trust root.
 *
 * @param keyStore The key store containing CA trust root certificates
 * @param certPath The certpath from which to extract a valid cert path to a trusted certificate.
 * @return The valid CertPath.
 * @throws CertPathValidatorException If the CertPath is invalid.
 */
public static CertPath findTrustedCertPath(KeyStore keyStore, CertPath certPath)
        throws CertPathValidatorException {

    // This will be the cert path to return
    List<X509Certificate> trustedCertPath = new ArrayList<X509Certificate>();
    // This is the certs to validate
    List<? extends Certificate> certs = certPath.getCertificates();

    X509Certificate x509Certificate;
    int index = 0;
    int certsSize = certs.size();

    Certificate certificate = certs.get(index);
    if (!(certificate instanceof X509Certificate)) {
        throw new CertPathValidatorException(
                "Certificate of type " + X509Certificate.class.getName() + " required");
    }
    x509Certificate = (X509Certificate) certificate;

    while (index < certsSize) {
        CertPath finalCertPath = isTrustedCert(keyStore, x509Certificate, trustedCertPath);
        if (finalCertPath != null) {
            return finalCertPath;
        }

        if (index + 1 >= certsSize) {
            break;
        }

        index++;
        Certificate issuerCertificate = certs.get(index);
        x509Certificate = checkCertificate(trustedCertPath, x509Certificate, issuerCertificate);
    }

    X509CertSelector selector = new X509CertSelector();
    selector.setSubject(x509Certificate.getIssuerX500Principal());
    Collection<? extends Certificate> caCerts;
    try {
        caCerts = KeyStoreUtil.getTrustedCertificates(keyStore, selector);
    } catch (KeyStoreException e) {
        throw new CertPathValidatorException(e);
    }
    if (caCerts.size() < 1) {
        throw new CertPathValidatorException("No trusted path can be constructed");
    }

    boolean foundTrustRoot = false;

    for (Certificate caCert : caCerts) {
        if (!(caCert instanceof X509Certificate)) {
            logger.warn("Skipped a certificate: not an X509Certificate");
            continue;
        }
        try {
            trustedCertPath.add(checkCertificate(trustedCertPath, x509Certificate, caCert));
            // currently the caCert self-signature is not checked
            // to be consistent with the isTrustedCert() method
            foundTrustRoot = true;
            // we found a CA cert that signed the certificate
            // so we don't need to check any more
            break;
        } catch (CertPathValidatorException e) {
            // fine, just move on to check the next potential CA cert
            // after the loop we'll check whether any were successful
            logger.warn("Failed to validate signature of certificate with " + "subject DN '"
                    + x509Certificate.getSubjectDN() + "' against a CA certificate with issuer DN '"
                    + ((X509Certificate) caCert).getSubjectDN() + "'");
        }
    }

    if (!foundTrustRoot) {
        throw new CertPathValidatorException("No trusted path can be constructed");
    }

    try {
        CertificateFactory certFac = CertificateFactory.getInstance("X.509");
        return certFac.generateCertPath(trustedCertPath);
    } catch (CertificateException e) {
        throw new CertPathValidatorException("Error generating trusted certificate path", e);
    }
}

From source file:org.globus.gsi.util.CertificateUtil.java

public static CertPath getCertPath(X509Certificate[] certs) throws CertificateException {

    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    return factory.generateCertPath(Arrays.asList(certs));
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

boolean validateCertificate(Certificate cert) {
    boolean isValidated;

    if (cert == null) {
        return false;
    }//from   w w w .jav a 2  s  . c  o m

    try {
        KeyStore keyStore = getTrustStore();

        PKIXParameters parms = new PKIXParameters(keyStore);
        parms.setRevocationEnabled(false);

        CertPathValidator certValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType()); // PKIX

        ArrayList<Certificate> start = new ArrayList<>();
        start.add(cert);
        CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT);
        CertPath certPath = certFactory.generateCertPath(start);

        certValidator.validate(certPath, parms);
        isValidated = true;
    } catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException
            | CertificateException | CertPathValidatorException | CryptoException e) {
        logger.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate"
                + cert.toString());
        isValidated = false;
    }

    return isValidated;
}

From source file:org.josso.auth.scheme.validation.AbstractX509CertificateValidator.java

/**
 * Generates certificate path from supplied client certificate
 * and CA certificates.//from  w w w.ja  v a2 s. c o  m
 * 
 * @param clientCertificate client certificate
 * @return certificate path
 * @throws CertificateException
 */
protected CertPath generateCertificatePath(X509Certificate clientCertificate) throws CertificateException {
    if (!_initialized) {
        initialize();
    }
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(clientCertificate);
    certs.addAll(_caCerts);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    return cf.generateCertPath(certs);
}