Example usage for org.bouncycastle.cert X509CRLHolder toASN1Structure

List of usage examples for org.bouncycastle.cert X509CRLHolder toASN1Structure

Introduction

In this page you can find the example usage for org.bouncycastle.cert X509CRLHolder toASN1Structure.

Prototype

public CertificateList toASN1Structure() 

Source Link

Document

Return the underlying ASN.1 structure for the CRL in this holder.

Usage

From source file:com.aqnote.shared.cryptology.cert.main.AQCRLMain.java

License:Open Source License

public static void createCRL() throws CertException {

    try {/*www  .  ja  va  2  s . c  om*/
        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(X500NameUtil.createRootCaPrincipal(), new Date());
        crlBuilder.setNextUpdate(new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR));
        X509CRLHolder crlHolder = crlBuilder.build(new JcaContentSignerBuilder(SHA256_RSA)
                .setProvider(JCE_PROVIDER).build(CaCertLoader.getRootCaKeyPair(USER_CERT_PASSWD).getPrivate()));
        X509CRL crl = new JcaX509CRLConverter().setProvider(JCE_PROVIDER).getCRL(crlHolder);
        FileOutputStream fostream = new FileOutputStream(CRL_FILE);
        PKCSWriter.storeCRLFile(crl, fostream);

        ASN1Dump.dumpAsString(crlHolder.toASN1Structure());
    } catch (OperatorCreationException e) {
        throw new CertException(e);
    } catch (IOException e) {
        throw new CertException(e);
    } catch (InvalidKeyException e) {
        throw new CertException(e);
    } catch (CRLException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    } catch (NoSuchProviderException e) {
        throw new CertException(e);
    } catch (SignatureException e) {
        throw new CertException(e);
    } catch (Exception e) {
        throw new CertException(e);
    }

    return;
}

From source file:com.aqnote.shared.encrypt.cert.main.bc.AQCRLCreator.java

License:Open Source License

public static void createNewCRL() throws CertException {

    try {/*from ww  w  .  j  a  v  a2  s  .  com*/
        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(X500NameUtil.createRootPrincipal(), new Date());
        crlBuilder.setNextUpdate(new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR));
        X509CRLHolder crlHolder = crlBuilder.build(new JcaContentSignerBuilder(SHA256_RSA)
                .setProvider(JCE_PROVIDER).build(CaCertLoader.getCaKeyPair().getPrivate()));
        X509CRL crl = new JcaX509CRLConverter().setProvider(JCE_PROVIDER).getCRL(crlHolder);
        FileOutputStream fostream = new FileOutputStream(MAD_CRL_FILE);
        PKCSWriter.storeCRLFile(crl, fostream);

        ASN1Dump.dumpAsString(crlHolder.toASN1Structure());
    } catch (OperatorCreationException e) {
        throw new CertException(e);
    } catch (IOException e) {
        throw new CertException(e);
    } catch (InvalidKeyException e) {
        throw new CertException(e);
    } catch (CRLException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    } catch (NoSuchProviderException e) {
        throw new CertException(e);
    } catch (SignatureException e) {
        throw new CertException(e);
    } catch (Exception e) {
        throw new CertException(e);
    }

    return;
}

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

License:Open Source License

