Example usage for java.security.cert X509CRL getNextUpdate

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

Introduction

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

Prototype

public abstract Date getNextUpdate();

Source Link

Document

Gets the nextUpdate date from the CRL.

Usage

From source file:mitm.common.security.crl.GenerateTestCRLs.java

@Test
public void testGenerateRootEmptyCRL() throws Exception {
    X509CRLBuilder crlGenerator = createX509CRLBuilder();

    Date thisDate = TestUtils.parseDate("30-Nov-2007 11:38:35 GMT");

    Date nextDate = TestUtils.parseDate("30-Nov-2027 11:38:35 GMT");

    crlGenerator.setThisUpdate(thisDate);
    crlGenerator.setNextUpdate(nextDate);
    crlGenerator.setSignatureAlgorithm("SHA256WithRSAEncryption");

    X509CRL crl = crlGenerator.generateCRL(new KeyAndCertificateImpl(rootPrivateKey, rootCertificate));

    assertEquals("EMAILADDRESS=root@example.com, CN=MITM Test Root, L=Amsterdam, ST=NH, C=NL",
            crl.getIssuerX500Principal().toString());
    assertEquals(thisDate, crl.getThisUpdate());
    assertEquals(nextDate, crl.getNextUpdate());
    assertNull(crl.getRevokedCertificates());
    assertFalse(crl.isRevoked(caCertificate));

    File crlFile = new File("test/tmp/test-generate-root-empty.crl");

    FileOutputStream fos = new FileOutputStream(crlFile);

    IOUtils.write(crl.getEncoded(), fos);

    fos.close();//from  ww  w.  jav a  2 s .  c o m
}

From source file:mitm.common.security.crl.GenerateTestCRLs.java

@Test
public void testGenerateRootRevokedCRL() throws Exception {
    X509CRLBuilder crlGenerator = createX509CRLBuilder();

    Date thisDate = TestUtils.parseDate("30-Nov-2007 11:38:35 GMT");

    Date nextDate = TestUtils.parseDate("30-Nov-2027 11:38:35 GMT");

    crlGenerator.setThisUpdate(thisDate);
    crlGenerator.setNextUpdate(nextDate);
    crlGenerator.setSignatureAlgorithm("SHA256WithRSAEncryption");

    crlGenerator.addCRLEntry(caCertificate.getSerialNumber(), thisDate, CRLReason.cACompromise);

    X509CRL crl = crlGenerator.generateCRL(new KeyAndCertificateImpl(rootPrivateKey, rootCertificate));

    assertEquals("EMAILADDRESS=root@example.com, CN=MITM Test Root, L=Amsterdam, ST=NH, C=NL",
            crl.getIssuerX500Principal().toString());
    assertEquals(thisDate, crl.getThisUpdate());
    assertEquals(nextDate, crl.getNextUpdate());
    assertEquals(1, crl.getRevokedCertificates().size());
    assertTrue(crl.isRevoked(caCertificate));

    File crlFile = new File("test/tmp/test-generate-root-ca-revoked.crl");

    FileOutputStream fos = new FileOutputStream(crlFile);

    IOUtils.write(crl.getEncoded(), fos);

    fos.close();/*from  w w w  . ja va  2s.  co m*/
}

From source file:mitm.common.security.crl.GenerateTestCRLs.java

