Example usage for java.security.cert X509CRL getEncoded

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

Introduction

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

Prototype

public abstract byte[] getEncoded() throws CRLException;

Source Link

Document

Returns the ASN.1 DER-encoded form of this CRL.

Usage

From source file:com.netscape.cms.publish.publishers.FileBasedPublisher.java

/**
 * Publishes a object to the ldap directory.
 *
 * @param conn a Ldap connection//  ww w  . j a v  a2s . c o  m
 *            (null if LDAP publishing is not enabled)
 * @param dn dn of the ldap entry to publish cert
 *            (null if LDAP publishing is not enabled)
 * @param object object to publish
 *            (java.security.cert.X509Certificate or,
 *            java.security.cert.X509CRL)
 */
public void publish(LDAPConnection conn, String dn, Object object) throws ELdapException {
    CMS.debug("FileBasedPublisher: publish");

    try {
        if (object instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) object;
            BigInteger sno = cert.getSerialNumber();
            String name = mDir + File.separator + "cert-" + sno.toString();
            if (mDerAttr) {
                FileOutputStream fos = null;
                try {
                    String fileName = name + ".der";
                    fos = new FileOutputStream(fileName);
                    fos.write(cert.getEncoded());
                } finally {
                    if (fos != null)
                        fos.close();
                }
            }
            if (mB64Attr) {
                String fileName = name + ".b64";
                PrintStream ps = null;
                Base64OutputStream b64 = null;
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(fileName);
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    b64 = new Base64OutputStream(new PrintStream(new FilterOutputStream(output)));
                    b64.write(cert.getEncoded());
                    b64.flush();
                    ps = new PrintStream(fos);
                    ps.print(output.toString("8859_1"));
                } finally {
                    if (ps != null) {
                        ps.close();
                    }
                    if (b64 != null) {
                        b64.close();
                    }
                    if (fos != null)
                        fos.close();
                }
            }
        } else if (object instanceof X509CRL) {
            X509CRL crl = (X509CRL) object;
            String[] namePrefix = getCrlNamePrefix(crl, mTimeStamp.equals("GMT"));
            String baseName = mDir + File.separator + namePrefix[0];
            String tempFile = baseName + ".temp";
            ZipOutputStream zos = null;
            byte[] encodedArray = null;
            File destFile = null;
            String destName = null;
            File renameFile = null;

            if (mDerAttr) {
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(tempFile);
                    encodedArray = crl.getEncoded();
                    fos.write(encodedArray);
                } finally {
                    if (fos != null)
                        fos.close();
                }
                if (mZipCRL) {
                    try {
                        zos = new ZipOutputStream(new FileOutputStream(baseName + ".zip"));
                        zos.setLevel(mZipLevel);
                        zos.putNextEntry(new ZipEntry(baseName + ".der"));
                        zos.write(encodedArray, 0, encodedArray.length);
                        zos.closeEntry();
                    } finally {
                        if (zos != null)
                            zos.close();
                    }
                }
                destName = baseName + ".der";
                destFile = new File(destName);

                if (destFile.exists()) {
                    destFile.delete();
                }
                renameFile = new File(tempFile);
                renameFile.renameTo(destFile);

                if (mLatestCRL) {
                    String linkExt = ".";
                    if (mLinkExt != null && mLinkExt.length() > 0) {
                        linkExt += mLinkExt;
                    } else {
                        linkExt += "der";
                    }
                    String linkName = mDir + File.separator + namePrefix[1] + linkExt;
                    createLink(linkName, destName);
                    if (mZipCRL) {
                        linkName = mDir + File.separator + namePrefix[1] + ".zip";
                        createLink(linkName, baseName + ".zip");
                    }
                }
            }

            // output base64 file
            if (mB64Attr == true) {
                if (encodedArray == null)
                    encodedArray = crl.getEncoded();
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(tempFile);
                    fos.write(Utils.base64encode(encodedArray, true).getBytes());
                } finally {
                    if (fos != null)
                        fos.close();
                }
                destName = baseName + ".b64";
                destFile = new File(destName);

                if (destFile.exists()) {
                    destFile.delete();
                }
                renameFile = new File(tempFile);
                renameFile.renameTo(destFile);
            }
            purgeExpiredFiles();
            purgeExcessFiles();
        }
    } catch (IOException e) {
        mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
                CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString()));
    } catch (CertificateEncodingException e) {
        mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
                CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString()));
    } catch (CRLException e) {
        mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE,
                CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString()));
    }
}

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

