Example usage for java.security.cert CertPathValidator validate

List of usage examples for java.security.cert CertPathValidator validate

Introduction

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

Prototype

public final CertPathValidatorResult validate(CertPath certPath, CertPathParameters params)
        throws CertPathValidatorException, InvalidAlgorithmParameterException 

Source Link

Document

Validates the specified certification path using the specified algorithm parameter set.

Usage

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

/**
 * Verifies the signature on an enveloped digital signature on a UDDI
 * entity, such as a business, service, tmodel or binding template.
 * <br><Br>/*from w w  w .  java2  s. co m*/
 * It is expected that either the public key of the signing certificate
 * is included within the signature keyinfo section OR that sufficient
 * information is provided in the signature to reference a public key
 * located within the Trust Store provided<br><Br> Optionally, this
 * function also validate the signing certificate using the options
 * provided to the configuration map.
 *
 * @param obj an enveloped signed JAXB object
 * @param OutErrorMessage a human readable error message explaining the
 * reason for failure
 * @return true if the validation passes the signature validation test,
 * and optionally any certificate validation or trust chain validation
 * @throws IllegalArgumentException for null input
 */
public boolean verifySignedUddiEntity(Object obj, AtomicReference<String> OutErrorMessage)
        throws IllegalArgumentException {
    if (OutErrorMessage == null) {
        OutErrorMessage = new AtomicReference<String>();
        OutErrorMessage.set("");
    }
    if (obj == null) {
        throw new IllegalArgumentException("obj");
    }
    try {
        DOMResult domResult = new DOMResult();
        JAXB.marshal(obj, domResult);

        Document doc = ((Document) domResult.getNode());
        Element docElement = doc.getDocumentElement(); //this is our signed node

        X509Certificate signingcert = getSigningCertificatePublicKey(docElement);

        if (signingcert != null) {
            logger.info(
                    "verifying signature based on X509 public key " + signingcert.getSubjectDN().toString());
            if (map.containsKey(CHECK_TIMESTAMPS) && Boolean.parseBoolean(map.getProperty(CHECK_TIMESTAMPS))) {
                signingcert.checkValidity();
            }
            if (map.containsKey(CHECK_REVOCATION_STATUS_OCSP)
                    && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_OCSP))) {
                logger.info("verifying revocation status via OSCP for X509 public key "
                        + signingcert.getSubjectDN().toString());
                X500Principal issuerX500Principal = signingcert.getIssuerX500Principal();
                logger.info("certificate " + signingcert.getSubjectDN().toString() + " was issued by "
                        + issuerX500Principal.getName() + ", attempting to retrieve certificate");
                Security.setProperty("ocsp.enable", "false");
                X509Certificate issuer = FindCertByDN(issuerX500Principal);
                if (issuer == null) {
                    OutErrorMessage.set(
                            "Unable to verify certificate status from OCSP because the issuer of the certificate is not in the trust store. "
                                    + OutErrorMessage.get());
                    //throw new CertificateException("unable to locate the issuers certificate in the trust store");
                } else {
                    RevocationStatus check = OCSP.check(signingcert, issuer);
                    logger.info("certificate " + signingcert.getSubjectDN().toString()
                            + " revocation status is " + check.getCertStatus().toString() + " reason "
                            + check.getRevocationReason().toString());
                    if (check.getCertStatus() != RevocationStatus.CertStatus.GOOD) {
                        OutErrorMessage
                                .set("Certificate status is " + check.getCertStatus().toString() + " reason "
                                        + check.getRevocationReason().toString() + "." + OutErrorMessage.get());

                        //throw new CertificateException("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString());
                    }
                }
            }
            if (map.containsKey(CHECK_REVOCATION_STATUS_CRL)
                    && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_CRL))) {
                logger.info("verifying revokation status via CRL for X509 public key "
                        + signingcert.getSubjectDN().toString());

                Security.setProperty("ocsp.enable", "false");
                System.setProperty("com.sun.security.enableCRLDP", "true");

                X509CertSelector targetConstraints = new X509CertSelector();
                targetConstraints.setCertificate(signingcert);
                PKIXParameters params = new PKIXParameters(GetTrustStore());
                params.setRevocationEnabled(true);
                CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert));

                CertPathValidator certPathValidator = CertPathValidator
                        .getInstance(CertPathValidator.getDefaultType());
                CertPathValidatorResult result = certPathValidator.validate(certPath, params);
                try {
                    PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
                    logger.info("revokation status via CRL PASSED for X509 public key "
                            + signingcert.getSubjectDN().toString());
                } catch (Exception ex) {
                    OutErrorMessage.set("Certificate status is via CRL Failed: " + ex.getMessage() + "."
                            + OutErrorMessage.get());
                }
            }
            if (map.containsKey(CHECK_TRUST_CHAIN)
                    && Boolean.parseBoolean(map.getProperty(CHECK_TRUST_CHAIN))) {
                logger.info("verifying trust chain X509 public key " + signingcert.getSubjectDN().toString());
                try {
                    PKIXParameters params = new PKIXParameters(GetTrustStore());
                    params.setRevocationEnabled(false);
                    CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert));

                    CertPathValidator certPathValidator = CertPathValidator
                            .getInstance(CertPathValidator.getDefaultType());
                    CertPathValidatorResult result = certPathValidator.validate(certPath, params);

                    PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;

                    TrustAnchor ta = pkixResult.getTrustAnchor();
                    X509Certificate cert = ta.getTrustedCert();

                    logger.info(
                            "trust chain validated X509 public key " + signingcert.getSubjectDN().toString());
                } catch (Exception ex) {
                    OutErrorMessage.set("Certificate status Trust validation failed: " + ex.getMessage() + "."
                            + OutErrorMessage.get());
                }
            }
            boolean b = verifySignature(docElement, signingcert.getPublicKey(), OutErrorMessage);
            if ((OutErrorMessage.get() == null || OutErrorMessage.get().length() == 0) && b) {
                //no error message and its cryptographically valid
                return true;
            }
            return false;
        }

        //last chance validation
        logger.info(
                "signature did not have an embedded X509 public key. reverting to user specified certificate");
        //cert wasn't included in the signature, revert to some other means
        KeyStore ks = KeyStore.getInstance(map.getProperty(SIGNATURE_KEYSTORE_FILETYPE));
        URL url = Thread.currentThread().getContextClassLoader()
                .getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE));
        if (url == null) {
            try {
                url = new File(map.getProperty(SIGNATURE_KEYSTORE_FILE)).toURI().toURL();
            } catch (Exception x) {
            }
        }
        if (url == null) {
            try {
                url = this.getClass().getClassLoader().getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE));
            } catch (Exception x) {
            }
        }
        if (url == null) {
            logger.error("");
            OutErrorMessage.set("The signed entity is signed but does not have a certificate attached and"
                    + "you didn't specify a keystore for me to look it up in. " + OutErrorMessage.get());
            return false;
        }
        KeyStore.PrivateKeyEntry keyEntry = null;

        ks.load(url.openStream(), map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray());

        if (map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD) == null) {
            keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                    new KeyStore.PasswordProtection(
                            map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray()));
        } else {
            keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                    new KeyStore.PasswordProtection(
                            map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD).toCharArray()));
        }

        Certificate origCert = keyEntry.getCertificate();
        if (map.containsKey(CHECK_TIMESTAMPS)) {
            if (origCert.getPublicKey() instanceof X509Certificate) {
                X509Certificate x = (X509Certificate) origCert.getPublicKey();
                x.checkValidity();
            }
        }
        PublicKey validatingKey = origCert.getPublicKey();
        return verifySignature(docElement, validatingKey, OutErrorMessage);
    } catch (Exception e) {
        //throw new RuntimeException(e);
        logger.error("Error caught validating signature", e);
        OutErrorMessage.set(e.getMessage());
        return false;
    }
}

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

