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:be.fedict.trust.service.bean.DownloaderMDB.java

private void processColdStartMessage(ColdStartMessage coldStartMessage) {
    if (null == coldStartMessage) {
        return;//from   ww w . j av  a  2s  .  c om
    }

    String crlUrl = coldStartMessage.getCrlUrl();
    String certUrl = coldStartMessage.getCertUrl();
    LOG.debug("cold start CRL URL: " + crlUrl);
    LOG.debug("cold start CA URL: " + certUrl);

    File crlFile = download(crlUrl);
    File certFile = download(certUrl);

    // parsing
    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        LOG.debug("certificate factory error: " + e.getMessage(), e);
        crlFile.delete();
        certFile.delete();
        return;
    }

    X509Certificate certificate = null;
    try {
        certificate = (X509Certificate) certificateFactory.generateCertificate(new FileInputStream(certFile));
    } catch (Exception e) {
        LOG.debug("error DER-parsing certificate");
        try {
            PEMReader pemReader = new PEMReader(new FileReader(certFile));
            certificate = (X509Certificate) pemReader.readObject();
            pemReader.close();
        } catch (Exception e2) {
            retry("error PEM-parsing certificate", e, certFile, crlFile);
        }
    }
    certFile.delete();

    X509CRL crl = null;
    try {
        crl = (X509CRL) certificateFactory.generateCRL(new FileInputStream(crlFile));
    } catch (Exception e) {
        retry("error parsing CRL", e, crlFile);
    }

    // first check whether the two correspond
    try {
        crl.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.error("no correspondence between CRL and CA");
        LOG.error("CRL issuer: " + crl.getIssuerX500Principal());
        LOG.debug("CA subject: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }
    LOG.debug("CRL matches CA: " + certificate.getSubjectX500Principal());

    // skip expired CAs
    Date now = new Date();
    Date notAfter = certificate.getNotAfter();
    if (now.after(notAfter)) {
        LOG.warn("CA already expired: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }

    // create database entitities
    CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(certificate);
    if (null != certificateAuthority) {
        LOG.debug("CA already in cache: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }

    /*
     * Lookup Root CA's trust point via parent certificates' CA entity.
     */
    LOG.debug(
            "Lookup Root CA's trust point via parent certificates' CA entity - Don't have Issuer's Serial Number??");
    String parentIssuerName = certificate.getIssuerX500Principal().toString();
    CertificateAuthorityEntity parentCertificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(parentIssuerName);
    if (null == parentCertificateAuthority) {
        LOG.error("CA not found for " + parentIssuerName + " ?!");
        crlFile.delete();
        return;
    }
    LOG.debug("parent CA: " + parentCertificateAuthority.getName());
    TrustPointEntity parentTrustPoint = parentCertificateAuthority.getTrustPoint();
    if (null != parentTrustPoint) {
        LOG.debug("trust point parent: " + parentTrustPoint.getName());
        LOG.debug("previous trust point fire data: " + parentTrustPoint.getFireDate());
    } else {
        LOG.debug("no parent trust point");
    }

    // create new CA
    certificateAuthority = this.certificateAuthorityDAO.addCertificateAuthority(certificate, crlUrl);

    // prepare harvesting
    certificateAuthority.setTrustPoint(parentTrustPoint);
    certificateAuthority.setStatus(Status.PROCESSING);
    if (null != certificateAuthority.getTrustPoint()
            && null == certificateAuthority.getTrustPoint().getFireDate()) {
        try {
            this.schedulingService.startTimer(certificateAuthority.getTrustPoint());
        } catch (InvalidCronExpressionException e) {
            LOG.error("invalid cron expression");
            crlFile.delete();
            return;
        }
    }

    // notify harvester
    String crlFilePath = crlFile.getAbsolutePath();
    try {
        this.notificationService.notifyHarvester(certificate.getSubjectX500Principal().toString(), crlFilePath,
                false);
    } catch (JMSException e) {
        crlFile.delete();
        throw new RuntimeException(e);
    }
}

From source file:com.verisign.epp.serverstub.LaunchDomainHandler.java

/**
 * Loads the trust store file and the Certificate Revocation List (CRL) file
 * into the <code>PKIXParameters</code> used to verify the certificate chain
 * and verify the certificate against the CRL. Both the Java Trust Store is
 * loaded with the trusted root CA certificates (trust anchors) and the CRL
 * file is attempted to be loaded to identify the revoked certificates. If
 * the CRL file is not found, then no CRL checking will be done.
 * /*from   w ww .j a  v  a2  s . com*/
 * @param aTrustStoreName
 *            Trust store file name
 * @param aCrls
 *            List of Certificate Revocation List (CRL) file names
 * 
 * @return Initialized <code>PKIXParameters</code> instance.
 * 
 * @throws Exception
 *             Error initializing the PKIX parameters
 */
private PKIXParameters loadPKIXParameters(String aTrustStoreName, List<String> aCrls) throws Exception {
    cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): enter");

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream trustStoreFile = new FileInputStream(aTrustStoreName);
    trustStore.load(trustStoreFile, null);
    trustStoreFile.close();
    cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): truststore = " + aTrustStoreName);
    PKIXParameters pkixParameters = new PKIXParameters(trustStore);

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

    Collection crlContentsList = new ArrayList();

    for (String currCrl : aCrls) {
        File crlFile = new File(currCrl);
        if (crlFile.exists()) {
            InputStream inStream = null;

            try {
                cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): adding CRL " + currCrl);
                inStream = new FileInputStream(currCrl);
                crlContentsList.add(certFactory.generateCRL(inStream));
            } finally {
                if (inStream != null) {
                    inStream.close();
                }
            }
        } else {
            throw new EPPException("CRL file " + currCrl + " does not exist.");
        }

    }

    // At least 1 CRL was loaded
    if (crlContentsList.size() != 0) {

        List<CertStore> certStores = new ArrayList<CertStore>();
        certStores.add(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crlContentsList)));

        pkixParameters.setCertStores(certStores);
        pkixParameters.setRevocationEnabled(true);
        cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): Revocation enabled");
    } else {
        pkixParameters.setRevocationEnabled(false);
        cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): Revocation disabled");
    }

    cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): exit");
    return pkixParameters;
}

