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:MainClass.java

public static void main(String[] args) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream(args[0]);
    X509CRL crl = (X509CRL) cf.generateCRL(in);
    System.out.println("type = " + crl.getType());
    System.out.println("version = " + crl.getVersion());
    System.out.println("issuer = " + crl.getIssuerDN().getName());
    System.out.println("signing algorithm = " + crl.getSigAlgName());
    System.out.println("this update = " + crl.getThisUpdate());
    System.out.println("next update = " + crl.getNextUpdate());
    in.close();/* w w w. j  av  a  2 s .c  o  m*/
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream(args[0]);
    X509CRL crl = (X509CRL) cf.generateCRL(in);
    Set s = crl.getRevokedCertificates();
    if (s != null && s.isEmpty() == false) {
        Iterator t = s.iterator();
        while (t.hasNext()) {
            X509CRLEntry entry = (X509CRLEntry) t.next();
            System.out.println("serial number = " + entry.getSerialNumber().toString(16));
            System.out.println("revocation date = " + entry.getRevocationDate());
            System.out.println("extensions = " + entry.hasExtensions());
        }/*from   w ww . java2s  .  com*/
    }
    in.close();
}

From source file:net.ripe.rpki.commons.crypto.crl.X509Crl.java

private static X509CRL makeX509CRLFromEncoded(byte[] encoded) {
    final X509CRL crl;
    if (null != encoded) {
        try {/*from  w w  w  .j  av  a2  s.  c  om*/
            final Closer closer = Closer.create();
            try {
                final ByteArrayInputStream in = new ByteArrayInputStream(encoded);
                final CertificateFactory factory = CertificateFactory.getInstance("X.509");
                crl = (X509CRL) factory.generateCRL(in);
            } catch (final CertificateException e) {
                throw closer.rethrow(new IllegalArgumentException(e));
            } catch (final CRLException e) {
                throw closer.rethrow(new IllegalArgumentException(e));
            } catch (final Throwable t) {
                throw closer.rethrow(t);
            } finally {
                closer.close();
            }
        } catch (final IOException e) {
            throw new RuntimeException("Error managing CRL I/O stream", e);
        }
    } else {
        crl = null;
    }
    return crl;

}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

/**
 * Load a CRL from the specified stream.
 *
 * @param is//  w ww .  j ava 2 s.  c  o  m
 *            Stream to load CRL from
 * @return The CRL
 * @throws CryptoException
 *             Problem encountered while loading the CRL
 */
