Example usage for java.security.cert CertificateFactory generateCRL

List of usage examples for java.security.cert CertificateFactory generateCRL

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory generateCRL.

Prototype

public final CRL generateCRL(InputStream inStream) throws CRLException 

Source Link

Document

Generates a certificate revocation list (CRL) object and initializes it with the data read from the input stream inStream .

Usage

From source file:org.casbah.provider.openssl.OpenSslCAProvider.java

private X509CRL loadCrlFromFile()
        throws FileNotFoundException, IOException, CRLException, CertificateException {
    FileInputStream fis = new FileInputStream(new File(caRootDir, CRL_FILE));
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509CRL result = (X509CRL) cf.generateCRL(fis);
    fis.close();/*from   www .  j  av  a 2s .  com*/
    return result;
}

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

/**
 * Gets issuer DN for CRL in the format we are sure about (BouncyCastle),supporting UTF8.
 * //from  w  ww. java2s . co m
 * @param crl X509RL
 * 
 * @return String containing the DN.
 */
public static String getIssuerDN(X509CRL crl) {
    String dn = null;
    try {
        CertificateFactory cf = CertTools.getCertificateFactory();
        X509CRL x509crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(crl.getEncoded()));
        // log.debug("Created certificate of class: " + x509crl.getClass().getName());
        dn = x509crl.getIssuerDN().toString();
    } catch (CRLException ce) {
        log.error("CRLException: ", ce);
        return null;
    }
    return stringToBCDNString(dn);
}

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

/**
 * Creates X509CRL from byte[]./* w  ww .  j  a va  2 s.  com*/
 * 
 * @param crl byte array containing CRL in DER-format
 * 
 * @return X509CRL
 * 
 * @throws CertificateException if the byte array does not contain a correct CRL.
 * @throws CRLException if the byte array does not contain a correct CRL.
 */
public static X509CRL getCRLfromByteArray(byte[] crl) throws CRLException {
    log.trace(">getCRLfromByteArray");
    CertificateFactory cf = CertTools.getCertificateFactory();
    X509CRL x509crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(crl));
    log.trace("<getCRLfromByteArray");

    return x509crl;
}

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

private CRL getCRL(final URL url) {
    CRL crl = null;/* w w  w.j  a  va  2 s. com*/
    try {
        final URLConnection con = url.openConnection();
        final InputStream is = con.getInputStream();
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        crl = cf.generateCRL(is);
        is.close();
        log.info("Downloaded CRL from " + url);
    } catch (IOException | CertificateException | CRLException e) {
        if (log.isDebugEnabled()) {
            log.debug("Fetching CRL from " + url.toString() + " failed. " + e.getLocalizedMessage());
        }
    }
    return crl;
}

From source file:org.codice.ddf.security.crl.generator.CrlGenerator.java

/**
 * Validates the given CRL by attempting to create a {@link CRL}
 *
 * @param byteSource - CRL byte source//w  ww.  ja va2 s. c om
 * @return - True if the CRL is valid. False if its invalid
 */
private boolean crlIsValid(ByteSource byteSource) {
    try (InputStream inputStream = byteSource.openStream()) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        certificateFactory.generateCRL(inputStream);
    } catch (CertificateException | CRLException | IOException e) {
        LOGGER.warn("An error occurred while validating the CRL. {}", e.getMessage());
        return false;
    }
    return true;
}

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

/**
 * Gets issuer DN for CRL in the format we are sure about (BouncyCastle),supporting UTF8.
 *
 * @param crl X509RL//  w  w  w  .  j  a v a  2 s.c  o  m
 *
 * @return String containing the DN.
 */
public static String getIssuerDN(X509CRL crl) {
    /*if (log.isTraceEnabled()) {
       log.trace(">getIssuerDN(crl)");
    }*/
    String dn = null;
    try {
        CertificateFactory cf = CertTools.getCertificateFactory();
        X509CRL x509crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(crl.getEncoded()));
        //log.debug("Created certificate of class: " + x509crl.getClass().getName());
        dn = x509crl.getIssuerDN().toString();
    } catch (CRLException ce) {
        log.error("CRLException: ", ce);
        return null;
    }
    /*if (log.isTraceEnabled()) {
       log.trace("<getIssuerDN(crl):"+dn);
    }*/
    return stringToBCDNString(dn);
}

From source file:org.gluu.oxtrust.ldap.service.SSLService.java

/**
 * Load a CRL from the specified stream.
 *
 * @param is Stream to load CRL from//  w w w  . j  a  va 2  s .  com
 * @return The CRL
 * @throws Exception Problem encountered while loading the CRL
 */
public static X509CRL loadCRL(InputStream is) throws Exception {
    try {
        CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE);
        X509CRL crl = (X509CRL) cf.generateCRL(is);
        return crl;
    } finally {
        IOUtils.closeQuietly(is);
    }
}

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