private TrustLinkerResult processCrl(URI crlUri, X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, BigInteger baseCrlNumber) {

    LOG.debug("CRL URI: " + crlUri);
    X509CRL x509crl = this.crlRepository.findCrl(crlUri, certificate, validationDate);
    if (null == x509crl) {
        return null;
    }/*from ww  w . j a  v a2s. c  om*/

    // check CRL integrity
    boolean crlIntegrityResult = checkCrlIntegrity(x509crl, certificate, validationDate);
    if (false == crlIntegrityResult) {
        return null;
    }

    // check CRL signature
    TrustLinkerResult trustResult = TrustValidator.checkSignatureAlgorithm(x509crl.getSigAlgName());
    if (!trustResult.isValid()) {
        return trustResult;
    }

    // we don't support indirect CRLs
    if (isIndirectCRL(x509crl)) {
        LOG.debug("indirect CRL detected");
        return null;
    }

    LOG.debug("CRL number: " + getCrlNumber(x509crl));
    // check delta CRL indicator against completeCrlNuber
    if (null != baseCrlNumber) {
        BigInteger crlNumber = getDeltaCrlIndicator(x509crl);
        if (!baseCrlNumber.equals(crlNumber)) {
            LOG.error("Delta CRL indicator (" + crlNumber + ") not equals base CRL number(" + baseCrlNumber
                    + ")");
            return null;
        }
    }

    // fill up revocation data if not null with this valid CRL
    if (null != revocationData) {
        try {
            revocationData.getCrlRevocationData().add(new CRLRevocationData(x509crl.getEncoded()));
        } catch (CRLException e) {
            LOG.error("CRLException: " + e.getMessage(), e);
            throw new RuntimeException("CRLException : " + e.getMessage(), e);
        }
    }

    boolean revoked = true;
    X509CRLEntry crlEntry = x509crl.getRevokedCertificate(childCertificate.getSerialNumber());
    if (null == crlEntry) {
        LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal());
        revoked = false;
    } else if (crlEntry.getRevocationDate().after(validationDate)) {
        LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal() + " at " + validationDate);
        revoked = false;
    }

    if (null != x509crl.getExtensionValue(X509Extensions.DeltaCRLIndicator.getId())) {
        // Delta CRL
        if (!revoked)
            return null;

    } else {
        // Base CRL, look for delta's
        List<URI> deltaCrlUris = getDeltaCrlUris(x509crl);
        if (null != deltaCrlUris) {
            for (URI deltaCrlUri : deltaCrlUris) {
                LOG.debug("delta CRL: " + deltaCrlUri.toString());
                TrustLinkerResult result = processCrl(deltaCrlUri, childCertificate, certificate,
                        validationDate, revocationData, getCrlNumber(x509crl));
                if (null != result)
                    return result;
            }
        }
    }

    if (!revoked)
        return new TrustLinkerResult(true);

    return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
            "certificate revoked by CRL=" + crlEntry.getSerialNumber());

}

From source file:com.sun.identity.security.cert.AMCRLStore.java

/**
 * Checks certificate and returns corresponding stored CRL in ldap store
 * @param certificate/* w  ww. ja  v  a  2 s .  co  m*/
 */
public X509CRL getCRL(X509Certificate certificate) throws IOException {
    LDAPEntry crlEntry = null;
    X509CRL crl = null;

    if (storeParam.isDoCRLCaching()) {
        if (debug.messageEnabled()) {
            debug.message("AMCRLStore.getCRL: Trying to get CRL from cache");
        }
        crl = (X509CRL) getCRLFromCache(certificate);
    }

    LDAPConnection ldc = getConnection();

    try {
        if (crl == null) {
            if (debug.messageEnabled()) {
                debug.message("AMCRLStore.getCRL: crl is null");
            }
            crlEntry = getLdapEntry(ldc);
            crl = getCRLFromEntry(crlEntry);
        }

        if (storeParam.isDoUpdateCRLs() && needCRLUpdate(crl)) {
            if (debug.messageEnabled()) {
                debug.message("AMCRLStore.getCRL: need CRL update");
            }

            X509CRL tmpcrl = null;
            IssuingDistributionPointExtension crlIDPExt = null;
            try {
                if (crl != null) {
                    crlIDPExt = getCRLIDPExt(crl);
                }
            } catch (Exception e) {
                debug.message("AMCRLStore.getCRL: crlIDPExt is null");
            }

            CRLDistributionPointsExtension crlDPExt = null;
            try {
                crlDPExt = getCRLDPExt(certificate);
            } catch (Exception e) {
                debug.message("AMCRLStore.getCRL: crlDPExt is null");
            }

            if ((tmpcrl == null) && (crlIDPExt != null)) {
                tmpcrl = getUpdateCRLFromCrlIDP(crlIDPExt);
            }

            if ((tmpcrl == null) && (crlDPExt != null)) {
                tmpcrl = getUpdateCRLFromCrlDP(crlDPExt);
            }

            if (tmpcrl != null) {
                if (crlEntry == null) {
                    crlEntry = getLdapEntry(ldc);
                }

                if (debug.messageEnabled()) {
                    debug.message("AMCRLStore.getCRL: new crl = " + tmpcrl);
                }

                if (crlEntry != null) {
                    updateCRL(ldc, crlEntry.getDN().toString(), tmpcrl.getEncoded());
                }
            }
            crl = tmpcrl;
        }

        if (storeParam.isDoCRLCaching()) {
            if (debug.messageEnabled()) {
                debug.message("AMCRLStore.getCRL: Updating CRL cache");
            }
            updateCRLCache(certificate, crl);
        }

    } catch (Exception e) {
        debug.error("AMCRLStore.getCRL: Error in getting CRL : ", e);
    } finally {
        if ((ldc != null) && (ldc.isConnected())) {
            try {
                ldc.disconnect();
            } catch (LDAPException ex) {
                //ignored
            }
        }
    }

    return crl;
}