public static X509CRL loadCRL(InputStream is) throws CryptoException {
    try {
        CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE);
        X509CRL crl = (X509CRL) cf.generateCRL(is);
        return crl;
    } catch (CertificateException ex) {
        throw new CryptoException(res.getString("NoLoadCrl.exception.message"), ex);
    } catch (CRLException ex) {
        throw new CryptoException(res.getString("NoLoadCrl.exception.message"), ex);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:demo.sts.provider.cert.CrlVerifier.java

public X509CRL getCrlFromStream(InputStream is) throws CertificateException, CRLException {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    return (X509CRL) certificateFactory.generateCRL(is);
}

From source file:be.fedict.trust.crl.OnlineCrlRepository.java

private X509CRL getCrl(URI crlUri) throws IOException, CertificateException, CRLException,
        NoSuchProviderException, NoSuchParserException, StreamParsingException {
    HttpClient httpClient = new HttpClient();
    if (null != this.networkConfig) {
        httpClient.getHostConfiguration().setProxy(this.networkConfig.getProxyHost(),
                this.networkConfig.getProxyPort());
    }/*from w  w  w. ja va 2 s  .co m*/
    if (null != this.credentials) {
        HttpState httpState = httpClient.getState();
        this.credentials.init(httpState);
    }
    String downloadUrl = crlUri.toURL().toString();
    LOG.debug("downloading CRL from: " + downloadUrl);
    GetMethod getMethod = new GetMethod(downloadUrl);
    getMethod.addRequestHeader("User-Agent", "jTrust CRL Client");
    int statusCode = httpClient.executeMethod(getMethod);
    if (HttpURLConnection.HTTP_OK != statusCode) {
        LOG.debug("HTTP status code: " + statusCode);
        return null;
    }

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
    X509CRL crl = (X509CRL) certificateFactory.generateCRL(getMethod.getResponseBodyAsStream());
    LOG.debug("CRL size: " + crl.getEncoded().length + " bytes");
    return crl;
}

From source file:eu.europa.ec.markt.dss.validation.xades.XAdESCRLSource.java

@Override
public List<X509CRL> getCRLsFromSignature() {
    List<X509CRL> list = new ArrayList<X509CRL>();

    try {/*from  w  ww .  j  a v a  2s.  c  o  m*/
        NodeList nodeList = (NodeList) XMLUtils.getNodeList(signatureElement, CRL_XPATH);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element certEl = (Element) nodeList.item(i);
            CertificateFactory factory = CertificateFactory.getInstance("X509");
            byte[] derEncoded = Base64.decodeBase64(certEl.getTextContent());
            X509CRL cert = (X509CRL) factory.generateCRL(new ByteArrayInputStream(derEncoded));
            list.add(cert);
        }
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    } catch (CRLException e) {
        throw new RuntimeException(e);
    }

    return list;
}

From source file:eu.europa.ec.markt.dss.validation.crl.JdbcCacheCRLSource.java

@Override
public X509CRL findCrl(X509Certificate certificate, X509Certificate issuerCertificate) throws IOException {

    OnlineCRLSource source = new OnlineCRLSource();
    String crlUrl = source.getCrlUri(certificate);

    if (crlUrl != null) {
        try {//w  w  w  .  ja va2  s.c  o  m
            MessageDigest digest = MessageDigest.getInstance(DigestAlgorithm.SHA1.getName());
            String key = Hex.encodeHexString(digest.digest(crlUrl.getBytes()));

            List<CachedCRL> crls = getJdbcTemplate().query("SELECT * FROM CACHED_CRL WHERE ID = ?",
                    new Object[] { key }, new RowMapper<CachedCRL>() {
                        @Override
                        public CachedCRL mapRow(ResultSet rs, int rowNum) throws SQLException {
                            CachedCRL cached = new CachedCRL();
                            cached.setKey(rs.getString("ID"));
                            cached.setCrl(rs.getBytes("DATA"));
                            return cached;
                        }
                    });

            if (crls.size() == 0) {
                LOG.info("CRL not in cache");
                X509CRL originalCRL = cachedSource.findCrl(certificate, issuerCertificate);
                if (originalCRL != null) {
                    getJdbcTemplate().update("INSERT INTO CACHED_CRL (ID, DATA) VALUES (?,?) ", key,
                            originalCRL.getEncoded());
                    return originalCRL;
                } else {
                    return null;
                }
            }

            CachedCRL crl = crls.get(0);

            CertificateFactory factory = CertificateFactory.getInstance("X509");
            X509CRL x509crl = (X509CRL) factory.generateCRL(new ByteArrayInputStream(crl.getCrl()));
            if (x509crl.getNextUpdate().after(new Date())) {
                LOG.fine("CRL in cache");
                return x509crl;
            } else {
                LOG.info("CRL expired");
                X509CRL originalCRL = cachedSource.findCrl(certificate, issuerCertificate);
                getJdbcTemplate().update("UPDATE CACHED_CRL SET DATA = ?  WHERE ID = ? ",
                        originalCRL.getEncoded(), key);
                return originalCRL;
            }

        } catch (NoSuchAlgorithmException e) {
            LOG.info("Cannot instantiate digest for algorithm SHA1 !?");
        } catch (CRLException e) {
            LOG.info("Cannot serialize CRL");
        } catch (CertificateException e) {
            LOG.info("Cannot instanciate X509 Factory");
        }
    }

    return null;
}