/**
 * Certificate Path Validation process/*  w  ww  .  j  a v a 2s .co m*/
 *
 * @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.info("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.apache.synapse.transport.utils.sslcert.pathvalidation.CertificatePathValidator.java

/**
 * Certificate Path Validation process/*www .jav a  2 s  .  c  o  m*/
 *
 * @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.apache.ws.security.components.crypto.CryptoBase.java

/**
 * Overridden because there's a bug in the base class where they don't use
 * the provider variant for the certificate validator.
 *
 * @param certs/*w w  w .  j av a2 s  .  c o  m*/
 *            Certificate chain to validate
 * @return true if the certificate chain is valid, false otherwise
 * @throws WSSecurityException
 */
public boolean validateCertPath(java.security.cert.X509Certificate[] certs)
        throws org.apache.ws.security.WSSecurityException {
    try {
        // Generate cert path
        java.util.List cert_list = java.util.Arrays.asList(certs);
        java.security.cert.CertPath path = getCertificateFactory().generateCertPath(cert_list);

        // Use the certificates in the keystore as TrustAnchors
        java.security.cert.PKIXParameters param = new java.security.cert.PKIXParameters(this.keystore);

        // Do not check a revocation list
        param.setRevocationEnabled(false);

        // Verify the trust path using the above settings
        String provider = getCryptoProvider();
        java.security.cert.CertPathValidator validator = null;
        if (provider == null || provider.length() == 0) {
            validator = java.security.cert.CertPathValidator.getInstance("PKIX");
        } else {
            validator = java.security.cert.CertPathValidator.getInstance("PKIX", provider);
        }
        validator.validate(path, param);
    } catch (java.security.NoSuchProviderException e) {
        throw new org.apache.ws.security.WSSecurityException(org.apache.ws.security.WSSecurityException.FAILURE,
                "certpath", new Object[] { e.getMessage() }, e);
    } catch (java.security.NoSuchAlgorithmException e) {
        throw new org.apache.ws.security.WSSecurityException(org.apache.ws.security.WSSecurityException.FAILURE,
                "certpath", new Object[] { e.getMessage() }, e);
    } catch (java.security.cert.CertificateException e) {
        throw new org.apache.ws.security.WSSecurityException(org.apache.ws.security.WSSecurityException.FAILURE,
                "certpath", new Object[] { e.getMessage() }, e);
    } catch (java.security.InvalidAlgorithmParameterException e) {
        throw new org.apache.ws.security.WSSecurityException(org.apache.ws.security.WSSecurityException.FAILURE,
                "certpath", new Object[] { e.getMessage() }, e);
    } catch (java.security.cert.CertPathValidatorException e) {
        throw new org.apache.ws.security.WSSecurityException(org.apache.ws.security.WSSecurityException.FAILURE,
                "certpath", new Object[] { e.getMessage() }, e);
    } catch (java.security.KeyStoreException e) {
        throw new org.apache.ws.security.WSSecurityException(org.apache.ws.security.WSSecurityException.FAILURE,
                "certpath", new Object[] { e.getMessage() }, e);
    }

    return true;
}

From source file:org.apache.ws.security.components.crypto.Merlin.java

/**
 * Evaluate whether a given certificate chain should be trusted.
 * Uses the CertPath API to validate a given certificate chain.
 *
 * @param certs Certificate chain to validate
 * @param enableRevocation whether to enable CRL verification or not
 * @return true if the certificate chain is valid, false otherwise
 * @throws WSSecurityException//w  w w  . j  a  v a  2 s . c  o  m
 */
public boolean verifyTrust(X509Certificate[] certs, boolean enableRevocation) throws WSSecurityException {
    try {
        // Generate cert path
        List<X509Certificate> certList = Arrays.asList(certs);
        CertPath path = getCertificateFactory().generateCertPath(certList);

        Set<TrustAnchor> set = new HashSet<TrustAnchor>();
        if (truststore != null) {
            Enumeration<String> truststoreAliases = truststore.aliases();
            while (truststoreAliases.hasMoreElements()) {
                String alias = truststoreAliases.nextElement();
                X509Certificate cert = (X509Certificate) truststore.getCertificate(alias);
                if (cert != null) {
                    TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue(NAME_CONSTRAINTS_OID));
                    set.add(anchor);
                }
            }
        }

        //
        // Add certificates from the keystore - only if there is no TrustStore, apart from
        // the case that the truststore is the JDK CA certs. This behaviour is preserved
        // for backwards compatibility reasons
        //
        if (keystore != null && (truststore == null || loadCACerts)) {
            Enumeration<String> aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                X509Certificate cert = (X509Certificate) keystore.getCertificate(alias);
                if (cert != null) {
                    TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue(NAME_CONSTRAINTS_OID));
                    set.add(anchor);
                }
            }
        }

        PKIXParameters param = new PKIXParameters(set);
        param.setRevocationEnabled(enableRevocation);
        if (enableRevocation && crlCertStore != null) {
            param.addCertStore(crlCertStore);
        }

        // Verify the trust path using the above settings
        String provider = getCryptoProvider();
        CertPathValidator validator = null;
        if (provider == null || provider.length() == 0) {
            validator = CertPathValidator.getInstance("PKIX");
        } else {
            validator = CertPathValidator.getInstance("PKIX", provider);
        }
        validator.validate(path, param);
        return true;
    } catch (java.security.NoSuchProviderException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (java.security.NoSuchAlgorithmException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (java.security.cert.CertificateException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (java.security.InvalidAlgorithmParameterException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (java.security.cert.CertPathValidatorException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (java.security.KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (NullPointerException e) {
        // NPE thrown by JDK 1.7 for one of the test cases
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    }
}

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

/**
 * Check the certificate with CA certificate.
 * /*from   w ww .  ja  va2s .c  o  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 .j  a  v a2s  . c  o m*/
 * 
 * @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.extra.db.ExtRAMsgHelper.java

/**
 * Method used to verify signed data./*  w  w  w . ja v a  2  s .c  o  m*/
 * 
 * @param TrustedCACerts a Collection of trusted certificates, should contain the entire chains
 * @param TrustedCRLs a Collection of trusted CRLS, use null if no CRL check should be used.
 * @param signedData the data to verify
 * @param date the date used to check the validity against.
 * @return a ParsedSignatureResult.
 */
public static ParsedSignatureResult verifySignature(Collection cACertChain, Collection trustedCRLs,
        byte[] signedData, Date date) {
    boolean verifies = false;
    X509Certificate usercert = null;
    ParsedSignatureResult retval = new ParsedSignatureResult(false, null, null);
    byte[] content = null;

    try {
        // First verify the signature
        CMSSignedData sp = new CMSSignedData(signedData);

        CertStore certs = sp.getCertificatesAndCRLs("Collection", "BC");
        SignerInformationStore signers = sp.getSignerInfos();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ((CMSProcessableByteArray) sp.getSignedContent()).write(baos);
        content = baos.toByteArray();
        baos.close();

        Collection c = signers.getSigners();
        Iterator it = c.iterator();

        while (it.hasNext()) {
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = certs.getCertificates(signer.getSID());

            Iterator certIt = certCollection.iterator();
            usercert = (X509Certificate) certIt.next();

            boolean validalg = signer.getDigestAlgOID().equals(signAlg);

            verifies = validalg && signer.verify(usercert.getPublicKey(), "BC");

        }

        // Second validate the certificate           
        X509Certificate rootCert = null;
        Iterator iter = cACertChain.iterator();
        while (iter.hasNext()) {
            X509Certificate cert = (X509Certificate) iter.next();
            if (cert.getIssuerDN().equals(cert.getSubjectDN())) {
                rootCert = cert;
                break;
            }
        }

        if (rootCert == null) {
            throw new CertPathValidatorException("Error Root CA cert not found in cACertChain");
        }

        List list = new ArrayList();
        list.add(usercert);
        list.add(cACertChain);
        if (trustedCRLs != null) {
            list.add(trustedCRLs);
        }

        CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list);
        CertStore store = CertStore.getInstance("Collection", ccsp);

        //validating path
        List certchain = new ArrayList();
        certchain.addAll(cACertChain);
        certchain.add(usercert);
        CertPath cp = CertificateFactory.getInstance("X.509", "BC").generateCertPath(certchain);

        Set trust = new HashSet();
        trust.add(new TrustAnchor(rootCert, null));

        CertPathValidator cpv = CertPathValidator.getInstance("PKIX", "BC");
        PKIXParameters param = new PKIXParameters(trust);
        param.addCertStore(store);
        param.setDate(date);
        if (trustedCRLs == null) {
            param.setRevocationEnabled(false);
        } else {
            param.setRevocationEnabled(true);
        }
        cpv.validate(cp, param);
        retval = new ParsedSignatureResult(verifies, usercert, content);
    } catch (Exception e) {
        log.error("Error verifying data : ", e);
    }

    return retval;
}

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

/**
 * Check the certificate with CA certificate.
 *
 * @param certificate cert to verify//from  www  .  j av  a 2 s .c  o  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//w  w  w .j a  v a2 s. c o m
 * @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;
}