protected void writeToEmptyCrl(OutputStream out) throws IOException {
    ASN1InputStream asn1in = null;
    try {/*from ww w . ja va2s  .c  om*/
        asn1in = new ASN1InputStream(crlIn);
        DERSequence certListSeq = (DERSequence) asn1in.readObject();
        CertificateList certList = new CertificateList(certListSeq);
        X509CRLHolder oldCrl = new X509CRLHolder(certList);

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

        Date now = new Date();
        Date oldNextUpdate = certList.getNextUpdate().getDate();
        Date oldThisUpdate = certList.getThisUpdate().getDate();

        Date nextUpdate = new Date(now.getTime() + (oldNextUpdate.getTime() - oldThisUpdate.getTime()));
        crlBuilder.setNextUpdate(nextUpdate);

        for (Object o : oldCrl.getExtensionOIDs()) {
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) o;
            X509Extension ext = oldCrl.getExtension(oid);

            if (oid.equals(X509Extension.cRLNumber)) {
                DEROctetString octet = (DEROctetString) ext.getValue().getDERObject();
                DERInteger currentNumber = (DERInteger) DERTaggedObject.fromByteArray(octet.getOctets());
                DERInteger nextNumber = new DERInteger(currentNumber.getValue().add(BigInteger.ONE));

                crlBuilder.addExtension(oid, ext.isCritical(), nextNumber);
            } else if (oid.equals(X509Extension.authorityKeyIdentifier)) {
                crlBuilder.addExtension(oid, ext.isCritical(),
                        new AuthorityKeyIdentifierStructure(ext.getValue().getDEREncoded()));
            }
        }

        for (DERSequence entry : newEntries) {
            // XXX: This is all a bit messy considering the user already passed in the serial, date
            // and reason.
            BigInteger serial = ((DERInteger) entry.getObjectAt(0)).getValue();
            Date revokeDate = ((Time) entry.getObjectAt(1)).getDate();
            int reason = CRLReason.unspecified;
            if (entry.size() == 3) {
                X509Extensions extensions = (X509Extensions) entry.getObjectAt(2);
                X509Extension reasonExt = extensions.getExtension(X509Extension.reasonCode);

                if (reasonExt != null) {
                    reason = ((DEREnumerated) reasonExt.getParsedValue()).getValue().intValue();
                }
            }
            crlBuilder.addCRLEntry(serial, revokeDate, reason);
        }

        RSAKeyParameters keyParams = new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent());

        signingAlg = oldCrl.toASN1Structure().getSignatureAlgorithm();
        digestAlg = new DefaultDigestAlgorithmIdentifierFinder().find(signingAlg);

        ContentSigner s;
        try {
            s = new BcRSAContentSignerBuilder(signingAlg, digestAlg).build(keyParams);
            X509CRLHolder newCrl = crlBuilder.build(s);
            out.write(newCrl.getEncoded());
        } catch (OperatorCreationException e) {
            throw new IOException("Could not sign CRL", e);
        }
    } finally {
        IOUtils.closeQuietly(asn1in);
    }
}

From source file:org.cesecore.certificates.crl.CrlCreateSessionBean.java

License:Open Source License

