Example usage for org.bouncycastle.asn1.x509 Extension cRLNumber

List of usage examples for org.bouncycastle.asn1.x509 Extension cRLNumber

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Extension cRLNumber.

Prototype

ASN1ObjectIdentifier cRLNumber

To view the source code for org.bouncycastle.asn1.x509 Extension cRLNumber.

Click Source Link

Document

CRL Number

Usage

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

License:Open Source License

void addCrl(final X509Cert caCert, final X509CRL crl)
        throws DataAccessException, CRLException, OperationException {
    ParamUtil.requireNonNull("caCert", caCert);
    ParamUtil.requireNonNull("crl", crl);

    byte[] encodedExtnValue = crl.getExtensionValue(Extension.cRLNumber.getId());
    Long crlNumber = null;/*from   www  .java 2  s.com*/
    if (encodedExtnValue != null) {
        byte[] extnValue = DEROctetString.getInstance(encodedExtnValue).getOctets();
        crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue().longValue();
    }

    encodedExtnValue = crl.getExtensionValue(Extension.deltaCRLIndicator.getId());
    Long baseCrlNumber = null;
    if (encodedExtnValue != null) {
        byte[] extnValue = DEROctetString.getInstance(encodedExtnValue).getOctets();
        baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue().longValue();
    }

    final String sql = SQLs.SQL_ADD_CRL;
    long currentMaxCrlId = datasource.getMax(null, "CRL", "ID");
    long crlId = currentMaxCrlId + 1;

    String b64Crl = Base64.toBase64String(crl.getEncoded());

    PreparedStatement ps = null;

    try {
        int caId = getCaId(caCert);
        ps = borrowPreparedStatement(sql);

        int idx = 1;
        ps.setLong(idx++, crlId);
        ps.setInt(idx++, caId);
        setLong(ps, idx++, crlNumber);
        Date date = crl.getThisUpdate();
        ps.setLong(idx++, date.getTime() / 1000);
        setDateSeconds(ps, idx++, crl.getNextUpdate());
        setBoolean(ps, idx++, (baseCrlNumber != null));
        setLong(ps, idx++, baseCrlNumber);
        ps.setString(idx++, b64Crl);

        ps.executeUpdate();
    } catch (SQLException ex) {
        throw datasource.translate(sql, ex);
    } finally {
        releaseDbResources(ps, null);
    }
}

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   w  w w. ja  v  a  2 s.  com*/

    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.ocsp.server.impl.store.crl.CrlCertStatusStore.java

License:Open Source License