From source file:org.candlepin.CRLBenchmark.java

@Setup(Level.Trial)
public void buildMassiveCRL() throws Exception {
    X500Name issuer = new X500Name("CN=Test Issuer");

    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

    generator.initialize(2048);//from w w w  . ja  v  a  2  s  . c o m
    KeyPair keyPair = generator.generateKeyPair();

    Provider bc = new BouncyCastleProvider();
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(bc)
            .build(keyPair.getPrivate());

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date());

    crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    /* With a CRL number of 127, incrementing it should cause the number of bytes in the length
     * portion of the TLV to increase by one.*/
    crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127")));

    for (int i = 0; i < 2000000; i++) {
        crlBuilder.addCRLEntry(new BigInteger(String.valueOf(i)), new Date(), CRLReason.unspecified);
    }

    X509CRLHolder holder = crlBuilder.build(signer);
    X509CRL crl = new JcaX509CRLConverter().setProvider(bc).getCRL(holder);

    crlFile = File.createTempFile("crl", ".der");
    System.out.println("\nWrote test crl to " + crlFile.getAbsolutePath());
    FileUtils.writeByteArrayToFile(crlFile, crl.getEncoded());
}

From source file:org.candlepin.CRLWriteBenchmark.java

@Benchmark
@Fork(value = 1, jvmArgsAppend = { "-Xloggc:gc_in_memory_write.log", "-verbose:gc", "-XX:+PrintGCDetails",
        "-XX:+PrintGCTimeStamps" })
public void inMemory() {
    ASN1InputStream stream = null;
    try {/*w w  w  .  j  a  va2 s . c o  m*/
        stream = new ASN1InputStream(new BufferedInputStream(new FileInputStream(crlFile)));
        DERObject o = stream.readObject();

        X509CRLHolder oldCrl = new X509CRLHolder(o.getDEREncoded());

        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date());
        crlBuilder.addCRL(oldCrl);

        crlBuilder.addCRLEntry(new BigInteger("25000000000"), new Date(), CRLReason.unspecified);

        X509CRLHolder holder = crlBuilder.build(signer);
        X509CRL crl = new JcaX509CRLConverter().setProvider(bc).getCRL(holder);

        File newCrlFile = File.createTempFile("new_crl", ".der");
        FileUtils.writeByteArrayToFile(newCrlFile, crl.getEncoded());
        System.out.println("\nWrote new crl to " + newCrlFile.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.candlepin.CRLWriteBenchmark.java

@Setup(Level.Trial)
public void buildMassiveCRL() throws Exception {
    issuer = new X500Name("CN=Test Issuer");

    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

    generator.initialize(2048);//from  w  w w.j  av a 2 s  .  c  o m
    KeyPair keyPair = generator.generateKeyPair();

    bc = new BouncyCastleProvider();
    signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(bc).build(keyPair.getPrivate());

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date());
    crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    /* With a CRL number of 127, incrementing it should cause the number of bytes in the length
     * portion of the TLV to increase by one.*/
    crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127")));

    for (int i = 0; i < 2000000; i++) {
        crlBuilder.addCRLEntry(new BigInteger(String.valueOf(i)), new Date(), CRLReason.unspecified);
    }

    X509CRLHolder holder = crlBuilder.build(signer);
    X509CRL crl = new JcaX509CRLConverter().setProvider(bc).getCRL(holder);

    crlFile = File.createTempFile("crl", ".der");
    System.out.println("\nWrote test crl to " + crlFile.getAbsolutePath());
    FileUtils.writeByteArrayToFile(crlFile, crl.getEncoded());
}

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

/**
 * Gets issuer DN for CRL in the format we are sure about (BouncyCastle),supporting UTF8.
 * /*from  www  . ja v  a 2  s  .c  om*/
 * @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

/**
 * Generate SHA1 fingerprint of CRL in string representation.
 * /*from  ww  w  . ja va  2  s.  c  om*/
 * @param crl X509CRL.
 * 
 * @return String containing hex format of SHA1 fingerprint.
 */
public static String getFingerprintAsString(X509CRL crl) {
    try {
        byte[] res = generateSHA1Fingerprint(crl.getEncoded());

        return new String(Hex.encode(res));
    } catch (CRLException ce) {
        log.error("Error encoding CRL.", ce);
    }

    return null;
}

From source file:org.ejbca.core.model.ca.publisher.LdapPublisher.java

/**
 * Method to lazy create the fake CRL.//from  w ww  .j a v a 2 s .  c  o  m
 */
protected byte[] getFakeCRL() {
    byte[] fakecrl = null;
    try {
        X509CRL crl = CertTools.getCRLfromByteArray(fakecrlbytes);
        fakecrl = crl.getEncoded();
    } catch (CRLException e) {
    }
    return fakecrl;
}

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 ww. j  av  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);
}