Example usage for java.security.cert CertPathValidator getInstance

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

Introduction

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

Prototype

public static CertPathValidator getInstance(String algorithm, Provider provider)
        throws NoSuchAlgorithmException 

Source Link

Document

Returns a CertPathValidator object that implements the specified algorithm.

Usage

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

/**
 * Certificate Path Validation process/*from   ww w .  j ava2s  .c  om*/
 *
 * @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/*from   www.  j av a  2 s .  c  om*/
 *
 * @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

/**
 * 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./*ww w. j  a v a  2  s. 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.//from   ww w  . j  a v  a2  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

/**
 * 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  a  2s .c om*/
 * @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.viafirma.nucleo.validacion.CRLValidationHandler.java

/**
 * Metodo encargado de la verificacin de los certificados
 * /*  ww  w.j  ava 2s  .  com*/
 * @param certificadoX509
 * @throws ExcepcionErrorInterno
 */
public CodigoError validarCRL(X509Certificate certificadoX509) {

    try {
        // 1.- Inicia la factoria de certificados
        CertificateFactory factoriaCertificados = CertificateFactory.getInstance("X.509",
                BouncyCastleProvider.PROVIDER_NAME);
        log.debug("Validando certificado perteneciente a: " + certificadoX509.getIssuerDN());
        CertPathValidator validador = CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);

        // 2.- Configuracin de los parametros del validador
        // 2.1.- Para comprobar que el camino de confianza no esta roto,
        // tengo en cuenta todos los certificados
        PKIXParameters parametros = new PKIXParameters(certificadosConfianza);
        // Fecha para la comprobacin de validez.
        parametros.setDate(new Date());

        if (validacionOnline) {
            // Para la validacin online de del estado de revocacin de los
            // certificados

            // ************
            // creo un almacen( cache ) de certificados y CRLs para no tener
            // que conectarme a las crls
            // en cada validacin

            // Genero un listado de las CRLS que vamos a utilizar para la
            // validacin del certificado.
            List<CRL> listaCRLsCertificadosAlmacenados = new LinkedList<CRL>();

            // Aade las crls de los certificados de confianza reconocidos
            // por Viafirma.
            // estos certificados son los marcados con el prefijo viafirma_
            for (TrustAnchor trustAnchor : certificadosConfianza) {
                // TODO establecer un sistema de cache eficiente
                // TODO recuperar solo las crls del certificado en uso.
                listaCRLsCertificadosAlmacenados
                        .addAll(CRLUtil.getCurrentInstance().getCRLs(trustAnchor.getTrustedCert()));
                // para cada certificado.
            }

            // aado al listado todas las crls del certificado actual. EJ
            // para el caso de
            // un certificado de FNMT el certificado personal contiene CN =
            // CRL1827,OU = FNMT Clase 2 CA,O = FNMT,C = ES
            listaCRLsCertificadosAlmacenados.addAll(CRLUtil.getCurrentInstance().getCRLs(certificadoX509));

            // parametros para la creacin del almacen(cache CRLs)
            CollectionCertStoreParameters params = new CollectionCertStoreParameters(
                    listaCRLsCertificadosAlmacenados);
            CertStore almacen = CertStore.getInstance("Collection", params, BouncyCastleProvider.PROVIDER_NAME);

            parametros.addCertStore(almacen);
        } else {
            // No se utilizan las CRLs para la comprobacin de la
            // revocacin.
            parametros.setRevocationEnabled(false);
        }

        // certificados a validar ( solo 1)
        List<X509Certificate> certificadosValidar = new ArrayList<X509Certificate>(1);
        certificadosValidar.add(certificadoX509);

        // genero el listado de certificados a validar
        CertPath certPath = factoriaCertificados.generateCertPath(certificadosValidar);
        // validacin
        CertPathValidatorResult resultado = validador.validate(certPath, parametros);
        if (log.isDebugEnabled()) {
            if (resultado instanceof java.security.cert.PKIXCertPathValidatorResult) {
                // pintamos el arbol de politicas
                PolicyNode node = ((java.security.cert.PKIXCertPathValidatorResult) resultado).getPolicyTree();
                StringBuffer ruta = new StringBuffer(
                        "Certificado vlido: " + certificadoX509.getSubjectDN().getName());
                while (node != null) {
                    ruta.append("-->");
                    ruta.append(node.getValidPolicy());
                    if (node.getChildren().hasNext()) {
                        node = node.getChildren().next();
                    } else {
                        node = null;
                    }
                }
                log.info("ruta de validacin: " + ruta);
            }
        }
        return CodigoError.OK_CERTIFICADO_VALIDADO;
    } catch (CertificateException e) {
        log.fatal(CodigoError.ERROR_INTERNO, e);
        return CodigoError.ERROR_INTERNO;
    } catch (NoSuchProviderException e) {
        log.fatal(CodigoError.ERROR_INTERNO, e);
        return CodigoError.ERROR_INTERNO;

    } catch (NoSuchAlgorithmException e) {
        log.fatal(CodigoError.ERROR_INTERNO, e);
        return CodigoError.ERROR_INTERNO;
    } catch (InvalidAlgorithmParameterException e) {
        log.fatal(CodigoError.ERROR_VALIDACION_CONFIGURACION_PARAMETRO, e);
        return CodigoError.ERROR_VALIDACION_CONFIGURACION_PARAMETRO;
    } catch (CRLException e) {
        log.fatal(CodigoError.ERROR_VALIDACION_CRL, e);
        return CodigoError.ERROR_VALIDACION_CRL;
    } catch (CertPathValidatorException e) {
        // detectamos el tipo de problema
        if (e.getMessage().contains(java.security.cert.CertificateExpiredException.class.getName())
                || e.getMessage().contains("Certificate revocation after")
                || e.getMessage().contains("NotAfter") || e.getMessage().contains("certificate expired on")) {
            log.warn("El certificado esta caducado." + e.getMessage() + " " + certificadoX509.getSubjectDN());
            return CodigoError.ERROR_VALIDACION_CERTIFICADO_CADUCADO;
        } else if (e.getMessage().contains(java.security.SignatureException.class.getName())) {
            log.warn(
                    "Algunos de los certificados en el camino de certificacin no tiene crl. Algunos de los certificados no se puede validar."
                            + e.getMessage() + " " + certificadoX509.getSubjectDN());
            return CodigoError.ERROR_VALIDACION_CRL;
        } else if (e.getMessage().contains("no valid CRL found")) {
            log.warn("No se ha podido comprobar la validez del certificado. " + e.getMessage() + " "
                    + certificadoX509.getSubjectDN());
            return CodigoError.ERROR_VALIDACION_CRL;
        } else if (e.getMessage().contains("CertPath not found")) {
            log.warn("Autoridad de certificacin no reconicida." + e.getMessage() + " "
                    + certificadoX509.getIssuerDN());
            return CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA;
        } else {
            log.warn("Autoridad de certificacin no reconicida." + e.getMessage() + " "
                    + certificadoX509.getIssuerDN());
            return CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA;
        }

        // TODO java.security.cert.CertPathValidatorException: couldn't
        // validate certificate:
        // java.security.cert.CertificateNotYetValidException: NotBefore:
        // Thu Apr 19 19:22:17 CEST 2007
        // at
        // org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi.engineValidate(PKIXCertPathValidatorSpi.java:819)

    }
}