public void validate(X509Certificate certificate) throws X509CertificateValidationException {

    try {/*from w  ww  .  j  a va2  s.  com*/
        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.viafirma.nucleo.validacion.CRLUtil.java

/**
 * Retorna el listado de CRLs para los certificados que tienen informacin
 * correcta sobre sus puntos de distrubicin. 1.- Recupera las urls de los
 * puntos de distribucin de crls. 2.- Se descarga todas las crls.
 * // w  w  w. j a  v  a  2s  . com
 * @param certificadoX509
 * @return
 * @throws NoSuchProviderException
 * @throws CertificateException
 */
private List<X509CRL> getCrlsPuntoDistribucion(X509Certificate certificadoX509)
        throws CertificateException, NoSuchProviderException {
    CertificateFactory factoriaCertificados = CertificateFactory.getInstance("X.509",
            BouncyCastleProvider.PROVIDER_NAME);
    List<String> urls = null;
    // recuperos los puntos de distribucin definidos del certificado.
    urls = getCrlPuntosDeDistribucion(certificadoX509);
    List<X509CRL> crls = new LinkedList<X509CRL>();
    if (urls != null) {
        // itero sobre las urls para ir obteniendo los listados
        for (String hostURL : urls) {
            log.debug("url ->" + hostURL);
            try {
                if (hostURL == null) {
                    log.debug("La url de la crl no es correcta.");

                } else if (!hostURL.startsWith("http:")) {
                    log.debug("La url de la crl no es correcta. " + hostURL);
                } else {
                    InputStream ioCrl = getIoCrlFromUrl(hostURL);

                    // leo el io para generar un fichero de crl
                    X509CRL crl = (X509CRL) factoriaCertificados.generateCRL(ioCrl);
                    if (crl != null) {
                        crls.add(crl);
                        // log.debug("CRLer -->" + crl.get());
                        log.debug("Effective   From -->" + crl.getThisUpdate());
                        log.debug("Nextate    -->" + crl.getNextUpdate());
                    } else {
                        log.debug("No se puede recuperar o no es un cert valido " + hostURL);
                    }
                    try {
                        ioCrl.close();
                    } catch (Exception e) {
                        // No se ha podido cerrar la conexin con la crl, sin importancia.
                    } // no importa si no podemos cerrar la conexin(
                      // significa que ya esta cerrada)
                }
            } catch (CRLException e) {
                log.warn(
                        "no se ha podido conectar a host para descargar las crls, en este momento no estan disponibles."
                                + e.getMessage(),
                        e);
                // e.printStackTrace();
            } catch (Exception e) {
                log.warn(
                        "no se ha podido conectar a host para descargar las crls, en este momento no estan disponibles."
                                + e.getMessage(),
                        e);
                e.printStackTrace();
            }
        }
    }
    return crls;
}

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

/**
 * Recupera el listado de Crls obtenidas desde el LDAP. 
 * TODO: Separar cada implementacin en un IMPL concreto que tenga que cumplir con una interfaz
 * para resolver las crls y para parsear el certificado 
 * NOTA: para utilizar de forma oficial la validazin de CRLs de la FNMT es necesario firmar un convenio.
 * //from w  w  w.  j  a v a 2s  . co m
 * @param certificadoX509
 * @return
 */
private List<X509CRL> getCrlLDAPFNMT(X509Certificate certificadoX509) {
    List<X509CRL> crls = new LinkedList<X509CRL>();
    // ********************************************************************************
    // si es un certiticado de la FNMT hay que acceder al ldap para
    // recuperar las crls.
    try {
        CertificateFactory factoriaCertificados = CertificateFactory.getInstance("X.509",
                BouncyCastleProvider.PROVIDER_NAME);
        // es un certificado de la FNMT. el procesamiento es diferente
        // al resto, es atacando a un LDAP
        // recuperamos del LDAP el certificado
        // NOTA: Esta url es solo para pruebas, para utilizar de forma
        // oficial la validazin de CRLs de la FNMT es necesario firmar un
        // convenio
        // ldap-2.cert.fnmt.es:389
        InputStream ioCrl = getIoCrlFromFNMTLDAP(certificadoX509);
        if (ioCrl != null) {
            // la crl del fichero actual esta publicada, recuperamos la crl
            // leo el io para generar un fichero de crl
            System.out.println("***ioCrl:" + ioCrl);
            X509CRL crl = (X509CRL) factoriaCertificados.generateCRL(ioCrl);
            System.out.println("***Despues deioCrl:" + crl);
            try {
                if (crl != null) {
                    crls.add(crl);
                    System.out.println("***3:" + crl.getIssuerDN());
                    log.debug("CRLer     -->" + crl.getIssuerDN());
                    log.debug("Effective   From -->" + crl.getThisUpdate());
                    log.debug("Nextate    -->" + crl.getNextUpdate());
                    crls.add(crl);
                } else {
                    log.debug("No se puede recuperar o no es un cert valido .");
                }

                ioCrl.close();
            } catch (Throwable e) {
                log.warn("Problemas al recuperar la crl ." + e.getMessage());
                e.printStackTrace();
            } // no importa si no podemos cerrar la conexin( significa
              // que ya esta cerrada)
        } else {
            log.error("No se ha recuperado la crl.");
        }
    } catch (CRLException e) {
        log.warn("No se puede recuperar la crl." + e.getMessage());
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return crls;
}