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.crl.OfflineCrlRepository.java

/**
 * Main constructor//from   w  w w .  j a v  a2  s. com
 * 
 * @param encodedCrls
 *            the list of encoded CRL's that can be queried.
 * @throws NoSuchProviderException
 * @throws CertificateException
 * @throws CRLException
 */
public OfflineCrlRepository(List<byte[]> encodedCrls)
        throws CertificateException, NoSuchProviderException, CRLException {

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
    this.crls = new LinkedList<X509CRL>();
    for (byte[] encodedCrl : encodedCrls) {
        ByteArrayInputStream bais = new ByteArrayInputStream(encodedCrl);
        this.crls.add((X509CRL) certificateFactory.generateCRL(bais));
    }
}

From source file:be.fedict.trust.service.bean.HarvesterMDB.java

private void processHarvestMessage(HarvestMessage harvestMessage) {
    if (null == harvestMessage) {
        return;/*from  w w w  . j a v a 2  s.com*/
    }
    String caName = harvestMessage.getCaName();
    boolean update = harvestMessage.isUpdate();
    String crlFilePath = harvestMessage.getCrlFile();
    File crlFile = new File(crlFilePath);

    LOG.debug("processHarvestMessage - Don't have CA's Serial Number??");
    LOG.debug("issuer: " + caName);
    CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(caName);
    if (null == certificateAuthority) {
        LOG.error("unknown certificate authority: " + caName);
        deleteCrlFile(crlFile);
        return;
    }
    if (!update && Status.PROCESSING != certificateAuthority.getStatus()) {
        /*
         * Possible that another harvester instance already activated or is
         * processing the CA cache in the meanwhile.
         */
        LOG.debug("CA status not marked for processing");
        deleteCrlFile(crlFile);
        return;
    }

    Date validationDate = new Date();

    X509Certificate issuerCertificate = certificateAuthority.getCertificate();

    Date notAfter = issuerCertificate.getNotAfter();
    if (validationDate.after(notAfter)) {
        LOG.info("will not update CRL cache for expired CA: " + issuerCertificate.getSubjectX500Principal());
        deleteCrlFile(crlFile);
        return;
    }

    FileInputStream crlInputStream;
    try {
        crlInputStream = new FileInputStream(crlFile);
    } catch (FileNotFoundException e) {
        LOG.error("CRL file does not exist: " + crlFilePath);
        return;
    }
    X509CRL crl;
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
        crl = (X509CRL) certificateFactory.generateCRL(crlInputStream);
    } catch (Exception e) {
        LOG.error("BC error: " + e.getMessage(), e);
        deleteCrlFile(crlFile);
        return;
    }

    LOG.debug("checking integrity CRL...");
    boolean crlValid = CrlTrustLinker.checkCrlIntegrity(crl, issuerCertificate, validationDate);
    if (!crlValid) {
        this.auditDAO.logAudit("Invalid CRL for CA=" + caName);
        deleteCrlFile(crlFile);
        return;
    }
    BigInteger crlNumber = getCrlNumber(crl);
    LOG.debug("CRL number: " + crlNumber);

    BigInteger currentCrlNumber = this.certificateAuthorityDAO.findCrlNumber(caName);
    if (null != currentCrlNumber) {
        LOG.debug("CRL number in database: " + currentCrlNumber);
    }
    if (null != currentCrlNumber && currentCrlNumber.compareTo(crlNumber) >= 0
            && certificateAuthority.getStatus() == Status.ACTIVE) {
        // current CRL cache is higher or equal, no update needed
        LOG.debug("current CA cache is new enough.");
        deleteCrlFile(crlFile);
        return;
    }

    List<RevokedCertificateEntity> revokedCertificateEntities = this.certificateAuthorityDAO
            .getRevokedCertificates(caName);
    LOG.debug("number of revoked certificates in database: " + revokedCertificateEntities.size());
    Map<String, RevokedCertificateEntity> revokedCertificatesMap = new HashMap<String, RevokedCertificateEntity>();
    for (RevokedCertificateEntity revokedCertificateEntity : revokedCertificateEntities) {
        String serialNumber = revokedCertificateEntity.getPk().getSerialNumber();
        revokedCertificatesMap.put(serialNumber, revokedCertificateEntity);
    }

    LOG.debug("processing CRL... " + caName);
    boolean isIndirect;
    Enumeration revokedCertificatesEnum;
    try {
        isIndirect = isIndirectCRL(crl);
        revokedCertificatesEnum = getRevokedCertificatesEnum(crl);
    } catch (Exception e) {
        this.auditDAO.logAudit("Failed to parse CRL for CA=" + caName);
        this.failures++;
        throw new RuntimeException(e);
    }

    int entries = 0;
    if (revokedCertificatesEnum.hasMoreElements()) {
        /*
         * Split up persisting the crl entries to avoid memory issues.
         */
        Set<X509CRLEntry> revokedCertsBatch = new HashSet<X509CRLEntry>();
        X500Principal previousCertificateIssuer = crl.getIssuerX500Principal();
        int added = 0;
        while (revokedCertificatesEnum.hasMoreElements()) {

            TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry) revokedCertificatesEnum.nextElement();
            X500Name x500name = new X500Name(previousCertificateIssuer.getName(X500Principal.RFC1779));
            X509CRLEntryObject revokedCertificate = new X509CRLEntryObject(entry, isIndirect, x500name);
            previousCertificateIssuer = revokedCertificate.getCertificateIssuer();

            revokedCertsBatch.add(revokedCertificate);
            added++;
            if (added == BATCH_SIZE) {
                /*
                 * Persist batch
                 */
                this.certificateAuthorityDAO.updateRevokedCertificates(revokedCertsBatch, crlNumber,
                        crl.getIssuerX500Principal(), revokedCertificatesMap);
                entries += revokedCertsBatch.size();
                revokedCertsBatch.clear();
                added = 0;
            }
        }
        /*
         * Persist final batch
         */
        this.certificateAuthorityDAO.updateRevokedCertificates(revokedCertsBatch, crlNumber,
                crl.getIssuerX500Principal(), revokedCertificatesMap);
        entries += revokedCertsBatch.size();

        /*
         * Cleanup redundant CRL entries
         */
        if (null != crlNumber) {
            this.certificateAuthorityDAO.removeOldRevokedCertificates(crlNumber,
                    crl.getIssuerX500Principal().toString());
        }
    }

    deleteCrlFile(crlFile);

    LOG.debug("CRL this update: " + crl.getThisUpdate());
    LOG.debug("CRL next update: " + crl.getNextUpdate());
    certificateAuthority.setStatus(Status.ACTIVE);
    certificateAuthority.setThisUpdate(crl.getThisUpdate());
    certificateAuthority.setNextUpdate(crl.getNextUpdate());
    LOG.debug("cache activated for CA: " + crl.getIssuerX500Principal() + " (entries=" + entries + ")");
}