@Test
public void testGenerateCACRLSignedByIncorrectKey() throws Exception {
    X509CRLBuilder crlGenerator = createX509CRLBuilder();

    Date thisDate = TestUtils.parseDate("30-Nov-2007 11:38:35 GMT");

    Date nextDate = TestUtils.parseDate("30-Nov-2027 11:38:35 GMT");

    crlGenerator.setThisUpdate(thisDate);
    crlGenerator.setNextUpdate(nextDate);
    crlGenerator.setSignatureAlgorithm("SHA256WithRSAEncryption");

    X509Certificate certificate = TestUtils
            .loadCertificate("test/resources/testdata/certificates/" + "valid_certificate_mitm_test_ca.cer");
    assertNotNull(certificate);//  w  w w  .j av  a 2 s.  c o m

    crlGenerator.addCRLEntry(certificate.getSerialNumber(), thisDate, CRLReason.privilegeWithdrawn);

    String encodedPrivateKey = "30820276020100300d06092a864886f70d0101010500048202603082025c"
            + "02010002818100a9fee3017954c99b248d1486830c71b2e0ea3f9b7a2763"
            + "1bed8a731f5bd7e1edf856bc3fb7c63dedbeb5bb0de474e7792b3aa7e7b2"
            + "274c03a47c7d89b1935eaef172c6395f2322f1ed9e61ae46d716b4b4394c"
            + "1a802db05a2d7c3d1d41a3e8afc65ff8dada7414744f1ee1540e50ee7fb8"
            + "db437b20c5ee33a82b9d575cfbc951020301000102818004f84ab2b45562"
            + "3f82e60cff91bd3f65b765a1ce6dd7d0f1f413e421ba91a92d47e161478b"
            + "9be41b9b43bce03f199bdad304b7fbf21d6bff7f439477fe150ce38c312f"
            + "c015f3c89291aaa42c4c106f623dfd9f76acad2f1c77b590f038ffbb25f9"
            + "14b6f7ead769808ddd0e2d648442620b50518d9b7fb132b2fa1fa3e9d628"
            + "41024100e69ab3765120d0e0ba5dc21bf384b2f553211b4b1902175454c6"
            + "2f1b0f8ad385d78490539308c9fd5145ae36cc2a6d364fdd97d83d9b6623"
            + "a987db239e716055024100bcb77acf1e9829ab5b2c9a5e73d343db857474"
            + "a529ba52ca256655eb7d760e85d3c68eec9500e3db0494c8f77cb8058593"
            + "6e52a9290149367392d74ecdc3510d024100bd15723b7cb024b56ffabad3"
            + "c26c3774f2b1bdb8690c0ee7060feec6088b737f56450b368be4740332e5"
            + "a8c0a3cdd1f8eba9adfd101ee0b43329036584604075024055465b9a27ea"
            + "fe394e33b375a6c4fa4ec1d943b4364cd9883aaa297d05ee48d5b4426ee6"
            + "fcd5b02091cb619c63a10bedb6170e071e5e5464e4889ffe1e007a290240"
            + "7b60d23994a2ec38db909678446ed56d32455bf684141b9ee0aec68b2025"
            + "1d4d94fd2beebf02074559b811ae1130d2e2aa3bec2e9bccb06969104856" + "00c70759";

    PrivateKey privateKey = decodePrivateKey(encodedPrivateKey);

    // sign not by the caPrivateKey but by some other key
    X509CRL crl = crlGenerator.generateCRL(new KeyAndCertificateImpl(privateKey, caCertificate));

    assertEquals("EMAILADDRESS=ca@example.com, CN=MITM Test CA, L=Amsterdam, ST=NH, C=NL",
            crl.getIssuerX500Principal().toString());
    assertEquals(thisDate, crl.getThisUpdate());
    assertEquals(nextDate, crl.getNextUpdate());
    assertEquals(1, crl.getRevokedCertificates().size());
    assertTrue(crl.isRevoked(certificate));

    File crlFile = new File("test/tmp/test-generate-ca-signed-incorrect-key.crl");

    FileOutputStream fos = new FileOutputStream(crlFile);

    IOUtils.write(crl.getEncoded(), fos);

    fos.close();
}

From source file:net.sf.dsig.verify.X509CRLHelper.java

/**
 * Retrieve the CRL/*  w  ww .  jav  a 2s .c  om*/
 * 
 * @param distributionPointUriAsString the distribution point URI
 * @return the {@link X509CRL} object
 * @throws NetworkAccessException when any network access issues occur
 * @throws VerificationException when an error occurs while parsing the CRL
 */
public X509CRL getX509CRL(String distributionPointUriAsString)
        throws NetworkAccessException, VerificationException {
    synchronized (mutex) {
        Date nextUpdate = (Date) uriNextUpdateMap.get(distributionPointUriAsString);
        if (nextUpdate != null && nextUpdate.after(new Date())) {
            logger.debug("Returning cached X509CRL" + "; distributionPoint=" + distributionPointUriAsString
                    + ", nextUpdate=" + nextUpdate);
            return (X509CRL) uriX509CrlMap.get(distributionPointUriAsString);
        }

        HostConfiguration config = getHostConfiguration();

        GetMethod get = new GetMethod(distributionPointUriAsString);
        try {
            getHttpClient().executeMethod(config, get);

            logger.debug("HTTP GET executed" + "; distributionPointUri=" + distributionPointUriAsString
                    + ", statusLine=" + get.getStatusLine());

            if (get.getStatusCode() != HttpStatus.SC_OK) {
                throw new NetworkAccessException("HTTP GET failed; statusLine=" + get.getStatusLine());
            }

            X509CRL crl = null;
            byte[] responseBodyBytes = get.getResponseBody();
            try {
                crl = (X509CRL) CertificateFactory.getInstance("X.509")
                        .generateCRL(new ByteArrayInputStream(responseBodyBytes));
            } catch (CertificateException e) {
                throw new ConfigurationException("X.509 certificate factory missing");
            }

            uriNextUpdateMap.put(distributionPointUriAsString, crl.getNextUpdate());
            uriX509CrlMap.put(distributionPointUriAsString, crl);

            return crl;
        } catch (IOException e) {
            throw new NetworkAccessException("I/O error occured", e);
        } catch (CRLException e) {
            throw new VerificationException("Error while following CRL protocol", e);
        } finally {
            get.releaseConnection();
        }
    }
}

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