From source file:org.apache.synapse.transport.certificatevalidation.crl.CRLVerifier.java

/**
 * Downloads CRL from the crlUrl. Does not support HTTPS
 *///from w w w.j ava 2  s .  c  om
protected X509CRL downloadCRLFromWeb(String crlURL) throws IOException, CertificateVerificationException {
    InputStream crlStream = null;
    try {
        URL url = new URL(crlURL);
        crlStream = url.openStream();
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        return (X509CRL) cf.generateCRL(crlStream);
    } catch (MalformedURLException e) {
        throw new CertificateVerificationException("CRL Url is malformed", e);
    } catch (IOException e) {
        throw new CertificateVerificationException("Cant reach URI: " + crlURL + " - only support HTTP", e);
    } catch (CertificateException e) {
        throw new CertificateVerificationException(e);
    } catch (CRLException e) {
        throw new CertificateVerificationException("Cannot generate X509CRL from the stream data", e);
    } finally {
        if (crlStream != null)
            crlStream.close();
    }
}

From source file:org.apache.synapse.transport.utils.sslcert.crl.CRLVerifier.java

/**
 * Downloads CRL from the crlUrl. Does not support HTTPS
 *//*from   w  ww . j a v a 2  s  . c om*/
protected X509CRL downloadCRLFromWeb(String crlURL) throws IOException, CertificateVerificationException {
    InputStream crlStream = null;
    try {
        URL url = new URL(crlURL);
        crlStream = url.openStream();
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        return (X509CRL) cf.generateCRL(crlStream);
    } catch (MalformedURLException e) {
        throw new CertificateVerificationException("CRL Url is malformed", e);
    } catch (IOException e) {
        throw new CertificateVerificationException("Cant reach URI: " + crlURL + " - only support HTTP", e);
    } catch (CertificateException e) {
        throw new CertificateVerificationException(e);
    } catch (CRLException e) {
        throw new CertificateVerificationException("Cannot generate X509CRL from the " + "stream data", e);
    } finally {
        if (crlStream != null)
            crlStream.close();
    }
}

From source file:org.apache.ws.security.components.crypto.Merlin.java