From source file:FileSystemDirectoryCertStore.java

private void transverseDirToFindContent(File dir, Collection contentList, String[] certsFilesExts,
        String[] crlsFilesExts, CertificateFactory cf) throws CertificateException, CRLException {
    File[] dirContents = dir.listFiles();
    for (int i = 0; i < dirContents.length; i++) {
        File f = dirContents[i];//ww  w  .ja va2  s.c  om

        if (f.isDirectory())
            transverseDirToFindContent(f, contentList, certsFilesExts, crlsFilesExts, cf);
        else if (f.isFile())
            try {
                if (hasExt(f, certsFilesExts))
                    contentList.add((X509Certificate) cf.generateCertificate(new FileInputStream(f)));
                else if (hasExt(f, crlsFilesExts))
                    contentList.add((X509CRL) cf.generateCRL(new FileInputStream(f)));
            } catch (FileNotFoundException ex) {
                // The file existed right up there! If somehow it doesn't exist
                // now, nevermind.
            }
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.pades.PAdESSignature.java

@Override
public ListCRLSource getCRLSource() {

    PdfDict dss = getDSSDictionary();//from   w  ww.  jav a  2s.c  o  m
    try {

        List<X509CRL> list = new ArrayList<X509CRL>();
        if (dss != null) {

            PdfArray crlArray = dss.getAsArray("CRLs");
            if (crlArray != null) {

                CertificateFactory factory = CertificateFactory.getInstance("X509");
                for (int i = 0; i < crlArray.size(); i++) {

                    byte[] stream = crlArray.getBytes(i);
                    X509CRL cert = (X509CRL) factory.generateCRL(new ByteArrayInputStream(stream));
                    if (!list.contains(cert)) {

                        list.add(cert);
                    }
                }
            }
        }
        if (list.size() > 0) {
            return new ListCRLSource(list);
        }
    } catch (IOException ex) {

        throw new DSSException(ex);
    } catch (CertificateException e) {

        throw new DSSException(e);
    } catch (CRLException e) {

        throw new DSSException(e);
    }
    return null;
}

From source file:be.fedict.trust.client.XKMS2Client.java

/**
 * Validate the specified certificate chain against the specified trust
 * domain using historical validation using the specified revocation data.
 *//*w  w  w  .  j a va 2s . c o m*/
public void validateEncoded(String trustDomain, List<X509Certificate> certificateChain, Date validationDate,
        List<byte[]> ocspResponses, List<byte[]> crls)
        throws CertificateEncodingException, TrustDomainNotFoundException, RevocationDataNotFoundException,
        ValidationFailedException, RevocationDataCorruptException {
    if ((null == ocspResponses || ocspResponses.isEmpty()) && (null == crls || crls.isEmpty())) {
        LOG.error("No revocation data for historical validation.");
        throw new RevocationDataNotFoundException();
    }

    try {
        // check encoded OCSP response are valid
        for (byte[] encodedOcspResponse : ocspResponses) {
            new OCSPResp(encodedOcspResponse);
        }
        // check encoded CRLs are valid
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        for (byte[] encodedCrl : crls) {
            ByteArrayInputStream bais = new ByteArrayInputStream(encodedCrl);
            certificateFactory.generateCRL(bais);
        }
    } catch (IOException e) {
        throw new RevocationDataCorruptException("Invalid OCSP response", e);
    } catch (CRLException e) {
        throw new RevocationDataCorruptException("Invalid CRL", e);
    } catch (CertificateException e) {
        throw new RevocationDataCorruptException(e);
    }

    validate(trustDomain, certificateChain, false, validationDate, ocspResponses, crls, null, null, null);
}

From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java

/**
 *  CRL- ? ,    ? ? ,  ? ?//from www . j a va2s. c o m
 *   ? 
 *
 * @param crlName
 */
private void loadCrlObject(String crlName) {
    TypeOfCrlLoaded oldState = MAP_OF_LOAD_CRL_LABEL.get(crlName);
    if (TypeOfCrlLoaded.LOADING.equals(oldState)) {
        return;
    }
    MAP_OF_LOAD_CRL_LABEL.put(crlName, TypeOfCrlLoaded.LOADING);
    String location = MAP_OF_CRL_PATH.get(crlName);
    try {
        URL url = new URL(location);
        HttpURLConnection conn = null;
        if (useProxy) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort));
            conn = (HttpURLConnection) url.openConnection(proxy);
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.connect();
        if (conn.getResponseCode() == 200) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509", "KALKAN");
            X509CRL crlObject = (X509CRL) cf.generateCRL(conn.getInputStream());
            MAP_OF_XCRL.put(crlName, crlObject);
        } else {
            String msg = "(1) ? CRL- : '" + location + "' : "
                    + conn.getResponseCode() + " ,  " + conn.getResponseMessage();
            log.warning(msg);
        }
    } catch (Exception e) {
        String msg = "(1) ? CRL- : '" + location + "' : "
                + e.getMessage();
        log.warning(msg);
    }
    //MAP_OF_LOAD_CRL_LABEL.put(crlName, oldState ) ;
    MAP_OF_LOAD_CRL_TIME.put(crlName, new Date());
    MAP_OF_LOAD_CRL_LABEL.put(crlName, TypeOfCrlLoaded.LOADED);
}