private boolean needCRLUpdate(X509CRL crl) {
    Date nextCRLUpdate = null;//from  w w w .j  a  va 2s  . c o  m
    if (crl == null) {
        return true;
    }
    // Check CRLNextUpdate in CRL
    nextCRLUpdate = crl.getNextUpdate();
    if (debug.messageEnabled()) {
        debug.message("AMCRLStore.needCRLUpdate: nextCrlUpdate = " + nextCRLUpdate);
    }

    return ((nextCRLUpdate != null) && nextCRLUpdate.before(new Date()));
}

From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java

protected void checkCRL(X509Certificate cert, CertificateRevocationLists crlsList,
        TrustedCertificates trustedCerts) throws ProxyPathValidatorException {
    if (crlsList == null) {
        return;/*from   w  w w. jav a  2 s.c om*/
    }

    logger.debug("checkCRLs: enter");
    // Should not happen, just a sanity check.
    if (trustedCerts == null) {
        String err = "Trusted certificates are null, cannot verify CRLs";
        logger.error(err);
        throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, null, err);
    }

    String issuerName = cert.getIssuerDN().getName();
    X509CRL crl = crlsList.getCrl(issuerName);
    if (crl == null) {
        logger.debug("No CRL for certificate");
        return;
    }

    // get CA cert for the CRL
    X509Certificate x509Cert = trustedCerts.getCertificate(issuerName);
    if (x509Cert == null) {
        // if there is no trusted certs from that CA, then
        // the chain cannot contain a cert from that CA,
        // which implies not checking this CRL should be fine.
        logger.debug("No trusted cert with this CA signature");
        return;
    }

    // validate CRL
    try {
        crl.verify(x509Cert.getPublicKey());
    } catch (Exception exp) {
        logger.error("CRL verification failed");
        throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, exp);
    }

    Date now = new Date();
    // check date validity of CRL
    if ((crl.getThisUpdate().before(now))
            || ((crl.getNextUpdate() != null) && (crl.getNextUpdate().after(now)))) {
        if (crl.isRevoked(cert)) {
            throw new ProxyPathValidatorException(ProxyPathValidatorException.REVOKED, cert,
                    "This cert " + cert.getSubjectDN().getName() + " is on a CRL");
        }
    }

    logger.debug("checkCRLs: exit");
}

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

