Example usage for java.security.cert X509CRL getThisUpdate

List of usage examples for java.security.cert X509CRL getThisUpdate

Introduction

In this page you can find the example usage for java.security.cert X509CRL getThisUpdate.

Prototype

public abstract Date getThisUpdate();

Source Link

Document

Gets the thisUpdate date from the CRL.

Usage

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

private boolean isCorrectCRL(final CRL crl, final String issuerDN) {
    if (!(crl instanceof X509CRL)) {
        return false;
    }// w  w  w .j  av a2s  .co  m

    X509CRL x509crl = (X509CRL) crl;
    if (!StringUtils.equals(issuerDN, CertTools.getIssuerDN(x509crl))) {
        return false;
    }

    final Date now = new Date(System.currentTimeMillis());
    final Date nextUpdate = x509crl.getNextUpdate();
    if (nextUpdate != null) {
        if (nextUpdate.after(now)) {
            return true;
        }

        if (log.isDebugEnabled()) {
            log.debug("CRL issued by " + issuerDN + " is out of date");
        }
        return false;
    }

    final Date thisUpdate = x509crl.getThisUpdate();
    if (thisUpdate != null) {
        final GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(now);
        gc.add(Calendar.HOUR, 1);
        final Date expire = gc.getTime();

        if (expire.before(now)) {
            if (log.isDebugEnabled()) {
                log.debug("Could not find when CRL issued by " + issuerDN
                        + " should be updated and this CRL is over one hour old. Not using it");
            }
            return false;
        }

        log.warn("Could not find when CRL issued by " + issuerDN
                + " should be updated, but this CRL was issued less than an hour ago, so we are using it");
        return true;
    }

    if (log.isDebugEnabled()) {
        log.debug("Could not check issuance time for CRL issued by " + issuerDN);
    }
    return false;
}

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 ww.j a  v a 2  s  . c  o  m*/
 * @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.
 * //www .ja v a  2 s.  c  o  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;
}

From source file:org.wso2.carbon.identity.certificateauthority.crl.CrlFactory.java

/**
 * @param tenantId id of the tenant creating delta crl
 * @return a delta crl which/*  w w  w .  j  a v  a 2  s. com*/
 * @throws Exception
 */
public X509CRL creteDeltaCrl(int tenantId) throws Exception {
    RevocationDAO revocationDAO = new RevocationDAO();
    CrlDataHolderDao crlDataHolderDao = new CrlDataHolderDao();
    X509CRL latestCrl;
    try {
        CRLDataHolder dataholder = crlDataHolderDao.getLatestCRL(tenantId, false);
        latestCrl = crlDataHolderDao.getLatestCRL(tenantId, false).getCRL();
        RevokedCertificate[] revokedCertificates = revocationDAO.getRevokedCertificatesAfter(tenantId,
                latestCrl.getThisUpdate());
        CRLDataHolder crlDataHolder = crlDataHolderDao.getLatestCRL(tenantId, false);
        PrivateKey privateKey = CAUtils.getConfiguredPrivateKey();
        X509Certificate certb = CAUtils.getConfiguredCaCert();
        int fullnumber = crlDataHolderDao.findHighestCrlNumber(tenantId, false);
        int deltanumber = crlDataHolderDao.findHighestCrlNumber(tenantId, true);
        // nextCrlNumber: The highest number of last CRL (full or delta) and increased by 1 (both full CRLs and deltaCRLs share the same series of CRL Number)
        int nextCrlNumber = ((fullnumber > deltanumber) ? fullnumber : deltanumber) + 1;
        return createCRL(certb, privateKey, revokedCertificates, nextCrlNumber, fullnumber, false);
    } catch (CaException e) {
        log.info("No base crl found to create a delta crl");
    }
    return null;
}

From source file:org.wso2.carbon.identity.certificateauthority.crl.CrlFactory.java

/**
 * creates and store a crl in db for the given tenant
 *
 * @param tenantId tenant id// w ww .  j  a va2  s . c  o  m
 * @throws Exception
 */
public void createAndStoreCrl(int tenantId) throws Exception {
    X509CRL crl = createFullCrl(tenantId);
    CrlDataHolderDao crlDataHolderDao = new CrlDataHolderDao();
    RevocationDAO revocationDAO = new RevocationDAO();
    revocationDAO.removeActivedCertificates();
    int fullnumber = crlDataHolderDao.findHighestCrlNumber(tenantId, false);
    int deltanumber = crlDataHolderDao.findHighestCrlNumber(tenantId, true);
    // nextCrlNumber: The highest number of last CRL (full or delta) and increased by 1 (both full CRLs and deltaCRLs share the same series of CRL Number)
    int nextCrlNumber = ((fullnumber > deltanumber) ? fullnumber : deltanumber) + 1;

    crlDataHolderDao.addCRL(crl, tenantId, crl.getThisUpdate(), crl.getNextUpdate(), nextCrlNumber, -1);

}

From source file:org.wso2.carbon.identity.certificateauthority.crl.CrlFactory.java

