Example usage for java.security.cert TrustAnchor getTrustedCert

List of usage examples for java.security.cert TrustAnchor getTrustedCert

Introduction

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

Prototype

public final X509Certificate getTrustedCert() 

Source Link

Document

Returns the most-trusted CA certificate.

Usage

From source file:mitm.common.security.crl.PKITSTest.java

@Test
public void test_4_4_11_Invalid_Old_CRL_nextUpdate_Test11() throws Exception {
    // add certificates
    addCertificates(new File(testBase, "certs/OldCRLnextUpdateCACert.crt"), certStoreParams.getCertStore());
    addCertificates(new File(testBase, "certs/InvalidOldCRLnextUpdateTest11EE.crt"),
            certStoreParams.getCertStore());

    // add crls//from w w w .  j av  a 2s  .  c o m
    addCRL(new File(testBase, "crls/TrustAnchorRootCRL.crl"), certStoreParams.getCRLStore());
    addCRL(new File(testBase, "crls/OldCRLnextUpdateCACRL.crl"), certStoreParams.getCRLStore());

    X509CertSelector selector = new X509CertSelector();

    selector.setSerialNumber(BigIntegerUtils.hexDecode("1"));
    selector.setIssuer("CN=Old CRL nextUpdate CA, O=Test Certificates, C=US");

    PKIXCertPathBuilderResult result = getCertPathBuilderResult(selector);

    CertPath certPath = result.getCertPath();

    TrustAnchor trustAnchor = result.getTrustAnchor();

    assertNotNull(trustAnchor);
    assertEquals("CN=Trust Anchor, O=Test Certificates, C=US",
            trustAnchor.getTrustedCert().getSubjectX500Principal().toString());

    PKIXRevocationChecker revocationChecker = new PKIXRevocationChecker(certStoreParams.getCRLStore());

    Date now = TestUtils.parseDate("02-Jan-2002 16:38:35 GMT");

    RevocationResult revocationResult = revocationChecker.getRevocationStatus(certPath, trustAnchor, now);

    assertEquals(RevocationStatus.EXPIRED, revocationResult.getStatus());
    assertEquals(null, revocationResult.getReason());

    RevocationDetail[] detail = revocationResult.getDetails();

    assertEquals(detail.length, 2);
    assertEquals(RevocationStatus.EXPIRED, detail[0].getStatus());
    assertTrue(DateUtils.addDays(detail[0].getNextUpdate(), 2).after(now));
    assertEquals(RevocationStatus.NOT_REVOKED, detail[1].getStatus());
}

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 ww  .j  a  v  a2 s  . c om*/
 * 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.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./* w  w w  .  ja v  a2 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.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/*  www  . j  a  va2  s .  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.globus.gsi.stores.PEMKeyStore.java

private void loadDirectories(String directoryList) throws CertificateException {

    try {/*w w  w  .  j  av  a  2  s. co  m*/
        caDelegate.loadWrappers(directoryList);
        Map<String, ResourceTrustAnchor> wrapperMap = caDelegate.getWrapperMap();
        Set<String> knownCerts = new HashSet<String>();
        // The alias hashing merits explanation.  Loading all the files in a directory triggers a
        // deadlock bug for old jglobus clients if the directory contains repeated CAs (like the
        // modern IGTF bundle does).  So, we ignore the cert if the alias is incorrect or already seen.
        // However, we track all the certs we ignore and load any that were completely ignored due to
        // aliases.  So, non-hashed directories will still work.
        Map<String, String> ignoredAlias = new HashMap<String, String>();
        Map<String, ResourceTrustAnchor> ignoredAnchor = new HashMap<String, ResourceTrustAnchor>();
        Map<String, X509Certificate> ignoredCert = new HashMap<String, X509Certificate>();
        for (ResourceTrustAnchor trustAnchor : wrapperMap.values()) {
            String alias = trustAnchor.getResourceURL().toExternalForm();
            TrustAnchor tmpTrustAnchor = trustAnchor.getTrustAnchor();
            X509Certificate trustCert = tmpTrustAnchor.getTrustedCert();
            String hash = CertificateIOUtil.nameHash(trustCert.getSubjectX500Principal());
            if (this.aliasObjectMap == null) {
                System.out.println("Alias Map Null");
            }
            boolean hash_in_alias = !alias.contains(hash);
            if (knownCerts.contains(hash) || !hash_in_alias) {
                if (!hash_in_alias) {
                    ignoredAlias.put(hash, alias);
                    ignoredAnchor.put(hash, trustAnchor);
                    ignoredCert.put(hash, trustCert);
                }
                continue;
            }
            knownCerts.add(hash);
            this.aliasObjectMap.put(alias, trustAnchor);
            certFilenameMap.put(trustCert, alias);
        }
        // Add any CA we skipped above.
        for (String hash : ignoredAlias.keySet()) {
            if (knownCerts.contains(hash)) {
                continue;
            }
            String alias = ignoredAlias.get(hash);
            this.aliasObjectMap.put(alias, ignoredAnchor.get(hash));
            certFilenameMap.put(ignoredCert.get(hash), alias);
        }
    } catch (ResourceStoreException e) {
        throw new CertificateException("", e);
    }
}

From source file:org.globus.gsi.stores.ResourceCertStore.java