From source file:com.verisign.epp.codec.launch.EPPLaunchTst.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 w  w.j  av a  2  s .c om*/
 * @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
 */
public static PKIXParameters loadPKIXParameters(String aTrustStoreName, List<String> aCrls) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream trustStoreFile = new FileInputStream(aTrustStoreName);
    trustStore.load(trustStoreFile, null);
    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 {
                inStream = new FileInputStream(currCrl);
                crlContentsList.add(certFactory.generateCRL(inStream));
            } finally {
                if (inStream != null) {
                    inStream.close();
                }
            }
        } else {
            System.err.println("CRL file \"" + currCrl + "\" NOT found.");
        }

    }

    // 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);
        System.out.println("Revocation enabled");
    } else {
        pkixParameters.setRevocationEnabled(false);
        System.out.println("Revocation disabled.");

    }

    return pkixParameters;
}

From source file:eu.europa.ec.markt.dss.validation.pades.PDFDocumentValidator.java

private boolean checkVriDict(PdfDictionary vriSigDictionary, boolean _vriVerificationresult,
        PAdESSignature pades, ValidationContext ctx, String hexHash)
        throws CertificateException, IOException, CRLException, OCSPException {

    boolean vriVerificationresult = _vriVerificationresult;

    if (vriSigDictionary == null) {
        LOG.info("Couldn't find the signature VRI identified by " + hexHash + " in the DSS");
        vriVerificationresult = false;// ww  w. j a v a 2  s .co m
    } else {
        LOG.info("Found the signature VRI identified by " + hexHash + " in the DSS");

        // Verify the certs in the VRI
        PdfArray vricert = vriSigDictionary.getAsArray(new PdfName("Cert"));
        if (vricert != null) {
            CertificateFactory factory = CertificateFactory.getInstance("X509");
            List<X509Certificate> certs = new ArrayList<X509Certificate>();
            for (int i = 0; i < vricert.size(); i++) {
                PdfStream stream = vricert.getAsStream(i);
                certs.add((X509Certificate) factory.generateCertificate(
                        new ByteArrayInputStream(PdfReader.getStreamBytes((PRStream) stream))));
            }
            vriVerificationresult &= everyCertificateValueAreThere(ctx, certs, pades.getSigningCertificate());
        }

        // Verify the CRLs in the VRI
        PdfArray vricrl = vriSigDictionary.getAsArray(new PdfName("CRL"));
        if (vricrl != null) {
            CertificateFactory factory = CertificateFactory.getInstance("X509");
            List<X509CRL> crls = new ArrayList<X509CRL>();
            for (int i = 0; i < vricrl.size(); i++) {
                PdfStream stream = vricrl.getAsStream(i);
                crls.add((X509CRL) factory
                        .generateCRL(new ByteArrayInputStream(PdfReader.getStreamBytes((PRStream) stream))));
            }
            vriVerificationresult &= everyCRLValueOrRefAreThere(ctx, crls);
        }

        // Verify the OCSPs in the VRI
        PdfArray vriocsp = vriSigDictionary.getAsArray(new PdfName("OCSP"));
        if (vriocsp != null) {
            List<BasicOCSPResp> ocsps = new ArrayList<BasicOCSPResp>();
            for (int i = 0; i < vriocsp.size(); i++) {
                PdfStream stream = vriocsp.getAsStream(i);
                ocsps.add((BasicOCSPResp) new OCSPResp(PdfReader.getStreamBytes((PRStream) stream))
                        .getResponseObject());
            }
            vriVerificationresult &= everyOCSPValueOrRefAreThere(ctx, ocsps);
        }

    }

    return vriVerificationresult;
}

From source file:edu.uiuc.ncsa.myproxy.MyProxyLogon.java

/**
 * Gets the CRLs returned by the MyProxy server.
 *
 * @return CRLs or null if none available
 *//*from w  w  w.  j ava 2s.c o  m*/
public X509CRL[] getCRLs() throws CertificateException {
    if (trustrootData == null)
        return null;
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    Collection<X509CRL> c = new ArrayList<X509CRL>(trustrootData.length);
    for (int i = 0; i < trustrootData.length; i++) {
        String crlData = trustrootData[i];
        int index = crlData.indexOf("-----BEGIN X509 CRL-----");
        if (index >= 0) {
            crlData = crlData.substring(index);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(crlData.getBytes());
            try {
                X509CRL crl = (X509CRL) certFactory.generateCRL(inputStream);
                c.add(crl);
            } catch (Exception e) {
                getMlf().warn(this.trustrootFilenames[i] + " can not be parsed as an X509CRL.");
            }
        }
    }
    if (c.isEmpty())
        return null;
    return c.toArray(new X509CRL[0]);
}