public void loadProperties(Properties properties, ClassLoader loader) throws CredentialException, IOException {
    if (properties == null) {
        return;//from   www .jav a 2 s . co m
    }
    this.properties = properties;
    //
    // Load the provider(s)
    //
    String provider = properties.getProperty(CRYPTO_KEYSTORE_PROVIDER);
    if (provider != null) {
        provider = provider.trim();
    }
    String certProvider = properties.getProperty(CRYPTO_CERT_PROVIDER);
    if (certProvider != null) {
        setCryptoProvider(certProvider);
    }
    //
    // Load the KeyStore
    //
    String alias = properties.getProperty(KEYSTORE_ALIAS);
    if (alias != null) {
        alias = alias.trim();
        defaultAlias = alias;
    }
    String keyStoreLocation = properties.getProperty(KEYSTORE_FILE);
    if (keyStoreLocation == null) {
        keyStoreLocation = properties.getProperty(OLD_KEYSTORE_FILE);
    }
    if (keyStoreLocation != null) {
        keyStoreLocation = keyStoreLocation.trim();
        InputStream is = loadInputStream(loader, keyStoreLocation);

        try {
            String passwd = properties.getProperty(KEYSTORE_PASSWORD, "security");
            if (passwd != null) {
                passwd = passwd.trim();
            }
            String type = properties.getProperty(KEYSTORE_TYPE, KeyStore.getDefaultType());
            if (type != null) {
                type = type.trim();
            }
            keystore = load(is, passwd, provider, type);
            if (DO_DEBUG) {
                LOG.debug("The KeyStore " + keyStoreLocation + " of type " + type + " has been loaded");
            }
            String privatePasswd = properties.getProperty(KEYSTORE_PRIVATE_PASSWORD);
            if (privatePasswd != null) {
                privatePasswordSet = true;
            }
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else {
        if (DO_DEBUG) {
            LOG.debug("The KeyStore is not loaded as KEYSTORE_FILE is null");
        }
    }

    //
    // Load the TrustStore
    //
    String trustStoreLocation = properties.getProperty(TRUSTSTORE_FILE);
    if (trustStoreLocation != null) {
        trustStoreLocation = trustStoreLocation.trim();
        InputStream is = loadInputStream(loader, trustStoreLocation);

        try {
            String passwd = properties.getProperty(TRUSTSTORE_PASSWORD, "changeit");
            if (passwd != null) {
                passwd = passwd.trim();
            }
            String type = properties.getProperty(TRUSTSTORE_TYPE, KeyStore.getDefaultType());
            if (type != null) {
                type = type.trim();
            }
            truststore = load(is, passwd, provider, type);
            if (DO_DEBUG) {
                LOG.debug("The TrustStore " + trustStoreLocation + " of type " + type + " has been loaded");
            }
            loadCACerts = false;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else {
        String loadCacerts = properties.getProperty(LOAD_CA_CERTS, "false");
        if (loadCacerts != null) {
            loadCacerts = loadCacerts.trim();
        }
        if (Boolean.valueOf(loadCacerts).booleanValue()) {
            String cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
            if (cacertsPath != null) {
                cacertsPath = cacertsPath.trim();
            }
            InputStream is = new FileInputStream(cacertsPath);
            try {
                String cacertsPasswd = properties.getProperty(TRUSTSTORE_PASSWORD, "changeit");
                if (cacertsPasswd != null) {
                    cacertsPasswd = cacertsPasswd.trim();
                }
                truststore = load(is, cacertsPasswd, null, KeyStore.getDefaultType());
                if (DO_DEBUG) {
                    LOG.debug("CA certs have been loaded");
                }
                loadCACerts = true;
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        }
    }
    //
    // Load the CRL file
    //
    String crlLocation = properties.getProperty(X509_CRL_FILE);
    if (crlLocation != null) {
        crlLocation = crlLocation.trim();
        InputStream is = loadInputStream(loader, crlLocation);

        try {
            CertificateFactory cf = getCertificateFactory();
            X509CRL crl = (X509CRL) cf.generateCRL(is);

            if (provider == null || provider.length() == 0) {
                crlCertStore = CertStore.getInstance("Collection",
                        new CollectionCertStoreParameters(Collections.singletonList(crl)));
            } else {
                crlCertStore = CertStore.getInstance("Collection",
                        new CollectionCertStoreParameters(Collections.singletonList(crl)), provider);
            }
            if (DO_DEBUG) {
                LOG.debug("The CRL " + crlLocation + " has been loaded");
            }
        } catch (Exception e) {
            if (DO_DEBUG) {
                LOG.debug(e.getMessage(), e);
            }
            throw new CredentialException(CredentialException.IO_ERROR, "ioError00", e);
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
}

From source file:org.apache.ws.security.components.crypto.MerlinDevice.java

@Override
public void loadProperties(Properties properties, ClassLoader loader) throws CredentialException, IOException {
    if (properties == null) {
        return;//from ww  w .ja va  2s. c om
    }
    this.properties = properties;
    //
    // Load the provider(s)
    //
    String provider = properties.getProperty(CRYPTO_KEYSTORE_PROVIDER);
    if (provider != null) {
        provider = provider.trim();
    }
    String certProvider = properties.getProperty(CRYPTO_CERT_PROVIDER);
    if (certProvider != null) {
        setCryptoProvider(certProvider);
    }
    //
    // Load the KeyStore
    //
    String alias = properties.getProperty(KEYSTORE_ALIAS);
    if (alias != null) {
        alias = alias.trim();
        defaultAlias = alias;
    }
    String keyStoreLocation = properties.getProperty(KEYSTORE_FILE);
    if (keyStoreLocation == null) {
        keyStoreLocation = properties.getProperty(OLD_KEYSTORE_FILE);
    }
    String keyStorePassword = properties.getProperty(KEYSTORE_PASSWORD, "security");
    if (keyStorePassword != null) {
        keyStorePassword = keyStorePassword.trim();
    }
    String keyStoreType = properties.getProperty(KEYSTORE_TYPE, KeyStore.getDefaultType());
    if (keyStoreType != null) {
        keyStoreType = keyStoreType.trim();
    }
    if (keyStoreLocation != null) {
        keyStoreLocation = keyStoreLocation.trim();
        InputStream is = loadInputStream(loader, keyStoreLocation);

        try {
            keystore = load(is, keyStorePassword, provider, keyStoreType);
            if (DO_DEBUG) {
                LOG.debug("The KeyStore " + keyStoreLocation + " of type " + keyStoreType + " has been loaded");
            }
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else {
        keystore = load(null, keyStorePassword, provider, keyStoreType);
    }

    //
    // Load the TrustStore
    //
    String trustStorePassword = properties.getProperty(TRUSTSTORE_PASSWORD, "changeit");
    if (trustStorePassword != null) {
        trustStorePassword = trustStorePassword.trim();
    }
    String trustStoreType = properties.getProperty(TRUSTSTORE_TYPE, KeyStore.getDefaultType());
    if (trustStoreType != null) {
        trustStoreType = trustStoreType.trim();
    }
    String loadCacerts = properties.getProperty(LOAD_CA_CERTS, "false");
    if (loadCacerts != null) {
        loadCacerts = loadCacerts.trim();
    }
    String trustStoreLocation = properties.getProperty(TRUSTSTORE_FILE);
    if (trustStoreLocation != null) {
        trustStoreLocation = trustStoreLocation.trim();
        InputStream is = loadInputStream(loader, trustStoreLocation);

        try {
            truststore = load(is, trustStorePassword, provider, trustStoreType);
            if (DO_DEBUG) {
                LOG.debug("The TrustStore " + trustStoreLocation + " of type " + trustStoreType
                        + " has been loaded");
            }
            loadCACerts = false;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else if (Boolean.valueOf(loadCacerts).booleanValue()) {
        String cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
        if (cacertsPath != null) {
            cacertsPath = cacertsPath.trim();
        }
        InputStream is = new FileInputStream(cacertsPath);
        try {
            String cacertsPasswd = properties.getProperty(TRUSTSTORE_PASSWORD, "changeit");
            if (cacertsPasswd != null) {
                cacertsPasswd = cacertsPasswd.trim();
            }
            truststore = load(is, cacertsPasswd, null, KeyStore.getDefaultType());
            if (DO_DEBUG) {
                LOG.debug("CA certs have been loaded");
            }
            loadCACerts = true;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else {
        truststore = load(null, trustStorePassword, provider, trustStoreType);
    }
    //
    // Load the CRL file
    //
    String crlLocation = properties.getProperty(X509_CRL_FILE);
    if (crlLocation != null) {
        crlLocation = crlLocation.trim();
        InputStream is = loadInputStream(loader, crlLocation);

        try {
            CertificateFactory cf = getCertificateFactory();
            X509CRL crl = (X509CRL) cf.generateCRL(is);

            if (provider == null || provider.length() == 0) {
                crlCertStore = CertStore.getInstance("Collection",
                        new CollectionCertStoreParameters(Collections.singletonList(crl)));
            } else {
                crlCertStore = CertStore.getInstance("Collection",
                        new CollectionCertStoreParameters(Collections.singletonList(crl)), provider);
            }
            if (DO_DEBUG) {
                LOG.debug("The CRL " + crlLocation + " has been loaded");
            }
        } catch (Exception e) {
            if (DO_DEBUG) {
                LOG.debug(e.getMessage(), e);
            }
            throw new CredentialException(CredentialException.IO_ERROR, "ioError00", e);
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
}

From source file:org.candlepin.CRLBenchmark.java

@Benchmark
@Fork(value = 1, jvmArgsAppend = { "-Xloggc:gc_in_memory.log", "-verbose:gc", "-XX:+PrintGCDetails",
        "-XX:+PrintGCTimeStamps" })
public void inMemory() {
    InputStream stream = null;//from   www .  ja v a2 s  . com
    try {
        List<BigInteger> l = new LinkedList<BigInteger>();

        stream = new BufferedInputStream(new FileInputStream(crlFile));
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509CRL crl = (X509CRL) cf.generateCRL(stream);

        for (X509CRLEntry entry : crl.getRevokedCertificates()) {
            l.add(entry.getSerialNumber());
        }

        if (!"1999999".equals(l.get(1999999).toString())) {
            throw new RuntimeException("CRL list read in is incorrect");
        } else {
            System.out.println("Read " + l.size() + " entries");
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.candlepin.util.X509CRLEntryStreamTest.java

@Test
public void testIterateOverSerials() throws Exception {
    InputStream referenceStream = new FileInputStream(derFile);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509CRL referenceCrl = (X509CRL) cf.generateCRL(referenceStream);

    Set<BigInteger> referenceSerials = new HashSet<BigInteger>();

    for (X509CRLEntry entry : referenceCrl.getRevokedCertificates()) {
        referenceSerials.add(entry.getSerialNumber());
    }/*from   w ww  .  jav  a 2s.c o m*/

    X509CRLEntryStream stream = new X509CRLEntryStream(derFile);
    try {
        Set<BigInteger> streamedSerials = new HashSet<BigInteger>();
        while (stream.hasNext()) {
            streamedSerials.add(stream.next().getSerialNumber());
        }

        assertEquals(referenceSerials, streamedSerials);
    } finally {
        referenceStream.close();
        stream.close();
    }
}

From source file:org.candlepin.util.X509CRLEntryStreamTest.java

@Test
public void testPemReadThroughBase64Stream() throws Exception {
    /* NB: Base64InputStream only takes base64.  The "-----BEGIN X509 CRL-----" and
     * corresponding footer must be removed.  Luckily in Base64InputStream stops the
     * minute it sees a padding character and our test file has some padding.  Thus,
     * we don't need to worry about removing the footer.  If the Base64 file didn't
     * require padding, I'm not sure what happens so the footer should be removed
     * somehow for real uses *///from  w  w  w  .j a  v a  2s. c o  m

    InputStream referenceStream = new BufferedInputStream(new FileInputStream(pemFile));
    byte[] header = "-----BEGIN X509 CRL-----".getBytes("ASCII");
    Streams.readFully(referenceStream, header);

    referenceStream = new Base64InputStream(referenceStream);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509CRL referenceCrl = (X509CRL) cf.generateCRL(referenceStream);

    Set<BigInteger> referenceSerials = new HashSet<BigInteger>();

    for (X509CRLEntry entry : referenceCrl.getRevokedCertificates()) {
        referenceSerials.add(entry.getSerialNumber());
    }

    X509CRLEntryStream stream = new X509CRLEntryStream(derFile);
    try {
        Set<BigInteger> streamedSerials = new HashSet<BigInteger>();
        while (stream.hasNext()) {
            streamedSerials.add(stream.next().getSerialNumber());
        }

        assertEquals(referenceSerials, streamedSerials);
    } finally {
        referenceStream.close();
        stream.close();
    }
}

From source file:org.candlepin.util.X509CRLStreamWriterTest.java

private X509CRL readCRL(PublicKey signatureKey) throws Exception {
    // We could return a X509CRLHolder but that class isn't as fully featured as the built in
    // X509CRL.//from   ww  w . j a  va  2 s .co m
    InputStream changedStream = new BufferedInputStream(new FileInputStream(outfile));
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509CRL changedCrl = (X509CRL) cf.generateCRL(changedStream);
    changedCrl.verify(signatureKey, BC.PROVIDER_NAME);

    return changedCrl;
}