Example usage for org.bouncycastle.cert.jcajce JcaCertStoreBuilder addCertificate

List of usage examples for org.bouncycastle.cert.jcajce JcaCertStoreBuilder addCertificate

Introduction

In this page you can find the example usage for org.bouncycastle.cert.jcajce JcaCertStoreBuilder addCertificate.

Prototype

public JcaCertStoreBuilder addCertificate(X509CertificateHolder cert) 

Source Link

Document

Add a single certificate.

Usage

From source file:CAModulePackage.CertificateHelper.java

/**
 * Validates the certificate chain/path.
 * @param TACerts - Set of Certificates that are the Trust Anchors.
 * @param certificates - List of certificates in the chain/path.
 * @return True if the path is valid, False if it's not.
 *//* www  .j  a  va2  s.c om*/
public static boolean validateCertificatePath(Set<X509CertificateHolder> TACerts,
        ArrayList<X509CertificateHolder> certificates) {
    Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();

    //Convert all our TA Certificates to normal X509Certificates.
    for (X509CertificateHolder cert : TACerts) {

        X509Certificate tempCert = null;
        try {
            tempCert = (new JcaX509CertificateConverter()).getCertificate(cert);
        } catch (CertificateException e) {
            e.printStackTrace();
        }
        trustAnchors.add(new TrustAnchor(tempCert, null));
    }

    PKIXBuilderParameters params = null;
    try {
        params = new PKIXBuilderParameters(trustAnchors, new X509CertSelector());
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }

    //Build a Certificate Store with the certificates from the chain.
    JcaCertStoreBuilder builder = new JcaCertStoreBuilder();
    for (X509CertificateHolder c : certificates) {
        System.out.println("---Chain Cert---");
        System.out.println("SUBJ: " + c.getSubject().toString());
        System.out.println("ISSUER: " + c.getIssuer().toString());
        builder.addCertificate(c);
    }

    //Add the store to the build parameters
    try {
        params.addCertStore(builder.build());
    } catch (GeneralSecurityException ex) {
        Logger.getLogger(CertificateHelper.class.getName()).log(Level.SEVERE, null, ex);
    }

    params.setRevocationEnabled(false);

    //Build the certificate chain - if a result is thrown, we failed.
    PKIXCertPathBuilderSpi pathBuilder = new PKIXCertPathBuilderSpi();
    PKIXCertPathBuilderResult resultPath = null;
    try {
        resultPath = (PKIXCertPathBuilderResult) pathBuilder.engineBuild(params);
    } catch (CertPathBuilderException e) {
        return false;
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }

    return true;
}