From source file:dk.itst.oiosaml.sp.metadata.CRLChecker.java

public void checkCertificates(IdpMetadata metadata, Configuration conf) {
    for (String entityId : metadata.getEntityIDs()) {
        Metadata md = metadata.getMetadata(entityId);

        for (X509Certificate certificate : md.getAllCertificates()) {
            String url = getCRLUrl(conf, entityId, certificate);
            if (url == null) {
                log.debug("No CRL configured in oiosaml-sp.properties, and no CRL found in certificate");
                continue;
            }/*from   w  w w.  j  a  v a  2  s  .co m*/

            try {
                URL u = new URL(url);
                InputStream is = u.openStream();

                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509CRL crl = (X509CRL) cf.generateCRL(is);
                is.close();

                if (log.isDebugEnabled())
                    log.debug("CRL for " + url + ": " + crl);

                if (!checkCRLSignature(crl, certificate, conf)) {
                    md.setCertificateValid(certificate, false);
                } else {
                    X509CRLEntry revokedCertificate = crl.getRevokedCertificate(certificate.getSerialNumber());
                    boolean revoked = revokedCertificate != null;
                    log.debug(
                            "Certificate status for " + entityId + ": " + revoked + " - cert: " + certificate);
                    Audit.log(Operation.CRLCHECK, false, entityId, "Revoked: " + revoked);

                    md.setCertificateValid(certificate, !revoked);
                }
            } catch (MalformedURLException e) {
                log.error("Unable to parse url " + url, e);
                throw new WrappedException(Layer.BUSINESS, e);
            } catch (IOException e) {
                log.error("Unable to read CRL from " + url, e);
                throw new WrappedException(Layer.BUSINESS, e);
            } catch (GeneralSecurityException e) {
                throw new WrappedException(Layer.BUSINESS, e);
            }
        }
    }
}

From source file:net.sf.jsignpdf.crl.CRLInfo.java

/**
 * Initialize CRLs (load URLs from certificates and download the CRLs).
 *///from  w  w w  .  jav a 2  s .  co  m
private void initCrls() {
    if (!options.isCrlEnabledX() || crls != null) {
        return;
    }
    LOGGER.info(RES.get("console.readingCRLs"));
    final Set<String> urls = new HashSet<String>();
    for (Certificate cert : certChain) {
        if (cert instanceof X509Certificate) {
            urls.addAll(getCrlUrls((X509Certificate) cert));
        }
    }
    final Set<CRL> crlSet = new HashSet<CRL>();
    for (final String urlStr : urls) {
        try {
            LOGGER.info(RES.get("console.crlinfo.loadCrl", urlStr));
            final URL tmpUrl = new URL(urlStr);
            final CountingInputStream inStream = new CountingInputStream(
                    tmpUrl.openConnection(options.createProxy()).getInputStream());
            final CertificateFactory cf = CertificateFactory.getInstance(Constants.CERT_TYPE_X509);
            final CRL crl = cf.generateCRL(inStream);
            final long tmpBytesRead = inStream.getByteCount();
            LOGGER.info(RES.get("console.crlinfo.crlSize", String.valueOf(tmpBytesRead)));
            if (!crlSet.contains(crl)) {
                byteCount += tmpBytesRead;
                crlSet.add(crl);
            } else {
                LOGGER.info(RES.get("console.crlinfo.alreadyLoaded"));
            }
            inStream.close();
        } catch (MalformedURLException e) {
            LOGGER.warn("", e);
        } catch (IOException e) {
            LOGGER.warn("", e);
        } catch (CertificateException e) {
            LOGGER.warn("", e);
        } catch (CRLException e) {
            LOGGER.warn("", e);
        }
    }
    crls = crlSet.toArray(new CRL[crlSet.size()]);
}