Example usage for java.security.cert X509CertSelector X509CertSelector

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

Introduction

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

Prototype

public X509CertSelector() 

Source Link

Document

Creates an X509CertSelector .

Usage

From source file:org.globus.gsi.TrustedCertificates.java

public synchronized void reload(String locations) {
    if (locations == null) {
        return;/*from   w w w  .j  a v  a2s . c o  m*/
    }

    this.changed = false;

    StringTokenizer tokens = new StringTokenizer(locations, ",");
    File caDir = null;

    Map newCertSubjectDNMap = new HashMap();
    Map newSigningDNMap = new HashMap();

    while (tokens.hasMoreTokens()) {
        caDir = new File(tokens.nextToken().toString().trim());

        if (!caDir.canRead()) {
            logger.debug("Cannot read: " + caDir.getAbsolutePath());
            continue;
        }

        String caCertLocation = "file:" + caDir.getAbsolutePath();
        //            String sigPolPattern = caCertLocation + "/*.signing_policy";
        //            if (!caDir.isDirectory()) {
        //                sigPolPattern = getPolicyFileName(caCertLocation);
        //            }

        try {
            ms_trustStore = Stores.getTrustStore(caCertLocation + "/" + Stores.getDefaultCAFilesPattern());

            Collection<? extends Certificate> caCerts = KeyStoreUtil.getTrustedCertificates(ms_trustStore,
                    new X509CertSelector());
            Iterator iter = caCerts.iterator();
            while (iter.hasNext()) {
                X509Certificate cert = (X509Certificate) iter.next();
                if (!newCertSubjectDNMap.containsKey(cert.getSubjectDN().toString()))
                    newCertSubjectDNMap.put(cert.getSubjectDN().toString(), cert);
            }
        } catch (Exception e) {
            logger.warn("Failed to create trust store", e);
        }

        try {
            ms_sigPolStore = Stores
                    .getSigningPolicyStore(caCertLocation + "/" + Stores.getDefaultSigningPolicyFilesPattern());
        } catch (GeneralSecurityException e) {
            logger.warn("Failed to create signing_policy store", e);
        }

        try {
            ms_sigPolStore = Stores
                    .getSigningPolicyStore(caCertLocation + "/" + Stores.getDefaultSigningPolicyFilesPattern());
            Collection<? extends Certificate> caCerts = KeyStoreUtil.getTrustedCertificates(ms_trustStore,
                    new X509CertSelector());
            Iterator iter = caCerts.iterator();
            while (iter.hasNext()) {
                X509Certificate cert = (X509Certificate) iter.next();
                X500Principal principal = cert.getSubjectX500Principal();
                if (!newCertSubjectDNMap.containsKey(cert.getSubjectDN().toString())) {
                    continue;
                }
                SigningPolicy policy;
                try {
                    policy = ms_sigPolStore.getSigningPolicy(principal);
                } catch (Exception e) {
                    if (!invalidPolicies.contains(principal)) {
                        logger.warn("Invalid signing policy for CA certificate; skipping");
                        logger.debug("Invalid signing policy for CA certificate; skipping", e);
                        invalidPolicies.add(principal);
                    }
                    continue;
                }
                if (policy != null) {
                    newSigningDNMap.put(CertificateUtil.toGlobusID(policy.getCASubjectDN()), policy);
                } else {
                    if (!invalidPolicies.contains(principal)) {
                        logger.warn("no signing policy for ca cert " + cert.getSubjectDN());
                        invalidPolicies.add(principal);
                    }
                }
            }
        } catch (Exception e) {
            logger.warn("Failed to create signing policy store", e);
        }
    }

    this.changed = true;
    this.certSubjectDNMap = newCertSubjectDNMap;
    this.policyDNMap = newSigningDNMap;

    if (this.changed) {
        this.certList = null;
    }
}

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 a 2s . c  om
        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/>//from  w  w  w. j  av  a 2 s.c  om
 * 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.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;
    }/*from   w  ww .  java 2s  . co m*/
    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;
}