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.hyperledger.fabric.sdk.security.CryptoPrimitives.java

boolean validateCertificate(Certificate cert) {
    boolean isValidated;

    if (cert == null) {
        return false;
    }/*from   ww w  . jav a2  s.  c om*/

    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.CRLX509CertificateValidator.java

public void validate(X509Certificate certificate) throws X509CertificateValidationException {

    try {/*from  w ww.  j  a v  a2 s  . c  o m*/
        URL crlUrl = null;
        if (_url != null) {
            crlUrl = new URL(_url);
            log.debug("Using the CRL server at: " + _url);
        } else {
            log.debug("Using the CRL server specified in the certificate.");
            System.setProperty("com.sun.security.enableCRLDP", "true");
        }

        // configure the proxy
        if (_httpProxyHost != null && _httpProxyPort != null) {
            System.setProperty("http.proxyHost", _httpProxyHost);
            System.setProperty("http.proxyPort", _httpProxyPort);
        } else {
            System.clearProperty("http.proxyHost");
            System.clearProperty("http.proxyPort");
        }

        // get certificate path
        CertPath cp = generateCertificatePath(certificate);

        // get trust anchors
        Set<TrustAnchor> trustedCertsSet = generateTrustAnchors();

        // init PKIX parameters
        PKIXParameters params = new PKIXParameters(trustedCertsSet);

        // activate certificate revocation checking
        params.setRevocationEnabled(true);

        // disable OCSP
        Security.setProperty("ocsp.enable", "false");

        // get a certificate revocation list
        if (crlUrl != null) {
            URLConnection connection = crlUrl.openConnection();
            connection.setDoInput(true);
            connection.setUseCaches(false);
            DataInputStream inStream = new DataInputStream(connection.getInputStream());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509CRL crl = (X509CRL) cf.generateCRL(inStream);
            inStream.close();
            params.addCertStore(CertStore.getInstance("Collection",
                    new CollectionCertStoreParameters(Collections.singletonList(crl))));
        }

        // perform validation
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
        X509Certificate trustedCert = (X509Certificate) cpvResult.getTrustAnchor().getTrustedCert();

        if (trustedCert == null) {
            log.debug("Trsuted Cert = NULL");
        } else {
            log.debug("Trusted CA DN = " + trustedCert.getSubjectDN());
        }

    } catch (CertPathValidatorException e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    } catch (Exception e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    }
    log.debug("CERTIFICATE VALIDATION SUCCEEDED");
}

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

public void validate(X509Certificate certificate) throws X509CertificateValidationException {

    try {/*from www . j a v  a  2s .c o  m*/
        if (_url != null) {
            log.debug("Using the OCSP server at: " + _url);
            Security.setProperty("ocsp.responderURL", _url);
        } else {
            log.debug("Using the OCSP server specified in the " + "Authority Info Access (AIA) extension "
                    + "of the certificate");
        }

        // configure the proxy
        if (_httpProxyHost != null && _httpProxyPort != null) {
            System.setProperty("http.proxyHost", _httpProxyHost);
            System.setProperty("http.proxyPort", _httpProxyPort);
        } else {
            System.clearProperty("http.proxyHost");
            System.clearProperty("http.proxyPort");
        }

        // get certificate path
        CertPath cp = generateCertificatePath(certificate);

        // get trust anchors
        Set<TrustAnchor> trustedCertsSet = generateTrustAnchors();

        // init PKIX parameters
        PKIXParameters params = new PKIXParameters(trustedCertsSet);

        // init cert store
        Set<X509Certificate> certSet = new HashSet<X509Certificate>();
        if (_ocspCert == null) {
            _ocspCert = getCertificate(_ocspResponderCertificateAlias);
        }
        if (_ocspCert != null) {
            certSet.add(_ocspCert);
            CertStoreParameters storeParams = new CollectionCertStoreParameters(certSet);
            CertStore store = CertStore.getInstance("Collection", storeParams);
            params.addCertStore(store);
            Security.setProperty("ocsp.responderCertSubjectName",
                    _ocspCert.getSubjectX500Principal().getName());
        }

        // activate certificate revocation checking
        params.setRevocationEnabled(true);

        // activate OCSP
        Security.setProperty("ocsp.enable", "true");

        // perform validation
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
        X509Certificate trustedCert = (X509Certificate) cpvResult.getTrustAnchor().getTrustedCert();

        if (trustedCert == null) {
            log.debug("Trsuted Cert = NULL");
        } else {
            log.debug("Trusted CA DN = " + trustedCert.getSubjectDN());
        }

    } catch (CertPathValidatorException e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    } catch (Exception e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    }
    log.debug("CERTIFICATE VALIDATION SUCCEEDED");
}

From source file:org.texai.x509.X509Utils.java

/** Validates the given X.509 certificate path, throwing an exception if the path is invalid.
 *
 * @param certPath the given X.509 certificate path, which does not include the trust anchor in contrast to a
 * certificate chain that does/*from w  w w.  j  a  va2 s .  co  m*/
 *
 * @throws InvalidAlgorithmParameterException if an invalid certificate path validation parameter is provided
 * @throws NoSuchAlgorithmException if an invalid encryption algorithm is specified
 * @throws CertPathValidatorException if the given x.509 certificate path is invalid
 */
public static void validateCertificatePath(final CertPath certPath)
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, CertPathValidatorException {
    //Preconditions
    assert certPath != null : "certPath must not be null";

    final Set<TrustAnchor> trustAnchors = new HashSet<>();
    trustAnchors.add(new TrustAnchor(X509Utils.getRootX509Certificate(), null)); // nameConstraints
    final PKIXParameters params = new PKIXParameters(trustAnchors);
    params.setSigProvider(BOUNCY_CASTLE_PROVIDER);
    params.setRevocationEnabled(false);
    final CertPathValidator certPathValidator = CertPathValidator
            .getInstance(CertPathValidator.getDefaultType());
    certPathValidator.validate(certPath, params);
}

From source file:org.viafirma.nucleo.validacion.CRLValidationHandler.java

/**
 * Metodo encargado de la verificacin de los certificados
 * /*  w ww  . j  a  va  2 s .  c o  m*/
 * @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)

    }
}

From source file:org.wso2.carbon.security.util.ServerCrypto.java

private boolean validateCertPath(KeyStore ks, Certificate[] certs) throws WSSecurityException {

    try {//w w w .j ava 2 s.  c  o m

        // Generate cert path
        java.util.List certList = java.util.Arrays.asList(certs);
        CertPath path = this.getCertificateFactory().generateCertPath(certList);

        // Use the certificates in the keystore as TrustAnchors
        PKIXParameters param = new PKIXParameters(ks);

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

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

From source file:org.wso2.carbon.webapp.ext.cxf.crypto.CXFServerCrypto.java

private boolean validateCertPath(KeyStore ks, Certificate[] certs) throws WSSecurityException {

    try {/*from  w w  w . j  av  a  2  s  .  c  o m*/

        // Generate cert path
        List certList = Arrays.asList(certs);
        CertPath path = this.getCertificateFactory().generateCertPath(certList);

        // Use the certificates in the keystore as TrustAnchors
        PKIXParameters param = new PKIXParameters(ks);

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

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

    return true;
}