/**
 * create and store a delta crl in database
 *
 * @param tenantId id of the tenant/*ww  w.  j a  v a  2s  .  c o m*/
 * @throws Exception
 */
public void createAndStoreDeltaCrl(int tenantId) throws Exception {
    X509CRL crl = creteDeltaCrl(tenantId);
    if (crl != null) {
        CrlDataHolderDao crlDataHolderDao = new CrlDataHolderDao();
        int fullnumber = crlDataHolderDao.findHighestCrlNumber(tenantId, false);
        int deltanumber = crlDataHolderDao.findHighestCrlNumber(tenantId, true);
        // nextCrlNumber: The highest number of last CRL (full or delta) and increased by 1 (both full CRLs and deltaCRLs share the same series of CRL Number)
        int nextCrlNumber = ((fullnumber > deltanumber) ? fullnumber : deltanumber) + 1;
        crlDataHolderDao.addCRL(crl, tenantId, crl.getThisUpdate(), crl.getNextUpdate(), nextCrlNumber, 1);
    } else {
        log.info("Error while creating delta crl for tenant " + tenantId);
    }
}

From source file:org.xdi.oxauth.cert.validation.CRLCertificateVerifier.java

@Override
public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers,
        Date validationDate) {/*from   www . j a v  a 2  s .c o  m*/
    X509Certificate issuer = issuers.get(0);
    ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate, ValidatorSourceType.CRL,
            CertificateValidity.UNKNOWN);

    try {
        Principal subjectX500Principal = certificate.getSubjectX500Principal();

        String crlURL = getCrlUri(certificate);
        if (crlURL == null) {
            log.error("CRL's URL for '" + subjectX500Principal + "' is empty");
            return status;
        }

        log.debug("CRL's URL for '" + subjectX500Principal + "' is '" + crlURL + "'");

        X509CRL x509crl = getCrl(crlURL);
        if (!validateCRL(x509crl, certificate, issuer, validationDate)) {
            log.error("The CRL is not valid!");
            status.setValidity(CertificateValidity.INVALID);
            return status;
        }

        X509CRLEntry crlEntry = x509crl.getRevokedCertificate(certificate.getSerialNumber());
        if (crlEntry == null) {
            log.debug("CRL status is valid for '" + subjectX500Principal + "'");
            status.setValidity(CertificateValidity.VALID);
        } else if (crlEntry.getRevocationDate().after(validationDate)) {
            log.warn("CRL revocation time after the validation date, the certificate '" + subjectX500Principal
                    + "' was valid at " + validationDate);
            status.setRevocationObjectIssuingTime(x509crl.getThisUpdate());
            status.setValidity(CertificateValidity.VALID);
        } else {
            log.info("CRL for certificate '" + subjectX500Principal + "' is revoked since "
                    + crlEntry.getRevocationDate());
            status.setRevocationObjectIssuingTime(x509crl.getThisUpdate());
            status.setRevocationDate(crlEntry.getRevocationDate());
            status.setValidity(CertificateValidity.REVOKED);
        }
    } catch (Exception ex) {
        log.error("CRL exception: ", ex);
    }

    return status;
}

From source file:org.xdi.oxauth.cert.validation.CRLCertificateVerifier.java

private boolean validateCRL(X509CRL x509crl, X509Certificate certificate, X509Certificate issuerCertificate,
        Date validationDate) {//from   w w w . j  av  a  2 s  .c  o m
    Principal subjectX500Principal = certificate.getSubjectX500Principal();

    if (x509crl == null) {
        log.error("No CRL found for certificate '" + subjectX500Principal + "'");
        return false;
    }

    if (log.isTraceEnabled()) {
        try {
            log.trace("CRL number: " + getCrlNumber(x509crl));
        } catch (IOException ex) {
            log.error("Failed to get CRL number", ex);
        }
    }

    if (!x509crl.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) {
        log.error("The CRL must be signed by the issuer '" + subjectX500Principal
                + "' but instead is signed by '" + x509crl.getIssuerX500Principal() + "'");
        return false;
    }

    try {
        x509crl.verify(issuerCertificate.getPublicKey());
    } catch (Exception ex) {
        log.error("The signature verification for CRL cannot be performed", ex);
        return false;
    }

    log.debug("CRL validationDate: " + validationDate);
    log.debug("CRL nextUpdate: " + x509crl.getThisUpdate());
    log.debug("CRL thisUpdate: " + x509crl.getNextUpdate());

    if (x509crl.getNextUpdate() != null && validationDate.after(x509crl.getNextUpdate())) {
        log.error("CRL is too old");
        return false;
    }

    if (issuerCertificate.getKeyUsage() == null) {
        log.error("There is no KeyUsage extension for certificate '" + subjectX500Principal + "'");
        return false;
    }

    if (!issuerCertificate.getKeyUsage()[6]) {
        log.error("cRLSign bit is not set for CRL certificate'" + subjectX500Principal + "'");
        return false;
    }

    return true;

}