@Override
public byte[] generateAndStoreCRL(AuthenticationToken admin, CA ca, Collection<RevokedCertInfo> certs,
        int basecrlnumber, int nextCrlNumber) throws CryptoTokenOfflineException, AuthorizationDeniedException {
    if (log.isTraceEnabled()) {
        log.trace(">createCRL(Collection)");
    }/*from ww w . j a  v  a 2 s  .c  o  m*/
    byte[] crlBytes = null; // return value

    // Check that we are allowed to create CRLs
    // Authorization for other things, that we have access to the CA has already been done
    final int caid = ca.getCAId();
    authorizedToCreateCRL(admin, caid);

    try {
        if ((ca.getStatus() != CAConstants.CA_ACTIVE)
                && (ca.getStatus() != CAConstants.CA_WAITING_CERTIFICATE_RESPONSE)) {
            String msg = intres.getLocalizedMessage("createcert.canotactive", ca.getSubjectDN());
            throw new CryptoTokenOfflineException(msg);
        }
        final X509CRLHolder crl;

        boolean deltaCRL = (basecrlnumber > -1);
        final CryptoToken cryptoToken = cryptoTokenManagementSession
                .getCryptoToken(ca.getCAToken().getCryptoTokenId());
        if (cryptoToken == null) {
            throw new CryptoTokenOfflineException(
                    "Could not find CryptoToken with id " + ca.getCAToken().getCryptoTokenId());
        }
        if (deltaCRL) {
            // Workaround if transaction handling fails so that crlNumber for deltaCRL would happen to be the same
            if (nextCrlNumber == basecrlnumber) {
                nextCrlNumber++;
            }
            crl = ca.generateDeltaCRL(cryptoToken, certs, nextCrlNumber, basecrlnumber);
        } else {
            crl = ca.generateCRL(cryptoToken, certs, nextCrlNumber);
        }
        if (crl != null) {
            // Store CRL in the database, this can still fail so the whole thing is rolled back
            String cafp = CertTools.getFingerprintAsString(ca.getCACertificate());
            if (log.isDebugEnabled()) {
                log.debug("Encoding CRL to byte array. Free memory=" + Runtime.getRuntime().freeMemory());
            }
            byte[] tmpcrlBytes = crl.getEncoded();
            if (log.isDebugEnabled()) {
                log.debug("Finished encoding CRL to byte array. Free memory="
                        + Runtime.getRuntime().freeMemory());
                log.debug("Storing CRL in certificate store.");
            }
            crlSession.storeCRL(admin, tmpcrlBytes, cafp, nextCrlNumber, crl.getIssuer().toString(),
                    crl.toASN1Structure().getThisUpdate().getDate(),
                    crl.toASN1Structure().getNextUpdate().getDate(), (deltaCRL ? 1 : -1));
            String msg = intres.getLocalizedMessage("createcrl.createdcrl", Integer.valueOf(nextCrlNumber),
                    ca.getName(), ca.getSubjectDN());
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            logSession.log(EventTypes.CRL_CREATION, EventStatus.SUCCESS, ModuleTypes.CRL, ServiceTypes.CORE,
                    admin.toString(), String.valueOf(caid), null, null, details);
            // Now all is finished and audit logged, now we are ready to "really" set the return value
            crlBytes = tmpcrlBytes;
        }
    } catch (CryptoTokenOfflineException ctoe) {
        String msg = intres.getLocalizedMessage("error.catokenoffline", ca.getSubjectDN());
        log.info(msg, ctoe);
        String auditmsg = intres.getLocalizedMessage("createcrl.errorcreate", ca.getName(), ctoe.getMessage());
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", auditmsg);
        logSession.log(EventTypes.CRL_CREATION, EventStatus.FAILURE, ModuleTypes.CRL, ServiceTypes.CORE,
                admin.toString(), String.valueOf(caid), null, null, details);
        throw ctoe;
    } catch (Exception e) {
        log.info("Error generating CRL: ", e);
        String msg = intres.getLocalizedMessage("createcrl.errorcreate", ca.getName(), e.getMessage());
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        logSession.log(EventTypes.CRL_CREATION, EventStatus.FAILURE, ModuleTypes.CRL, ServiceTypes.CORE,
                admin.toString(), String.valueOf(caid), null, null, details);
        if (e instanceof EJBException) {
            throw (EJBException) e;
        }
        throw new EJBException(msg, e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<createCRL(Collection)");
    }
    return crlBytes;
}

From source file:org.hyperledger.fabric_ca.sdkintegration.HFCAClientIT.java

License:Apache License

TBSCertList.CRLEntry[] parseCRL(String crl) throws Exception {

    Base64.Decoder b64dec = Base64.getDecoder();
    final byte[] decode = b64dec.decode(crl.getBytes(UTF_8));

    PEMParser pem = new PEMParser(new StringReader(new String(decode)));
    X509CRLHolder holder = (X509CRLHolder) pem.readObject();

    return holder.toASN1Structure().getRevokedCertificates();
}

From source file:org.xipki.ca.server.impl.X509CA.java

License:Open Source License

private X509CRL generateCRL(final boolean deltaCRL, final Date thisUpdate, final Date nextUpdate,
        final AuditEvent auditEvent) throws OperationException {
    X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
    if (crlSigner == null) {
        throw new OperationException(ErrorCode.INSUFFICIENT_PERMISSION, "CRL generation is not allowed");
    }//from  w w  w.ja v a  2  s.c  o  m

    LOG.info("     START generateCRL: ca={}, deltaCRL={}, nextUpdate={}",
            new Object[] { caInfo.getName(), deltaCRL, nextUpdate });

    if (auditEvent != null) {
        auditEvent.addEventData(new AuditEventData("crlType", deltaCRL ? "DELTA_CRL" : "FULL_CRL"));
        if (nextUpdate != null) {
            String value;
            synchronized (dateFormat) {
                value = dateFormat.format(nextUpdate);
            }
            auditEvent.addEventData(new AuditEventData("nextUpdate", value));
        } else {
            auditEvent.addEventData(new AuditEventData("nextUpdate", "NULL"));
        }
    }

    if (nextUpdate != null) {
        if (nextUpdate.getTime() - thisUpdate.getTime() < 10 * 60 * MS_PER_SECOND) {
            // less than 10 minutes
            throw new OperationException(ErrorCode.CRL_FAILURE, "nextUpdate and thisUpdate are too close");
        }
    }

    CRLControl crlControl = crlSigner.getCRLControl();
    boolean successfull = false;

    try {
        ConcurrentContentSigner _crlSigner = crlSigner.getSigner();

        CRLControl control = crlSigner.getCRLControl();

        boolean directCRL = _crlSigner == null;
        X500Name crlIssuer = directCRL ? caInfo.getPublicCAInfo().getX500Subject()
                : X500Name.getInstance(_crlSigner.getCertificate().getSubjectX500Principal().getEncoded());

        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(crlIssuer, thisUpdate);
        if (nextUpdate != null) {
            crlBuilder.setNextUpdate(nextUpdate);
        }

        BigInteger startSerial = BigInteger.ONE;
        final int numEntries = 100;

        X509CertWithDBCertId caCert = caInfo.getCertificate();
        List<CertRevInfoWithSerial> revInfos;
        boolean isFirstCRLEntry = true;

        Date notExpireAt;
        if (control.isIncludeExpiredCerts()) {
            notExpireAt = new Date(0);
        } else {
            // 10 minutes buffer
            notExpireAt = new Date(thisUpdate.getTime() - 600L * MS_PER_SECOND);
        }

        do {
            if (deltaCRL) {
                revInfos = certstore.getCertificatesForDeltaCRL(caCert, startSerial, numEntries,
                        control.isOnlyContainsCACerts(), control.isOnlyContainsUserCerts());
            } else {
                revInfos = certstore.getRevokedCertificates(caCert, notExpireAt, startSerial, numEntries,
                        control.isOnlyContainsCACerts(), control.isOnlyContainsUserCerts());
            }

            BigInteger maxSerial = BigInteger.ONE;

            for (CertRevInfoWithSerial revInfo : revInfos) {
                BigInteger serial = revInfo.getSerial();
                if (serial.compareTo(maxSerial) > 0) {
                    maxSerial = serial;
                }

                CRLReason reason = revInfo.getReason();
                Date revocationTime = revInfo.getRevocationTime();
                Date invalidityTime = revInfo.getInvalidityTime();
                if (invalidityTime != null && invalidityTime.equals(revocationTime)) {
                    invalidityTime = null;
                }

                if (directCRL || isFirstCRLEntry == false) {
                    if (invalidityTime != null) {
                        crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, reason.getCode(),
                                invalidityTime);
                    } else {
                        crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, reason.getCode());
                    }
                    continue;
                }

                List<Extension> extensions = new ArrayList<>(3);
                if (reason != CRLReason.UNSPECIFIED) {
                    Extension ext = createReasonExtension(reason.getCode());
                    extensions.add(ext);
                }
                if (invalidityTime != null) {
                    Extension ext = createInvalidityDateExtension(invalidityTime);
                    extensions.add(ext);
                }

                Extension ext = createCertificateIssuerExtension(caInfo.getPublicCAInfo().getX500Subject());
                extensions.add(ext);

                Extensions asn1Extensions = new Extensions(extensions.toArray(new Extension[0]));
                crlBuilder.addCRLEntry(revInfo.getSerial(), revocationTime, asn1Extensions);
                isFirstCRLEntry = false;
            } // end for

            startSerial = maxSerial.add(BigInteger.ONE);

        } while (revInfos.size() >= numEntries);
        // end do

        BigInteger crlNumber = caInfo.nextCRLNumber();
        if (auditEvent != null) {
            auditEvent.addEventData(new AuditEventData("crlNumber", crlNumber.toString()));
        }

        boolean onlyUserCerts = crlControl.isOnlyContainsUserCerts();
        boolean onlyCACerts = crlControl.isOnlyContainsCACerts();
        if (onlyUserCerts && onlyCACerts) {
            throw new RuntimeException("should not reach here, onlyUserCerts and onlyCACerts are both true");
        }

        try {
            // AuthorityKeyIdentifier
            byte[] akiValues = directCRL ? caInfo.getPublicCAInfo().getSubjectKeyIdentifer()
                    : crlSigner.getSubjectKeyIdentifier();
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(akiValues);
            crlBuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);

            // add extension CRL Number
            crlBuilder.addExtension(Extension.cRLNumber, false, new ASN1Integer(crlNumber));

            // IssuingDistributionPoint
            if (onlyUserCerts == true || onlyCACerts == true || directCRL == false) {
                IssuingDistributionPoint idp = new IssuingDistributionPoint((DistributionPointName) null, // distributionPoint,
                        onlyUserCerts, // onlyContainsUserCerts,
                        onlyCACerts, // onlyContainsCACerts,
                        (ReasonFlags) null, // onlySomeReasons,
                        directCRL == false, // indirectCRL,
                        false // onlyContainsAttributeCerts
                );

                crlBuilder.addExtension(Extension.issuingDistributionPoint, true, idp);
            }
        } catch (CertIOException e) {
            final String message = "crlBuilder.addExtension";
            if (LOG.isErrorEnabled()) {
                LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
            }
            LOG.debug(message, e);
            throw new OperationException(ErrorCode.INVALID_EXTENSION, e.getMessage());
        }

        startSerial = BigInteger.ONE;
        if (deltaCRL == false && control.isEmbedsCerts()) // XiPKI extension
        {
            ASN1EncodableVector vector = new ASN1EncodableVector();

            List<BigInteger> serials;

            do {
                serials = certstore.getCertSerials(caCert, notExpireAt, startSerial, numEntries, false,
                        onlyCACerts, onlyUserCerts);

                BigInteger maxSerial = BigInteger.ONE;
                for (BigInteger serial : serials) {
                    if (serial.compareTo(maxSerial) > 0) {
                        maxSerial = serial;
                    }

                    X509CertificateInfo certInfo;
                    try {
                        certInfo = certstore.getCertificateInfoForSerial(caCert, serial);
                    } catch (CertificateException e) {
                        throw new OperationException(ErrorCode.SYSTEM_FAILURE,
                                "CertificateException: " + e.getMessage());
                    }

                    Certificate cert = Certificate.getInstance(certInfo.getCert().getEncodedCert());

                    ASN1EncodableVector v = new ASN1EncodableVector();
                    v.add(cert);
                    String profileName = certInfo.getProfileName();
                    if (StringUtil.isNotBlank(profileName)) {
                        v.add(new DERUTF8String(certInfo.getProfileName()));
                    }
                    ASN1Sequence certWithInfo = new DERSequence(v);

                    vector.add(certWithInfo);
                } // end for

                startSerial = maxSerial.add(BigInteger.ONE);
            } while (serials.size() >= numEntries);
            // end fo

            try {
                crlBuilder.addExtension(ObjectIdentifiers.id_xipki_ext_crlCertset, false, new DERSet(vector));
            } catch (CertIOException e) {
                throw new OperationException(ErrorCode.INVALID_EXTENSION, "CertIOException: " + e.getMessage());
            }
        }

        ConcurrentContentSigner concurrentSigner = (_crlSigner == null) ? caInfo.getSigner(null) : _crlSigner;

        ContentSigner contentSigner;
        try {
            contentSigner = concurrentSigner.borrowContentSigner();
        } catch (NoIdleSignerException e) {
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, "NoIdleSignerException: " + e.getMessage());
        }

        X509CRLHolder crlHolder;
        try {
            crlHolder = crlBuilder.build(contentSigner);
        } finally {
            concurrentSigner.returnContentSigner(contentSigner);
        }

        try {
            X509CRL crl = new X509CRLObject(crlHolder.toASN1Structure());
            publishCRL(crl);

            successfull = true;
            LOG.info("SUCCESSFUL generateCRL: ca={}, crlNumber={}, thisUpdate={}",
                    new Object[] { caInfo.getName(), crlNumber, crl.getThisUpdate() });

            if (deltaCRL) {
                return crl;
            }

            // clean up the CRL
            try {
                cleanupCRLs();
            } catch (Throwable t) {
                LOG.warn("could not cleanup CRLs.{}: {}", t.getClass().getName(), t.getMessage());
            }
            return crl;
        } catch (CRLException e) {
            throw new OperationException(ErrorCode.CRL_FAILURE, "CRLException: " + e.getMessage());
        }
    } finally {
        if (successfull == false) {
            LOG.info("    FAILED generateCRL: ca={}", caInfo.getName());
        }
    }
}