private void processHarvestMessage(HarvestMessage harvestMessage) {
    if (null == harvestMessage) {
        return;/* www  .  j  a va2 s.c o m*/
    }
    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:mitm.common.security.crl.PKIXRevocationChecker.java

private RevocationDetail getRevocationDetail(List<X509CRL> crls, X509Certificate targetCertificate,
        X509Certificate issuerCertificate, PublicKey issuerPublicKey, Date now) throws NoSuchProviderException {
    RevocationDetailImpl detail = new RevocationDetailImpl(RevocationStatus.UNKNOWN);

    boolean validCRLFound = false;

    int reasonMask = 0;

    for (X509CRL crl : crls) {
        BigInteger serialNumber = targetCertificate.getSerialNumber();

        X509CRLEntry crlEntry = crl.getRevokedCertificate(serialNumber);

        Date revocationDate = null;

        if (crlEntry != null) {
            revocationDate = crlEntry.getRevocationDate();

            if (revocationDate == null || !now.before(revocationDate)) {
                /*/*from  www. ja  v  a2  s .  c o  m*/
                 * X.509 7.3 NOTE 4  When an implementation processing a certificate revocation list does not 
                 * recognize a critical extension in the crlEntryExtensions field, it shall assume that, 
                 * at a minimum, the identified certificate has been revoked and is no longer valid and 
                 * perform additional actions concerning that revoked certificate as dictated by local policy.
                 *
                 * We do not need to check for unsupported critical extension because if we do not support them
                 * we should assume that the certificate is revoked.
                 */

                // TODO: add support for onHold/removeFromCRL

                Integer reasonCode = null;
                try {
                    reasonCode = X509CRLEntryInspector.getReasonCode(crlEntry);
                } catch (IOException e) {
                    logger.error("Error retrieving reasonCode.", e);
                }

                detail = (reasonCode != null ? new RevocationDetailImpl(RevocationStatus.REVOKED, reasonCode)
                        : new RevocationDetailImpl(RevocationStatus.REVOKED));

                /* there is no need to continue because certificate is revoked */
                break;
            } else {
                if (now.before(revocationDate)) {
                    logger.info("Certificate is revoked in the future.");
                }
            }
        }

        if (hasUnsupportedCriticalExtensions(crl)) {
            logger.debug("The CRL has unsupported critical extensions.");

            detail = new RevocationDetailImpl(RevocationStatus.UNSUPPORTED_CRITICAL_EXTENSION);

            continue;
        }

        /*
         * check that the start time the CRL is valid is before the time the certificate is 
         * no longer valid. In other words, that the expiration date of the certificate is 
         * later than the date the CRL was issued. It is possible that the certificate was
         * at some point revoked but the CA removed it because the certificate is no longer 
         * valid
         */
        if (crl.getThisUpdate() != null && targetCertificate.getNotAfter().before(crl.getThisUpdate())) {
            logger.info("Certificate has expired before the CRL was valid.");

            continue;
        }

        try {
            if (X509CRLInspector.isDeltaCRL(crl)) {
                DeltaCRLStatus deltaStatus = getDeltaCRLStatus(targetCertificate, crl, issuerPublicKey, now);

                if (deltaStatus == DeltaCRLStatus.UNSUPPORTED_CRITICAL_EXTENSION) {
                    detail = new RevocationDetailImpl(RevocationStatus.UNSUPPORTED_CRITICAL_EXTENSION);

                    continue;
                } else if (deltaStatus == DeltaCRLStatus.UNKNOWN) {
                    continue;
                }
            } else {
                if (!acceptCRL_6_3_3_b(targetCertificate, crl)) {
                    logger.debug("CRL not valid according to acceptCRL_6_3_3_b.");
                    continue;
                }
            }
        } catch (IOException e) {
            logger.error("Error inspecting CRL.", e);

            continue;
        }

        if (crl.getNextUpdate() != null && now.after(crl.getNextUpdate())) {
            /*
             * an CRL cannot really expire but, when we want at least to log that the 
             * nextUpdate is overdue
             */
            logger.debug("The CRL next update is overdue.");

            /* we need to set the nextUpdate if this is a newer CRL */

            if (detail.getStatus() != RevocationStatus.EXPIRED || detail.getNextUpdate() == null) {
                detail = new RevocationDetailImpl(RevocationStatus.EXPIRED, crl.getNextUpdate());
            } else {
                if (crl.getNextUpdate().after(detail.getNextUpdate())) {
                    /* the nextUpdate of the current CRL is later so it's longer valid */
                    detail = new RevocationDetailImpl(RevocationStatus.EXPIRED, crl.getNextUpdate());
                }
            }

            continue;
        }

        try {
            reasonMask = reasonMask | getInterimReasonsMask(targetCertificate, crl);

            /* a valid crl was found. Continue search. */
            validCRLFound = true;
        } catch (IOException e) {
            logger.error("Error getting interim mask.", e);
        }
    }

    /*
     * if one the CRLs was good and the certificate was not revoked we will set the 
     * status to NOT_REVOKED
     */
    if (validCRLFound && detail.getStatus() != RevocationStatus.REVOKED) {
        /* check if all reasons are covered */
        if (reasonMask == allReasons) {
            detail = new RevocationDetailImpl(RevocationStatus.NOT_REVOKED);
        } else {
            logger.debug("Not all reasons were covered.");

            detail = new RevocationDetailImpl(RevocationStatus.UNKNOWN);
        }
    }

    return detail;
}

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

@Test
public void testAddEntryToEmptyCRL() throws Exception {
    Date oneHourAgo = new Date(new Date().getTime() - 60L * 60L * 1000L);
    Date oneHourHence = new Date(new Date().getTime() + 60L * 60L * 1000L);

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, oneHourAgo);
    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")));
    crlBuilder.setNextUpdate(oneHourHence);
    X509CRLHolder holder = crlBuilder.build(signer);

    File crlToChange = writeCRL(holder);

    File outfile = new File(folder.getRoot(), "new.crl");
    X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange, (RSAPrivateKey) keyPair.getPrivate(),
            (RSAPublicKey) keyPair.getPublic());

    // Add enough items to cause the number of length bytes to change
    Set<BigInteger> newSerials = new HashSet<BigInteger>(Arrays.asList(new BigInteger("2358215310"),
            new BigInteger("7231352433"), new BigInteger("8233181205"), new BigInteger("1455615868"),
            new BigInteger("4323487764"), new BigInteger("6673256679")));

    for (BigInteger i : newSerials) {
        stream.add(i, new Date(), CRLReason.privilegeWithdrawn);
    }/*w ww. j ava  2  s.com*/

    stream.preScan(crlToChange).lock();
    OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile));
    stream.write(o);
    o.close();

    X509CRL changedCrl = readCRL();

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

    for (X509CRLEntry entry : changedCrl.getRevokedCertificates()) {
        discoveredSerials.add(entry.getSerialNumber());
    }

    X509CRL originalCrl = new JcaX509CRLConverter().setProvider(BC).getCRL(holder);

    assertNotNull(changedCrl.getNextUpdate());

    long changedCrlUpdateDelta = changedCrl.getNextUpdate().getTime() - changedCrl.getThisUpdate().getTime();

    // We're allowing a tolerance of a few milliseconds to deal with minor timing issues
    long deltaTolerance = 3;
    long deltaDiff = changedCrlUpdateDelta - (oneHourHence.getTime() - oneHourAgo.getTime());

    assertTrue(Math.abs(deltaDiff) <= deltaTolerance);
    assertThat(changedCrl.getThisUpdate(), greaterThan(originalCrl.getThisUpdate()));

    assertEquals(newSerials, discoveredSerials);
    assertEquals(originalCrl.getIssuerX500Principal(), changedCrl.getIssuerX500Principal());

    ASN1ObjectIdentifier crlNumberOID = X509Extension.cRLNumber;
    byte[] oldCrlNumberBytes = originalCrl.getExtensionValue(crlNumberOID.getId());
    byte[] newCrlNumberBytes = changedCrl.getExtensionValue(crlNumberOID.getId());

    DEROctetString oldOctet = (DEROctetString) DERTaggedObject.fromByteArray(oldCrlNumberBytes);
    DEROctetString newOctet = (DEROctetString) DERTaggedObject.fromByteArray(newCrlNumberBytes);
    DERInteger oldNumber = (DERInteger) DERTaggedObject.fromByteArray(oldOctet.getOctets());
    DERInteger newNumber = (DERInteger) DERTaggedObject.fromByteArray(newOctet.getOctets());
    assertEquals(oldNumber.getValue().add(BigInteger.ONE), newNumber.getValue());

    ASN1ObjectIdentifier authorityKeyOID = X509Extension.authorityKeyIdentifier;
    byte[] oldAuthorityKeyId = originalCrl.getExtensionValue(authorityKeyOID.getId());
    byte[] newAuthorityKeyId = changedCrl.getExtensionValue(authorityKeyOID.getId());
    assertArrayEquals(oldAuthorityKeyId, newAuthorityKeyId);
}

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

@Test
public void testModifyNextUpdateTime() throws Exception {
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, 1);/*  w w  w.j a  va2 s .  c  o m*/
    Date nextUpdate = c.getTime();

    X509v2CRLBuilder crlBuilder = createCRLBuilder();
    crlBuilder.setNextUpdate(nextUpdate);
    X509CRLHolder holder = crlBuilder.build(signer);

    File crlToChange = writeCRL(holder);

    Thread.sleep(1000);

    X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange, (RSAPrivateKey) keyPair.getPrivate(),
            (RSAPublicKey) keyPair.getPublic());
    stream.preScan(crlToChange).lock();
    OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile));
    stream.write(o);
    o.close();

    X509CRL changedCrl = readCRL();
    X509CRL originalCrl = new JcaX509CRLConverter().setProvider(BC).getCRL(holder);

    assertTrue("Error: CRL nextUpdate field unmodified",
            originalCrl.getNextUpdate().before(changedCrl.getNextUpdate()));
}