/**
 * Returns a <code>Collection</code> of <code>Certificate</code>s that match
 * the specified selector. If no <code>Certificate</code>s match the
 * selector, an empty <code>Collection</code> will be returned.
 * <p/>//from   w ww.  ja va 2s .  c o m
 * For some <code>CertStore</code> types, the resulting
 * <code>Collection</code> may not contain <b>all</b> of the
 * <code>Certificate</code>s that match the selector. For instance, an LDAP
 * <code>CertStore</code> may not search all entries in the directory.
 * Instead, it may just search entries that are likely to contain the
 * <code>Certificate</code>s it is looking for.
 * <p/>
 * Some <code>CertStore</code> implementations (especially LDAP
 * <code>CertStore</code>s) may throw a <code>CertStoreException</code>
 * unless a non-null <code>CertSelector</code> is provided that includes
 * specific criteria that can be used to find the certificates. Issuer
 * and/or subject names are especially useful criteria.
 *
 * @param selector
 *            A <code>CertSelector</code> used to select which
 *            <code>Certificate</code>s should be returned. Specify
 *            <code>null</code> to return all <code>Certificate</code>s (if
 *            supported).
 * @return A <code>Collection</code> of <code>Certificate</code>s that match
 *         the specified selector (never <code>null</code>)
 * @throws java.security.cert.CertStoreException
 *             if an exception occurs
 */
public Collection<? extends Certificate> engineGetCertificates(CertSelector selector)
        throws CertStoreException {
    logger.debug("selecting Certificates");
    if (selector != null && !(selector instanceof X509CertSelector)) {
        throw new IllegalArgumentException();
    }

    if (caDelegate.getCollection() == null) {
        return null;
    }
    // Given that we always only use subject, how can we improve performance
    // here. Custom
    Vector<X509Certificate> certSet = new Vector<X509Certificate>();
    if (selector == null) {
        for (TrustAnchor trustAnchor : caDelegate.getCollection()) {
            certSet.add(trustAnchor.getTrustedCert());
        }

    } else {
        for (TrustAnchor trustAnchor : caDelegate.getCollection()) {
            X509Certificate cert = trustAnchor.getTrustedCert();
            if (selector.match(cert)) {
                certSet.add(cert);
            }
        }
    }

    return certSet;
}

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

/**
 * Metodo encargado de la verificacin de los certificados
 * //from  w  w  w. j a v  a  2s  .  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.viafirma.nucleo.validacion.OcspValidatorHandler.java

/**
 * Retorna el certificado de condianza.// w  w w . j  ava2 s  .c o m
 * 
 * @param certificadoX509
 * @return
 * @throws ExcepcionErrorInterno
 *             No se encuentra el certificado de confianza.
 */
private X509Certificate getIssuerX509(X509Certificate certificadoX509) throws ExcepcionErrorInterno {
    for (TrustAnchor trust : certificadosConfianza) {
        if (trust.getTrustedCert().getSubjectDN().getName().equals(certificadoX509.getIssuerDN().getName())) {
            return trust.getTrustedCert();
        }
    }
    log.warn(" No hemos encontrado el certificado de confianza.");
    throw new ExcepcionErrorInterno(CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA);
}

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

/**
 * Recupera el certificado con el DN indicado
 * //  www.jav a2  s.co  m
 * @param alias
 *            Alias del certificado deseado.
 * @return Certificado con el alias indicado
 * @throws ExcepcionErrorInterno
 */
private PublicKey getPublicKeyBySubjectName(X509Certificate certificadoResponseOCSP) {
    // ej: C=ES,O=DIRECCION GENERAL DE LA POLICIA,OU=DNIE,OU=FNMT,CN=AV DNIE
    // FNMT
    // cn:AV DNIE FNMT
    String cn = getCN(certificadoResponseOCSP);
    for (TrustAnchor certificadoConcianza : certificadosConfianza) {
        String cnConcianza = getCN(certificadoConcianza.getTrustedCert());
        // si los CN coninciden, encontrado!
        if (cn.equals(cnConcianza)) {
            // Hemos encontrado el certificado de confianza
            return certificadoConcianza.getTrustedCert().getPublicKey();
        }
    }
    return null;
}

From source file:org.viafirma.nucleo.X509.X509Handler.java

/**
 * Retorna el certificado emisor del certificado actual
 * /* ww w.j av a  2s  . co m*/
 * @param certificado
 * @param certificadosConfianza
 * @return
 * @throws ExcepcionErrorInterno  No se ha encontrado un certificado asociado vlido.
 */
public X509Certificate getEmisor(X509Certificate certificado, Set<TrustAnchor> certificadosConfianza)
        throws ExcepcionErrorInterno {
    // Si no es un certificado autoemitido
    if (certificado.getIssuerX500Principal().getName()
            .equals(certificado.getSubjectX500Principal().getName())) {
        // El certificado esta autofirmado, no hay emisor.
        return null;
    } else {
        // Busco el emisor indicado.
        for (TrustAnchor trustAnchor : certificadosConfianza) {
            if (trustAnchor.getTrustedCert().getSubjectX500Principal().getName()
                    .equals(certificado.getIssuerX500Principal().getName())) {
                // Encontrado el certificado de confianza.
                return trustAnchor.getTrustedCert();
            }
        }
    }
    log.error("No hay ningun certificado asociado a :" + certificado.getIssuerX500Principal().getName()
            + " es necesaria su instalacin para poder gestionar este tpo de certificados.");
    throw new ExcepcionErrorInterno(CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA);
}