From source file:org.xipki.pki.ca.server.impl.X509Ca.java

License:Open Source License

private X509CRL doGenerateCrl(final boolean deltaCrl, final Date thisUpdate, final Date nextUpdate,
        final AuditEvent event, final String msgId) throws OperationException {
    X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
    if (crlSigner == null) {
        throw new OperationException(ErrorCode.NOT_PERMITTED, "CRL generation is not allowed");
    }/*from  ww  w .  j  a va2  s.  co m*/

    String caName = caInfo.getName();
    LOG.info("     START generateCrl: ca={}, deltaCRL={}, nextUpdate={}", caName, deltaCrl, nextUpdate);
    event.addEventData(CaAuditConstants.NAME_crlType, deltaCrl ? "DELTA_CRL" : "FULL_CRL");

    if (nextUpdate == null) {
        event.addEventData(CaAuditConstants.NAME_nextUpdate, "null");
    } else {
        event.addEventData(CaAuditConstants.NAME_nextUpdate, DateUtil.toUtcTimeyyyyMMddhhmmss(nextUpdate));
        if (nextUpdate.getTime() - thisUpdate.getTime() < 10 * 60 * MS_PER_SECOND) {
            // less than 10 minutes
            throw new OperationException(ErrorCode.CRL_FAILURE, "nextUpdate and thisUpdate are too close");
        }
    }

    CrlControl crlControl = crlSigner.getCrlControl();
    boolean successful = false;

    try {
        ConcurrentContentSigner tmpCrlSigner = crlSigner.getSigner();
        CrlControl control = crlSigner.getCrlControl();

        boolean directCrl;
        X500Name crlIssuer;
        if (tmpCrlSigner == null) {
            directCrl = true;
            crlIssuer = caInfo.getPublicCaInfo().getX500Subject();
        } else {
            directCrl = false;
            crlIssuer = X500Name
                    .getInstance(tmpCrlSigner.getCertificate().getSubjectX500Principal().getEncoded());
        }

        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(crlIssuer, thisUpdate);
        if (nextUpdate != null) {
            crlBuilder.setNextUpdate(nextUpdate);
        }

        final int numEntries = 100;

        X509Cert caCert = caInfo.getCertificate();
        List<CertRevInfoWithSerial> revInfos;
        boolean isFirstCrlEntry = true;

        Date notExpireAt;
        if (control.isIncludeExpiredCerts()) {
            notExpireAt = new Date(0);
        } else {
            // 10 minutes buffer
            notExpireAt = new Date(thisUpdate.getTime() - 600L * MS_PER_SECOND);
        }

        long startId = 1;
        do {
            if (deltaCrl) {
                revInfos = certstore.getCertsForDeltaCrl(caCert, startId, numEntries,
                        control.isOnlyContainsCaCerts(), control.isOnlyContainsUserCerts());
            } else {
                revInfos = certstore.getRevokedCerts(caCert, notExpireAt, startId, numEntries,
                        control.isOnlyContainsCaCerts(), control.isOnlyContainsUserCerts());
            }

            long maxId = 1;

            for (CertRevInfoWithSerial revInfo : revInfos) {
                if (revInfo.getId() > maxId) {
                    maxId = revInfo.getId();
                }

                CrlReason reason = revInfo.getReason();
                if (crlControl.isExcludeReason() && reason != CrlReason.REMOVE_FROM_CRL) {
                    reason = CrlReason.UNSPECIFIED;
                }

                Date revocationTime = revInfo.getRevocationTime();
                Date invalidityTime = revInfo.getInvalidityTime();

                switch (crlControl.getInvalidityDateMode()) {
                case FORBIDDEN:
                    invalidityTime = null;
                    break;
                case OPTIONAL:
                    break;
                case REQUIRED:
                    if (invalidityTime == null) {
                        invalidityTime = revocationTime;
                    }
                    break;
                default:
                    throw new RuntimeException("unknown TripleState: " + crlControl.getInvalidityDateMode());
                }

                BigInteger serial = revInfo.getSerial();
                LOG.debug("added cert ca={} serial={} to CRL", caName, serial);

                if (directCrl || !isFirstCrlEntry) {
                    if (invalidityTime != null) {
                        crlBuilder.addCRLEntry(serial, revocationTime, reason.getCode(), invalidityTime);
                    } else {
                        crlBuilder.addCRLEntry(serial, revocationTime, reason.getCode());
                    }
                    continue;
                }

                List<Extension> extensions = new ArrayList<>(3);
                if (reason != CrlReason.UNSPECIFIED) {
                    Extension ext = createReasonExtension(reason.getCode());
                    extensions.add(ext);
                }
                if (invalidityTime != null) {
                    Extension ext = createInvalidityDateExtension(invalidityTime);
                    extensions.add(ext);
                }

                Extension ext = createCertificateIssuerExtension(caInfo.getPublicCaInfo().getX500Subject());
                extensions.add(ext);

                crlBuilder.addCRLEntry(serial, revocationTime,
                        new Extensions(extensions.toArray(new Extension[0])));
                isFirstCrlEntry = false;
            } // end for

            startId = maxId + 1;

        } while (revInfos.size() >= numEntries);
        // end do

        BigInteger crlNumber = caInfo.nextCrlNumber();
        event.addEventData(CaAuditConstants.NAME_crlNumber, crlNumber);

        boolean onlyUserCerts = crlControl.isOnlyContainsUserCerts();
        boolean onlyCaCerts = crlControl.isOnlyContainsCaCerts();
        if (onlyUserCerts && onlyCaCerts) {
            throw new RuntimeException("should not reach here, onlyUserCerts and onlyCACerts are both true");
        }

        try {
            // AuthorityKeyIdentifier
            byte[] akiValues = directCrl ? caInfo.getPublicCaInfo().getSubjectKeyIdentifer()
                    : crlSigner.getSubjectKeyIdentifier();
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(akiValues);
            crlBuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);

            // add extension CRL Number
            crlBuilder.addExtension(Extension.cRLNumber, false, new ASN1Integer(crlNumber));

            // IssuingDistributionPoint
            if (onlyUserCerts || onlyCaCerts || !directCrl) {
                IssuingDistributionPoint idp = new IssuingDistributionPoint((DistributionPointName) null, // distributionPoint,
                        onlyUserCerts, // onlyContainsUserCerts,
                        onlyCaCerts, // onlyContainsCACerts,
                        (ReasonFlags) null, // onlySomeReasons,
                        !directCrl, // indirectCRL,
                        false); // onlyContainsAttributeCerts

                crlBuilder.addExtension(Extension.issuingDistributionPoint, true, idp);
            }

            // freshestCRL
            List<String> deltaCrlUris = getCaInfo().getPublicCaInfo().getDeltaCrlUris();
            if (control.getDeltaCrlIntervals() > 0 && CollectionUtil.isNonEmpty(deltaCrlUris)) {
                CRLDistPoint cdp = CaUtil.createCrlDistributionPoints(deltaCrlUris,
                        caInfo.getPublicCaInfo().getX500Subject(), crlIssuer);
                crlBuilder.addExtension(Extension.freshestCRL, false, cdp);
            }
        } catch (CertIOException ex) {
            LogUtil.error(LOG, ex, "crlBuilder.addExtension");
            throw new OperationException(ErrorCode.INVALID_EXTENSION, ex);
        }

        addXipkiCertset(crlBuilder, deltaCrl, control, caCert, notExpireAt, onlyCaCerts, onlyUserCerts);

        ConcurrentContentSigner concurrentSigner = (tmpCrlSigner == null) ? caInfo.getSigner(null)
                : tmpCrlSigner;

        X509CRLHolder crlHolder;
        try {
            crlHolder = concurrentSigner.build(crlBuilder);
        } catch (NoIdleSignerException ex) {
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, "NoIdleSignerException: " + ex.getMessage());
        }

        try {
            X509CRL crl = X509Util.toX509Crl(crlHolder.toASN1Structure());
            caInfo.getCaEntry().setNextCrlNumber(crlNumber.longValue() + 1);
            caInfo.commitNextCrlNo();
            publishCrl(crl);

            successful = true;
            LOG.info("SUCCESSFUL generateCrl: ca={}, crlNumber={}, thisUpdate={}", caName, crlNumber,
                    crl.getThisUpdate());

            if (!deltaCrl) {
                // clean up the CRL
                cleanupCrlsWithoutException(msgId);
            }
            return crl;
        } catch (CRLException | CertificateException ex) {
            throw new OperationException(ErrorCode.CRL_FAILURE, ex);
        }
    } finally {
        if (!successful) {
            LOG.info("    FAILED generateCrl: ca={}", caName);
        }
    }
}