private synchronized void initializeStore(final boolean force) {
    Boolean updateCrlSuccessful = null;

    try {/*from  w w  w . ja v  a2 s.c  om*/
        File fullCrlFile = new File(crlFilename);
        if (!fullCrlFile.exists()) {
            // file does not exist
            LOG.warn("CRL File {} does not exist", crlFilename);
            return;
        }

        long newLastModifed = fullCrlFile.lastModified();

        long newLastModifedOfDeltaCrl;
        boolean deltaCrlExists;
        File deltaCrlFile = null;
        if (deltaCrlFilename != null) {
            deltaCrlFile = new File(deltaCrlFilename);
            deltaCrlExists = deltaCrlFile.exists();
            newLastModifedOfDeltaCrl = deltaCrlExists ? deltaCrlFile.lastModified() : 0;
        } else {
            deltaCrlExists = false;
            newLastModifedOfDeltaCrl = 0;
        }

        if (!force) {
            long now = System.currentTimeMillis();
            if (newLastModifed != lastmodifiedOfCrlFile && now - newLastModifed < 5000) {
                return; // still in copy process
            }

            if (deltaCrlExists) {
                if (newLastModifedOfDeltaCrl != lastModifiedOfDeltaCrlFile && now - newLastModifed < 5000) {
                    return; // still in copy process
                }
            }
        } // end if (force)

        byte[] newFp = sha1Fp(fullCrlFile);
        boolean crlFileChanged = !Arrays.equals(newFp, fpOfCrlFile);

        byte[] newFpOfDeltaCrl = deltaCrlExists ? sha1Fp(deltaCrlFile) : null;
        boolean deltaCrlFileChanged = !Arrays.equals(newFpOfDeltaCrl, fpOfDeltaCrlFile);

        if (!crlFileChanged && !deltaCrlFileChanged) {
            return;
        }

        if (crlFileChanged) {
            LOG.info("CRL file {} has changed, update of the CertStore required", crlFilename);
        }
        if (deltaCrlFileChanged) {
            LOG.info("DeltaCRL file {} has changed, update of the CertStore required", deltaCrlFilename);
        }

        auditPciEvent(AuditLevel.INFO, "UPDATE_CERTSTORE", "a newer CRL is available");
        updateCrlSuccessful = false;

        X509CRL crl = X509Util.parseCrl(crlFilename);

        byte[] octetString = crl.getExtensionValue(Extension.cRLNumber.getId());
        if (octetString == null) {
            throw new OcspStoreException("CRL without CRLNumber is not supported");
        }
        BigInteger newCrlNumber = ASN1Integer.getInstance(DEROctetString.getInstance(octetString).getOctets())
                .getPositiveValue();

        if (crlNumber != null && newCrlNumber.compareTo(crlNumber) <= 0) {
            throw new OcspStoreException(
                    String.format("CRLNumber of new CRL (%s) <= current CRL (%s)", newCrlNumber, crlNumber));
        }

        X500Principal issuer = crl.getIssuerX500Principal();

        boolean caAsCrlIssuer = true;
        if (!caCert.getSubjectX500Principal().equals(issuer)) {
            caAsCrlIssuer = false;
            if (issuerCert == null) {
                throw new IllegalArgumentException("issuerCert must not be null");
            }

            if (!issuerCert.getSubjectX500Principal().equals(issuer)) {
                throw new IllegalArgumentException("issuerCert and CRL do not match");
            }
        }

        X509Certificate crlSignerCert = caAsCrlIssuer ? caCert : issuerCert;
        try {
            crl.verify(crlSignerCert.getPublicKey());
        } catch (Exception ex) {
            throw new OcspStoreException(ex.getMessage(), ex);
        }

        X509CRL deltaCrl = null;
        BigInteger deltaCrlNumber = null;
        BigInteger baseCrlNumber = null;

        if (deltaCrlExists) {
            if (newCrlNumber == null) {
                throw new OcspStoreException("baseCRL does not contains CRLNumber");
            }

            deltaCrl = X509Util.parseCrl(deltaCrlFilename);
            octetString = deltaCrl.getExtensionValue(Extension.deltaCRLIndicator.getId());
            if (octetString == null) {
                deltaCrl = null;
                LOG.warn("{} is a full CRL instead of delta CRL, ignore it", deltaCrlFilename);
            } else {
                byte[] extnValue = DEROctetString.getInstance(octetString).getOctets();
                baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();
                if (!baseCrlNumber.equals(newCrlNumber)) {
                    deltaCrl = null;
                    LOG.info("{} is not a deltaCRL for the CRL {}, ignore it", deltaCrlFilename, crlFilename);
                } else {
                    octetString = deltaCrl.getExtensionValue(Extension.cRLNumber.getId());
                    extnValue = DEROctetString.getInstance(octetString).getOctets();
                    deltaCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();
                }
            } // end if(octetString == null)
        } // end if(deltaCrlExists)

        Date newThisUpdate;
        Date newNextUpdate;

        if (deltaCrl != null) {
            LOG.info("try to update CRL with CRLNumber={} and DeltaCRL with CRLNumber={}", newCrlNumber,
                    deltaCrlNumber);
            newThisUpdate = deltaCrl.getThisUpdate();
            newNextUpdate = deltaCrl.getNextUpdate();
        } else {
            newThisUpdate = crl.getThisUpdate();
            newNextUpdate = crl.getNextUpdate();
        }

        // Construct CrlID
        ASN1EncodableVector vec = new ASN1EncodableVector();
        if (StringUtil.isNotBlank(crlUrl)) {
            vec.add(new DERTaggedObject(true, 0, new DERIA5String(crlUrl, true)));
        }

        byte[] extValue = ((deltaCrl != null) ? deltaCrl : crl).getExtensionValue(Extension.cRLNumber.getId());
        if (extValue != null) {
            ASN1Integer asn1CrlNumber = ASN1Integer.getInstance(extractCoreValue(extValue));
            vec.add(new DERTaggedObject(true, 1, asn1CrlNumber));
        }
        vec.add(new DERTaggedObject(true, 2, new DERGeneralizedTime(newThisUpdate)));
        this.crlId = CrlID.getInstance(new DERSequence(vec));

        byte[] encodedCaCert;
        try {
            encodedCaCert = caCert.getEncoded();
        } catch (CertificateEncodingException ex) {
            throw new OcspStoreException(ex.getMessage(), ex);
        }

        Certificate bcCaCert = Certificate.getInstance(encodedCaCert);
        byte[] encodedName;
        try {
            encodedName = bcCaCert.getSubject().getEncoded("DER");
        } catch (IOException ex) {
            throw new OcspStoreException(ex.getMessage(), ex);
        }

        byte[] encodedKey = bcCaCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
        Map<HashAlgoType, IssuerHashNameAndKey> newIssuerHashMap = new ConcurrentHashMap<>();

        for (HashAlgoType hashAlgo : HashAlgoType.values()) {
            byte[] issuerNameHash = hashAlgo.hash(encodedName);
            byte[] issuerKeyHash = hashAlgo.hash(encodedKey);
            IssuerHashNameAndKey issuerHash = new IssuerHashNameAndKey(hashAlgo, issuerNameHash, issuerKeyHash);
            newIssuerHashMap.put(hashAlgo, issuerHash);
        }

        X500Name caName = X500Name.getInstance(caCert.getSubjectX500Principal().getEncoded());

        // extract the certificate, only in full CRL, not in delta CRL
        String oidExtnCerts = ObjectIdentifiers.id_xipki_ext_crlCertset.getId();
        byte[] extnValue = crl.getExtensionValue(oidExtnCerts);

        boolean certsConsidered = false;
        Map<BigInteger, CertWithInfo> certsMap;
        if (extnValue != null) {
            extnValue = extractCoreValue(extnValue);
            certsConsidered = true;
            certsMap = extractCertsFromExtCrlCertSet(extnValue, caName);
        } else {
            certsMap = new HashMap<>();
        }

        if (certsDirname != null) {
            if (extnValue != null) {
                LOG.warn("ignore certsDir '{}', since certificates are included in {}", certsDirname,
                        " CRL Extension certs");
            } else {
                certsConsidered = true;
                readCertWithInfosFromDir(caCert, certsDirname, certsMap);
            }
        }

        Map<BigInteger, CrlCertStatusInfo> newCertStatusInfoMap = new ConcurrentHashMap<>();

        // First consider only full CRL
        Set<? extends X509CRLEntry> revokedCertListInFullCrl = crl.getRevokedCertificates();
        if (revokedCertListInFullCrl != null) {
            for (X509CRLEntry revokedCert : revokedCertListInFullCrl) {
                X500Principal rcIssuer = revokedCert.getCertificateIssuer();
                if (rcIssuer != null && !caCert.getSubjectX500Principal().equals(rcIssuer)) {
                    throw new OcspStoreException("invalid CRLEntry");
                }
            }
        }

        Set<? extends X509CRLEntry> revokedCertListInDeltaCrl = (deltaCrl == null) ? null
                : deltaCrl.getRevokedCertificates();
        if (revokedCertListInDeltaCrl != null) {
            for (X509CRLEntry revokedCert : revokedCertListInDeltaCrl) {
                X500Principal rcIssuer = revokedCert.getCertificateIssuer();
                if (rcIssuer != null && !caCert.getSubjectX500Principal().equals(rcIssuer)) {
                    throw new OcspStoreException("invalid CRLEntry");
                }
            }
        }

        Map<BigInteger, X509CRLEntry> revokedCertMap = null;

        // merge the revoked list
        if (revokedCertListInDeltaCrl != null && !revokedCertListInDeltaCrl.isEmpty()) {
            revokedCertMap = new HashMap<BigInteger, X509CRLEntry>();
            if (revokedCertListInFullCrl != null) {
                for (X509CRLEntry entry : revokedCertListInFullCrl) {
                    revokedCertMap.put(entry.getSerialNumber(), entry);
                }
            }

            for (X509CRLEntry entry : revokedCertListInDeltaCrl) {
                BigInteger serialNumber = entry.getSerialNumber();
                CRLReason reason = entry.getRevocationReason();
                if (reason == CRLReason.REMOVE_FROM_CRL) {
                    revokedCertMap.remove(serialNumber);
                } else {
                    revokedCertMap.put(serialNumber, entry);
                }
            }
        }

        Iterator<? extends X509CRLEntry> it = null;
        if (revokedCertMap != null) {
            it = revokedCertMap.values().iterator();
        } else if (revokedCertListInFullCrl != null) {
            it = revokedCertListInFullCrl.iterator();
        }

        while (it != null && it.hasNext()) {
            X509CRLEntry revokedCert = it.next();
            BigInteger serialNumber = revokedCert.getSerialNumber();
            byte[] encodedExtnValue = revokedCert.getExtensionValue(Extension.reasonCode.getId());

            int reasonCode;
            if (encodedExtnValue != null) {
                ASN1Enumerated enumerated = ASN1Enumerated.getInstance(extractCoreValue(encodedExtnValue));
                reasonCode = enumerated.getValue().intValue();
            } else {
                reasonCode = CrlReason.UNSPECIFIED.getCode();
            }

            Date revTime = revokedCert.getRevocationDate();

            Date invalidityTime = null;
            extnValue = revokedCert.getExtensionValue(Extension.invalidityDate.getId());

            if (extnValue != null) {
                extnValue = extractCoreValue(extnValue);
                ASN1GeneralizedTime genTime = DERGeneralizedTime.getInstance(extnValue);
                try {
                    invalidityTime = genTime.getDate();
                } catch (ParseException ex) {
                    throw new OcspStoreException(ex.getMessage(), ex);
                }

                if (revTime.equals(invalidityTime)) {
                    invalidityTime = null;
                }
            }

            CertWithInfo cert = null;
            if (certsConsidered) {
                cert = certsMap.remove(serialNumber);
                if (cert == null && LOG.isInfoEnabled()) {
                    LOG.info("could not find certificate (serialNumber='{}')", LogUtil.formatCsn(serialNumber));
                }
            }

            Certificate bcCert = (cert == null) ? null : cert.getCert();
            Map<HashAlgoType, byte[]> certHashes = (bcCert == null) ? null : getCertHashes(bcCert);
            Date notBefore = (bcCert == null) ? null : bcCert.getTBSCertificate().getStartDate().getDate();
            Date notAfter = (bcCert == null) ? null : bcCert.getTBSCertificate().getEndDate().getDate();

            CertRevocationInfo revocationInfo = new CertRevocationInfo(reasonCode, revTime, invalidityTime);
            String profileName = (cert == null) ? null : cert.getProfileName();
            CrlCertStatusInfo crlCertStatusInfo = CrlCertStatusInfo.getRevokedCertStatusInfo(revocationInfo,
                    profileName, certHashes, notBefore, notAfter);
            newCertStatusInfoMap.put(serialNumber, crlCertStatusInfo);
        } // end while

        for (BigInteger serialNumber : certsMap.keySet()) {
            CertWithInfo cert = certsMap.get(serialNumber);

            Certificate bcCert = cert.getCert();
            Map<HashAlgoType, byte[]> certHashes = (bcCert == null) ? null : getCertHashes(bcCert);
            Date notBefore = (bcCert == null) ? null : bcCert.getTBSCertificate().getStartDate().getDate();
            Date notAfter = (bcCert == null) ? null : bcCert.getTBSCertificate().getEndDate().getDate();
            CrlCertStatusInfo crlCertStatusInfo = CrlCertStatusInfo.getGoodCertStatusInfo(cert.getProfileName(),
                    certHashes, notBefore, notAfter);
            newCertStatusInfoMap.put(cert.getSerialNumber(), crlCertStatusInfo);
        }

        this.initialized = false;
        this.lastmodifiedOfCrlFile = newLastModifed;
        this.fpOfCrlFile = newFp;

        this.lastModifiedOfDeltaCrlFile = newLastModifedOfDeltaCrl;
        this.fpOfDeltaCrlFile = newFpOfDeltaCrl;

        this.issuerHashMap.clear();
        this.issuerHashMap.putAll(newIssuerHashMap);
        this.certStatusInfoMap.clear();
        this.certStatusInfoMap.putAll(newCertStatusInfoMap);
        this.thisUpdate = newThisUpdate;
        this.nextUpdate = newNextUpdate;
        this.crlNumber = newCrlNumber;

        this.initializationFailed = false;
        this.initialized = true;
        updateCrlSuccessful = true;
        LOG.info("updated CertStore {}", name);
    } catch (Exception ex) {
        LogUtil.error(LOG, ex, "could not execute initializeStore()");
        initializationFailed = true;
        initialized = true;
    } finally {
        if (updateCrlSuccessful != null) {
            AuditLevel auditLevel = updateCrlSuccessful ? AuditLevel.INFO : AuditLevel.ERROR;
            AuditStatus auditStatus = updateCrlSuccessful ? AuditStatus.SUCCESSFUL : AuditStatus.FAILED;
            auditPciEvent(auditLevel, "UPDATE_CRL", auditStatus.name());
        }
    }
}

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;
    }/*  w ww . jav  a2 s.  c  om*/

    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();
}