From source file:org.xipki.pki.scep.serveremulator.CaEmulator.java

License:Open Source License

public synchronized CertificateList getCrl(final X500Name issuer, final BigInteger serialNumber)
        throws Exception {
    if (crl != null) {
        return crl;
    }//from  w  w  w  . j a v a  2  s .c o  m

    Date thisUpdate = new Date();
    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(caSubject, thisUpdate);
    Date nextUpdate = new Date(thisUpdate.getTime() + 30 * DAY_IN_MS);
    crlBuilder.setNextUpdate(nextUpdate);
    Date caStartTime = caCert.getTBSCertificate().getStartDate().getDate();
    Date revocationTime = new Date(caStartTime.getTime() + 1);
    if (revocationTime.after(thisUpdate)) {
        revocationTime = caStartTime;
    }
    crlBuilder.addCRLEntry(BigInteger.valueOf(2), revocationTime, CRLReason.keyCompromise);
    crlBuilder.addExtension(Extension.cRLNumber, false, new ASN1Integer(crlNumber.getAndAdd(1)));

    String signatureAlgorithm = ScepUtil.getSignatureAlgorithm(caKey, ScepHashAlgoType.SHA256);
    ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(caKey);
    X509CRLHolder crl = crlBuilder.build(contentSigner);
    return crl.toASN1Structure();
}