From source file:se.tillvaxtverket.tsltrust.webservice.daemon.ca.CertificationAuthority.java

License:Open Source License

public X509CRLHolder revokeCertificates() {
    long currentTime = System.currentTimeMillis();
    long nextUpdateTime = currentTime + crlValPeriod;
    List<DbCert> certList = CaSQLiteUtil.getCertificates(caDir, true);

    DbCAParam cp = CaSQLiteUtil.getParameter(caDir, CRL_SERIAL_KEY);
    if (cp == null) {
        return null;
    }/* w w w  . j  a  va2 s . c  om*/
    long nextCrlSerial = cp.getIntValue();

    try {

        AaaCRL crl = new AaaCRL(new Date(currentTime), new Date(nextUpdateTime), caRoot,
                (PrivateKey) key_store.getKey(ROOT, KS_PASSWORD), CertFactory.SHA256WITHRSA, crlFile);

        List<Extension> extList = new ArrayList<Extension>();
        // Add AKI
        X509ExtensionUtils extu = CertUtils.getX509ExtensionUtils();
        AuthorityKeyIdentifier aki = extu.createAuthorityKeyIdentifier(caRoot);
        extList.add(new Extension(Extension.authorityKeyIdentifier, false, aki.getEncoded("DER")));

        // CRLNumber to be adjusted to an incremental number
        CRLNumber crlNumber = new CRLNumber(BigInteger.valueOf(nextCrlSerial));
        extList.add(new Extension(Extension.cRLNumber, false, crlNumber.getEncoded("DER")));

        GeneralNames distributionPointName = new GeneralNames(
                new GeneralName(GeneralName.uniformResourceIdentifier, crlDpUrl));
        DistributionPointName dpn = new DistributionPointName(distributionPointName);
        IssuingDistributionPoint idp = new IssuingDistributionPoint(dpn, false, false);
        extList.add(new Extension(Extension.issuingDistributionPoint, true, idp.getEncoded("DER")));

        // IssuingDistributionPoint
        List<CRLEntryData> crlEdList = new ArrayList<>();

        certList.forEach((dbCert) -> {
            Date revTime = new Date();
            BigInteger serialNumber = dbCert.getCertificate().getSerialNumber();
            crlEdList.add(new CRLEntryData(serialNumber, new Date(dbCert.getRevDate()),
                    CRLReason.privilegeWithdrawn));
        });

        crl.updateCrl(new Date(currentTime), new Date(nextUpdateTime), crlEdList, extList);

        logRevocation(certList);

        // receive CRL
        latestCrl = crl.getCrl();
        cp.setIntValue(nextCrlSerial + 1);
        CaSQLiteUtil.storeParameter(cp, caDir);
        // Store CRL
        FileOps.saveByteFile(FileOps.readBinaryFile(crlFile), exportCrlFile);
        return latestCrl;

    } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException
            | CRLException | CertificateException | OperatorCreationException ex) {
        LOG.warning(ex.getMessage());
        return null;
    }
}