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.wildfly.extension.elytron.TlsTestCase.java

License:Apache License

private static X509CRLHolder createCRL() throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    SelfSignedX509CertificateAndSigningKey muneraSelfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey
            .builder().setDn(MUNERASOFT_DN).setKeyAlgorithmName("RSA")
            .setSignatureAlgorithmName("SHA256withRSA")
            .addExtension(false, "BasicConstraints", "CA:true,pathlen:2147483647").build();
    X509Certificate muneraCertificate = muneraSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();

    Calendar calendar = Calendar.getInstance();
    Date currentDate = calendar.getTime();
    calendar.add(Calendar.YEAR, 1);
    Date nextYear = calendar.getTime();
    calendar.add(Calendar.YEAR, -1);
    calendar.add(Calendar.SECOND, -30);
    Date revokeDate = calendar.getTime();

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(new X500Name(MUNERASOFT_DN.getName()), currentDate);
    crlBuilder.addExtension(Extension.authorityKeyIdentifier, false,
            new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(muneraCertificate.getPublicKey()));
    crlBuilder.addExtension(Extension.cRLNumber, false, new CRLNumber(BigInteger.valueOf(4110)));
    crlBuilder.addCRLEntry(new BigInteger("1005"), revokeDate, CRLReason.unspecified);
    crlBuilder.addCRLEntry(new BigInteger("1006"), revokeDate, CRLReason.unspecified);
    return crlBuilder.setNextUpdate(nextYear).build(new JcaContentSignerBuilder("SHA256withRSA")
            .setProvider("BC").build(muneraSelfSignedX509CertificateAndSigningKey.getSigningKey()));
}

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

License:Open Source License

void addCRL(final X509CertWithDBCertId caCert, final X509CRL crl)
        throws DataAccessException, CRLException, OperationException {
    byte[] encodedExtnValue = crl.getExtensionValue(Extension.cRLNumber.getId());
    Long crlNumber = null;//w  w  w.jav a2  s.  c  om
    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 = "INSERT INTO CRL (ID, CA_ID, CRL_NO, THISUPDATE, NEXTUPDATE, DELTACRL, BASECRL_NO, CRL)"
            + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    int currentMaxCrlId = (int) dataSource.getMax(null, "CRL", "ID");
    int crlId = currentMaxCrlId + 1;

    PreparedStatement ps = null;

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

        int idx = 1;
        ps.setInt(idx++, crlId);
        ps.setInt(idx++, caId);
        if (crlNumber != null) {
            ps.setInt(idx++, crlNumber.intValue());
        } else {
            ps.setNull(idx++, Types.INTEGER);
        }
        Date d = crl.getThisUpdate();
        ps.setLong(idx++, d.getTime() / 1000);
        d = crl.getNextUpdate();
        if (d != null) {
            ps.setLong(idx++, d.getTime() / 1000);
        } else {
            ps.setNull(idx++, Types.BIGINT);
        }

        ps.setInt(idx++, baseCrlNumber != null ? 1 : 0);

        if (baseCrlNumber != null) {
            ps.setLong(idx++, baseCrlNumber);
        } else {
            ps.setNull(idx++, Types.BIGINT);
        }

        byte[] encodedCrl = crl.getEncoded();
        String b64Crl = Base64.toBase64String(encodedCrl);
        ps.setString(idx++, b64Crl);

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

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  ww . j  a  va2s.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.commons.console.karaf.completer.ExtensionNameCompleter.java

License:Open Source License

public ExtensionNameCompleter() {
    List<ASN1ObjectIdentifier> oids = new LinkedList<>();
    oids.add(ObjectIdentifiers.id_extension_pkix_ocsp_nocheck);
    oids.add(ObjectIdentifiers.id_extension_admission);
    oids.add(Extension.auditIdentity);
    oids.add(Extension.authorityInfoAccess);
    oids.add(Extension.authorityKeyIdentifier);
    oids.add(Extension.basicConstraints);
    oids.add(Extension.biometricInfo);
    oids.add(Extension.certificateIssuer);
    oids.add(Extension.certificatePolicies);
    oids.add(Extension.cRLDistributionPoints);
    oids.add(Extension.cRLNumber);
    oids.add(Extension.deltaCRLIndicator);
    oids.add(Extension.extendedKeyUsage);
    oids.add(Extension.freshestCRL);
    oids.add(Extension.inhibitAnyPolicy);
    oids.add(Extension.instructionCode);
    oids.add(Extension.invalidityDate);
    oids.add(Extension.issuerAlternativeName);
    oids.add(Extension.issuingDistributionPoint);
    oids.add(Extension.keyUsage);
    oids.add(Extension.logoType);
    oids.add(Extension.nameConstraints);
    oids.add(Extension.noRevAvail);
    oids.add(Extension.policyConstraints);
    oids.add(Extension.policyMappings);
    oids.add(Extension.privateKeyUsagePeriod);
    oids.add(Extension.qCStatements);
    oids.add(Extension.reasonCode);
    oids.add(Extension.subjectAlternativeName);
    oids.add(Extension.subjectDirectoryAttributes);
    oids.add(Extension.subjectInfoAccess);
    oids.add(Extension.subjectKeyIdentifier);
    oids.add(Extension.targetInformation);
    oids.add(ObjectIdentifiers.id_pe_tlsfeature);

    StringBuilder enums = new StringBuilder();

    for (ASN1ObjectIdentifier oid : oids) {
        String name = ObjectIdentifiers.getName(oid);
        if (StringUtil.isBlank(name)) {
            name = oid.getId();//from  w ww  .j  a va2s . com
        }
        enums.append(name).append(",");
    }
    enums.deleteCharAt(enums.length() - 1);
    setTokens(enums.toString());
}

From source file:org.xipki.commons.security.shell.CrlInfoCmd.java

License:Open Source License

@Override
protected Object doExecute() throws Exception {
    CertificateList crl = CertificateList.getInstance(IoUtil.read(inFile));

    if (crlNumber != null && crlNumber) {
        ASN1Encodable asn1 = crl.getTBSCertList().getExtensions().getExtensionParsedValue(Extension.cRLNumber);
        if (asn1 == null) {
            return "null";
        }/*  ww  w.j  ava2 s. c  om*/
        return getNumber(ASN1Integer.getInstance(asn1).getPositiveValue());
    } else if (issuer != null && issuer) {
        return crl.getIssuer().toString();
    } else if (thisUpdate != null && thisUpdate) {
        return toUtcTimeyyyyMMddhhmmssZ(crl.getThisUpdate().getDate());
    } else if (nextUpdate != null && nextUpdate) {
        return crl.getNextUpdate() == null ? "null" : toUtcTimeyyyyMMddhhmmssZ(crl.getNextUpdate().getDate());
    }

    return null;
}

From source file:org.xipki.console.karaf.impl.completer.ExtensionNameCompleterImpl.java

License:Open Source License

public ExtensionNameCompleterImpl() {
    List<ASN1ObjectIdentifier> oids = new LinkedList<>();
    oids.add(ObjectIdentifiers.id_extension_pkix_ocsp_nocheck);
    oids.add(ObjectIdentifiers.id_extension_admission);
    oids.add(Extension.auditIdentity);
    oids.add(Extension.authorityInfoAccess);
    oids.add(Extension.authorityKeyIdentifier);
    oids.add(Extension.basicConstraints);
    oids.add(Extension.biometricInfo);
    oids.add(Extension.certificateIssuer);
    oids.add(Extension.certificatePolicies);
    oids.add(Extension.cRLDistributionPoints);
    oids.add(Extension.cRLNumber);
    oids.add(Extension.deltaCRLIndicator);
    oids.add(Extension.extendedKeyUsage);
    oids.add(Extension.freshestCRL);
    oids.add(Extension.inhibitAnyPolicy);
    oids.add(Extension.instructionCode);
    oids.add(Extension.invalidityDate);
    oids.add(Extension.issuerAlternativeName);
    oids.add(Extension.issuingDistributionPoint);
    oids.add(Extension.keyUsage);
    oids.add(Extension.logoType);
    oids.add(Extension.nameConstraints);
    oids.add(Extension.noRevAvail);
    oids.add(Extension.policyConstraints);
    oids.add(Extension.policyMappings);
    oids.add(Extension.privateKeyUsagePeriod);
    oids.add(Extension.qCStatements);
    oids.add(Extension.reasonCode);
    oids.add(Extension.subjectAlternativeName);
    oids.add(Extension.subjectDirectoryAttributes);
    oids.add(Extension.subjectInfoAccess);
    oids.add(Extension.subjectKeyIdentifier);
    oids.add(Extension.targetInformation);

    StringBuilder enums = new StringBuilder();

    for (ASN1ObjectIdentifier oid : oids) {
        String name = ObjectIdentifiers.getName(oid);
        if (StringUtil.isBlank(name)) {
            name = oid.getId();//from   w w w .j  av  a 2 s.  c  om
        }
        enums.append(name).append(",");
    }
    enums.deleteCharAt(enums.length() - 1);
    setTokens(enums.toString());
}

From source file:org.xipki.dbtool.CaCertStoreDbImporter.java

License:Open Source License

private void import_crl(final Crls crls) throws Exception {
    final String sql = "INSERT INTO CRL (ID, CA_ID, CRL_NO, THISUPDATE, NEXTUPDATE, DELTACRL, BASECRL_NO, CRL)"
            + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

    System.out.println("importing table CRL");

    PreparedStatement ps = prepareStatement(sql);

    try {/*from w ww.  ja v a 2  s  .  c  o  m*/
        int id = 1;
        for (CrlType crl : crls.getCrl()) {
            try {
                String filename = baseDir + File.separator + crl.getCrlFile();
                byte[] encodedCrl = IoUtil.read(filename);

                X509CRL c = null;
                try {
                    c = X509Util.parseCRL(new ByteArrayInputStream(encodedCrl));
                } catch (CertificateException | CRLException e) {
                    LOG.error("could not parse CRL in file {}", filename);
                    LOG.debug("could not parse CRL in file " + filename, e);
                }

                if (c == null) {
                    continue;
                }

                byte[] octetString = c.getExtensionValue(Extension.cRLNumber.getId());
                if (octetString == null) {
                    LOG.warn("CRL without CRL number, ignore it");
                    continue;
                }
                byte[] extnValue = DEROctetString.getInstance(octetString).getOctets();
                BigInteger crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();

                BigInteger baseCrlNumber = null;
                octetString = c.getExtensionValue(Extension.deltaCRLIndicator.getId());
                if (octetString != null) {
                    extnValue = DEROctetString.getInstance(octetString).getOctets();
                    baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();
                }

                int idx = 1;
                ps.setInt(idx++, id++);
                ps.setInt(idx++, crl.getCaId());
                ps.setLong(idx++, crlNumber.longValue());
                ps.setLong(idx++, c.getThisUpdate().getTime() / 1000);
                if (c.getNextUpdate() != null) {
                    ps.setLong(idx++, c.getNextUpdate().getTime() / 1000);
                } else {
                    ps.setNull(idx++, Types.INTEGER);
                }

                if (baseCrlNumber == null) {
                    setBoolean(ps, idx++, false);
                    ps.setNull(idx++, Types.BIGINT);
                } else {
                    setBoolean(ps, idx++, true);
                    ps.setLong(idx++, baseCrlNumber.longValue());
                }

                String s = Base64.toBase64String(encodedCrl);
                ps.setString(idx++, s);

                ps.executeUpdate();
            } catch (SQLException e) {
                System.err.println(
                        "error while importing CRL with ID=" + crl.getId() + ", message: " + e.getMessage());
                throw translate(sql, e);
            } catch (Exception e) {
                System.err.println(
                        "error while importing CRL with ID=" + crl.getId() + ", message: " + e.getMessage());
                throw e;
            }
        }
    } finally {
        releaseResources(ps, null);
    }

    System.out.println(" imported table CRL");
}

From source file:org.xipki.ocsp.server.impl.certstore.CrlCertStatusStore.java

License:Open Source License

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

    try {/*from w w w  .j a  va2 s.c o  m*/
        File fullCrlFile = new File(crlFilename);
        if (fullCrlFile.exists() == false) {
            // file does not exist
            LOG.warn("CRL File {} does not exist", crlFilename);
            return;
        }

        long newLastModifed = fullCrlFile.lastModified();

        boolean deltaCrlExists;
        File deltaCrlFile = null;
        if (deltaCrlFilename != null) {
            deltaCrlFile = new File(deltaCrlFilename);
            deltaCrlExists = deltaCrlFile.exists();
        } else {
            deltaCrlExists = false;
        }

        long newLastModifedOfDeltaCrl = deltaCrlExists ? deltaCrlFile.lastModified() : 0;

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

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

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

        if (crlFileChanged == false) {
            auditLogPCIEvent(AuditLevel.INFO, "UPDATE_CERTSTORE", "current CRL is still up-to-date");
            return;
        }

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

        if (crlFileChanged == false && deltaCrlFileChanged == false) {
            return;
        }

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

        auditLogPCIEvent(AuditLevel.INFO, "UPDATE_CERTSTORE", "a newer version of CRL is available");
        updateCRLSuccessfull = false;

        X509CRL crl = X509Util.parseCRL(crlFilename);
        BigInteger crlNumber;
        {
            byte[] octetString = crl.getExtensionValue(Extension.cRLNumber.getId());
            if (octetString != null) {
                byte[] extnValue = DEROctetString.getInstance(octetString).getOctets();
                crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();
            } else {
                crlNumber = null;
            }
        }

        X500Principal issuer = crl.getIssuerX500Principal();

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

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

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

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

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

            deltaCrl = X509Util.parseCRL(deltaCrlFilename);
            byte[] 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(crlNumber) == false) {
                    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();
                }
            }
        }

        if (crlFileChanged == false && deltaCrl == null) {
            return;
        }

        Date newThisUpdate;
        Date newNextUpdate;

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

        // Construct CrlID
        ASN1EncodableVector v = new ASN1EncodableVector();
        if (StringUtil.isNotBlank(crlUrl)) {
            v.add(new DERTaggedObject(true, 0, new DERIA5String(crlUrl, true)));
        }
        byte[] extValue = (deltaCrlExists ? deltaCrl : crl).getExtensionValue(Extension.cRLNumber.getId());
        if (extValue != null) {
            ASN1Integer asn1CrlNumber = ASN1Integer.getInstance(removeTagAndLenFromExtensionValue(extValue));
            v.add(new DERTaggedObject(true, 1, asn1CrlNumber));
        }
        v.add(new DERTaggedObject(true, 2, new DERGeneralizedTime(newThisUpdate)));
        this.crlID = CrlID.getInstance(new DERSequence(v));

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

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

        byte[] encodedKey = bcCaCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();

        Map<HashAlgoType, IssuerHashNameAndKey> newIssuerHashMap = new ConcurrentHashMap<>();

        for (HashAlgoType hashAlgo : HashAlgoType.values()) {
            byte[] issuerNameHash = HashCalculator.hash(hashAlgo, encodedName);
            byte[] issuerKeyHash = HashCalculator.hash(hashAlgo, 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
        boolean certsIncluded = false;
        Set<CertWithInfo> certs = new HashSet<>();
        String oidExtnCerts = ObjectIdentifiers.id_xipki_ext_crlCertset.getId();
        byte[] extnValue = crl.getExtensionValue(oidExtnCerts);
        if (extnValue == null) {
            // try the legacy OID
            extnValue = crl.getExtensionValue("1.3.6.1.4.1.12655.100");
        }

        if (extnValue != null) {
            extnValue = removeTagAndLenFromExtensionValue(extnValue);
            certsIncluded = true;
            ASN1Set asn1Set = DERSet.getInstance(extnValue);
            int n = asn1Set.size();
            for (int i = 0; i < n; i++) {
                ASN1Encodable asn1 = asn1Set.getObjectAt(i);
                Certificate bcCert;
                String profileName = null;

                try {
                    ASN1Sequence seq = ASN1Sequence.getInstance(asn1);
                    bcCert = Certificate.getInstance(seq.getObjectAt(0));
                    if (seq.size() > 1) {
                        profileName = DERUTF8String.getInstance(seq.getObjectAt(1)).getString();
                    }
                } catch (IllegalArgumentException e) {
                    // backwards compatibility
                    bcCert = Certificate.getInstance(asn1);
                }

                if (caName.equals(bcCert.getIssuer()) == false) {
                    throw new CertStatusStoreException("invalid entry in CRL Extension certs");
                }

                if (profileName == null) {
                    profileName = "UNKNOWN";
                }

                certs.add(new CertWithInfo(bcCert, profileName));
            }
        }

        if (certsDirname != null) {
            if (extnValue != null) {
                LOG.warn("ignore certsDir '{}', since certificates are included in CRL Extension certs",
                        certsDirname);
            } else {
                certsIncluded = true;
                Set<CertWithInfo> tmpCerts = readCertWithInfosFromDir(caCert, certsDirname);
                certs.addAll(tmpCerts);
            }
        }

        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 thisIssuer = revokedCert.getCertificateIssuer();
                if (thisIssuer != null && caCert.getSubjectX500Principal().equals(thisIssuer) == false) {
                    throw new CertStatusStoreException("invalid CRLEntry");
                }
            }
        }

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

        Map<BigInteger, X509CRLEntry> revokedCertMap = null;

        // merge the revoked list
        if (CollectionUtil.isNotEmpty(revokedCertListInDeltaCRL)) {
            revokedCertMap = new HashMap<BigInteger, X509CRLEntry>();
            for (X509CRLEntry entry : revokedCertListInFullCRL) {
                revokedCertMap.put(entry.getSerialNumber(), entry);
            }

            for (X509CRLEntry entry : revokedCertListInDeltaCRL) {
                BigInteger serialNumber = entry.getSerialNumber();
                java.security.cert.CRLReason reason = entry.getRevocationReason();
                if (reason == java.security.cert.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();
        }

        if (it != null) {
            while (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(removeTagAndLenFromExtensionValue(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 = removeTagAndLenFromExtensionValue(extnValue);
                    ASN1GeneralizedTime gTime = DERGeneralizedTime.getInstance(extnValue);
                    try {
                        invalidityTime = gTime.getDate();
                    } catch (ParseException e) {
                        throw new CertStatusStoreException(e.getMessage(), e);
                    }

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

                CertWithInfo cert = null;
                if (certsIncluded) {
                    for (CertWithInfo bcCert : certs) {
                        if (bcCert.cert.getIssuer().equals(caName)
                                && bcCert.cert.getSerialNumber().getPositiveValue().equals(serialNumber)) {
                            cert = bcCert;
                            break;
                        }
                    }

                    if (cert == null) {
                        LOG.info("could not find certificate (issuer = '{}', serialNumber = '{}'",
                                X509Util.getRFC4519Name(caName), serialNumber);
                    } else {
                        certs.remove(cert);
                    }
                }

                Map<HashAlgoType, byte[]> certHashes = (cert == null) ? null : getCertHashes(cert.cert);

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

        for (CertWithInfo cert : certs) {
            Map<HashAlgoType, byte[]> certHashes = getCertHashes(cert.cert);
            CrlCertStatusInfo crlCertStatusInfo = CrlCertStatusInfo.getGoodCertStatusInfo(cert.profileName,
                    certHashes);
            newCertStatusInfoMap.put(cert.cert.getSerialNumber().getPositiveValue(), 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.initializationFailed = false;
        this.initialized = true;
        updateCRLSuccessfull = true;
        LOG.info("updated CertStore {}", getName());
    } catch (Exception e) {
        final String message = "could not execute initializeStore()";
        if (LOG.isErrorEnabled()) {
            LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
        }
        LOG.debug(message, e);
        initializationFailed = true;
        initialized = true;
    } finally {
        if (updateCRLSuccessfull != null) {
            AuditLevel auditLevel;
            AuditStatus auditStatus;
            String eventType = "UPDATE_CRL";
            if (updateCRLSuccessfull) {
                auditLevel = AuditLevel.INFO;
                auditStatus = AuditStatus.FAILED;
            } else {
                auditLevel = AuditLevel.ERROR;
                auditStatus = AuditStatus.SUCCESSFUL;
            }

            auditLogPCIEvent(auditLevel, eventType, auditStatus.name());
        }
    }
}

From source file:org.xipki.pki.ca.dbtool.port.CaCertStoreDbExporter.java

License:Open Source License

private void doExportEntries(final CaDbEntryType type, final CertStoreType certstore, final File processLogFile,
        final FileOutputStream filenameListOs, final Long idProcessedInLastProcess) throws Exception {
    final int numEntriesPerSelect = Math.max(1, Math.round(type.getSqlBatchFactor() * numCertsPerSelect));
    final int numEntriesPerZip = Math.max(1, Math.round(type.getSqlBatchFactor() * numCertsInBundle));
    final File entriesDir = new File(baseDir, type.getDirName());
    final String tableName = type.getTableName();

    int numProcessedBefore;
    String coreSql;/*from   w  w w  . j  a va  2s . c  o m*/

    switch (type) {
    case CERT:
        numProcessedBefore = certstore.getCountCerts();
        coreSql = "ID,SN,CA_ID,PID,RID,ART,RTYPE,TID,UNAME,LUPDATE,REV,RR,RT,RIT,FP_RS,"
                + "REQ_SUBJECT,CERT FROM CERT INNER JOIN CRAW ON CERT.ID>=? " + "AND CERT.ID=CRAW.CID";
        break;
    case CRL:
        numProcessedBefore = certstore.getCountCrls();
        coreSql = "ID,CA_ID,CRL FROM CRL WHERE ID>=?";
        break;
    case USER:
        numProcessedBefore = certstore.getCountUsers();
        coreSql = "ID,NAME,PASSWORD,CN_REGEX FROM USERNAME WHERE ID>=?";
        break;
    case REQUEST:
        numProcessedBefore = certstore.getCountRequests();
        coreSql = "ID,LUPDATE,DATA FROM REQUEST WHERE ID>=?";
        break;
    case REQCERT:
        numProcessedBefore = certstore.getCountReqCerts();
        coreSql = "ID,RID,CID FROM REQCERT WHERE ID>=?";
        break;
    default:
        throw new RuntimeException("unknown CaDbEntryType " + type);
    }

    Long minId = null;
    if (idProcessedInLastProcess != null) {
        minId = idProcessedInLastProcess + 1;
    } else {
        minId = getMin(tableName, "ID");
    }

    String tablesText = (CaDbEntryType.CERT == type) ? "tables " + tableName + " and CRAW"
            : "table " + type.getTableName();
    System.out.println(getExportingText() + tablesText + " from ID " + minId);

    final long maxId = getMax(tableName, "ID");
    long total = getCount(tableName) - numProcessedBefore;
    if (total < 1) {
        total = 1; // to avoid exception
    }

    String sql = datasource.buildSelectFirstSql(coreSql, numEntriesPerSelect, "ID ASC");

    DbiXmlWriter entriesInCurrentFile = createWriter(type);
    PreparedStatement ps = prepareStatement(sql.toString());

    int numEntriesInCurrentFile = 0;

    int sum = 0;
    File currentEntriesZipFile = new File(baseDir,
            "tmp-" + type.getDirName() + "-" + System.currentTimeMillis() + ".zip");
    ZipOutputStream currentEntriesZip = getZipOutputStream(currentEntriesZipFile);

    long minIdOfCurrentFile = -1;
    long maxIdOfCurrentFile = -1;

    ProcessLog processLog = new ProcessLog(total);
    processLog.printHeader();

    try {
        Long id = null;
        boolean interrupted = false;
        long lastMaxId = minId - 1;

        while (true) {
            if (stopMe.get()) {
                interrupted = true;
                break;
            }

            ps.setLong(1, lastMaxId + 1);

            ResultSet rs = ps.executeQuery();

            // no entries anymore
            if (!rs.next()) {
                break;
            }

            do {
                id = rs.getLong("ID");
                if (lastMaxId < id) {
                    lastMaxId = id;
                }

                if (minIdOfCurrentFile == -1) {
                    minIdOfCurrentFile = id;
                } else if (minIdOfCurrentFile > id) {
                    minIdOfCurrentFile = id;
                }

                if (maxIdOfCurrentFile == -1) {
                    maxIdOfCurrentFile = id;
                } else if (maxIdOfCurrentFile < id) {
                    maxIdOfCurrentFile = id;
                }

                if (CaDbEntryType.CERT == type) {
                    String b64Cert = rs.getString("CERT");
                    byte[] certBytes = Base64.decode(b64Cert);

                    String sha1 = HashAlgoType.SHA1.hexHash(certBytes);
                    String certFileName = sha1 + ".der";
                    if (!evaulateOnly) {
                        ZipEntry certZipEntry = new ZipEntry(certFileName);
                        currentEntriesZip.putNextEntry(certZipEntry);
                        try {
                            currentEntriesZip.write(certBytes);
                        } finally {
                            currentEntriesZip.closeEntry();
                        }
                    }

                    CaCertType cert = new CaCertType();
                    cert.setId(id);

                    byte[] tid = null;
                    int art = rs.getInt("ART");
                    int reqType = rs.getInt("RTYPE");
                    String str = rs.getString("TID");
                    if (StringUtil.isNotBlank(str)) {
                        tid = Base64.decode(str);
                    }

                    cert.setArt(art);
                    cert.setReqType(reqType);
                    if (tid != null) {
                        cert.setTid(Base64.toBase64String(tid));
                    }

                    int cainfoId = rs.getInt("CA_ID");
                    cert.setCaId(cainfoId);

                    String serial = rs.getString("SN");
                    cert.setSn(serial);

                    int certprofileId = rs.getInt("PID");
                    cert.setPid(certprofileId);

                    int requestorinfoId = rs.getInt("RID");
                    if (requestorinfoId != 0) {
                        cert.setRid(requestorinfoId);
                    }

                    long lastUpdate = rs.getLong("LUPDATE");
                    cert.setUpdate(lastUpdate);

                    boolean revoked = rs.getBoolean("REV");
                    cert.setRev(revoked);

                    if (revoked) {
                        int revReason = rs.getInt("RR");
                        long revTime = rs.getLong("RT");
                        long revInvTime = rs.getLong("RIT");
                        cert.setRr(revReason);
                        cert.setRt(revTime);
                        if (revInvTime != 0) {
                            cert.setRit(revInvTime);
                        }
                    }

                    String user = rs.getString("UNAME");
                    if (user != null) {
                        cert.setUser(user);
                    }
                    cert.setFile(certFileName);

                    long fpReqSubject = rs.getLong("FP_RS");
                    if (fpReqSubject != 0) {
                        cert.setFpRs(fpReqSubject);
                        String reqSubject = rs.getString("REQ_SUBJECT");
                        cert.setRs(reqSubject);
                    }

                    ((CaCertsWriter) entriesInCurrentFile).add(cert);
                } else if (CaDbEntryType.CRL == type) {
                    String b64Crl = rs.getString("CRL");
                    byte[] crlBytes = Base64.decode(b64Crl);

                    X509CRL x509Crl = null;
                    try {
                        x509Crl = X509Util.parseCrl(crlBytes);
                    } catch (Exception ex) {
                        LogUtil.error(LOG, ex, "could not parse CRL with id " + id);
                        if (ex instanceof CRLException) {
                            throw (CRLException) ex;
                        } else {
                            throw new CRLException(ex.getMessage(), ex);
                        }
                    }

                    byte[] octetString = x509Crl.getExtensionValue(Extension.cRLNumber.getId());
                    if (octetString == null) {
                        LOG.warn("CRL without CRL number, ignore it");
                        continue;
                    }
                    String sha1 = HashAlgoType.SHA1.hexHash(crlBytes);

                    final String crlFilename = sha1 + ".crl";
                    if (!evaulateOnly) {
                        ZipEntry certZipEntry = new ZipEntry(crlFilename);
                        currentEntriesZip.putNextEntry(certZipEntry);
                        try {
                            currentEntriesZip.write(crlBytes);
                        } finally {
                            currentEntriesZip.closeEntry();
                        }
                    }

                    CaCrlType crl = new CaCrlType();
                    crl.setId(id);

                    int caId = rs.getInt("CA_ID");
                    crl.setCaId(caId);

                    byte[] extnValue = DEROctetString.getInstance(octetString).getOctets();
                    BigInteger crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();
                    crl.setCrlNo(crlNumber.toString());
                    crl.setFile(crlFilename);

                    ((CaCrlsWriter) entriesInCurrentFile).add(crl);
                } else if (CaDbEntryType.USER == type) {
                    String name = rs.getString("NAME");
                    CaUserType user = new CaUserType();
                    user.setId(id);
                    user.setName(name);
                    String password = rs.getString("PASSWORD");
                    user.setPassword(password);

                    String cnRegex = rs.getString("CN_REGEX");
                    user.setCnRegex(cnRegex);
                    ((CaUsersWriter) entriesInCurrentFile).add(user);
                } else if (CaDbEntryType.REQUEST == type) {
                    long update = rs.getLong("LUPDATE");
                    String b64Data = rs.getString("DATA");
                    byte[] dataBytes = Base64.decode(b64Data);
                    String sha1 = HashAlgoType.SHA1.hexHash(dataBytes);
                    final String dataFilename = sha1 + ".req";
                    if (!evaulateOnly) {
                        ZipEntry certZipEntry = new ZipEntry(dataFilename);
                        currentEntriesZip.putNextEntry(certZipEntry);
                        try {
                            currentEntriesZip.write(dataBytes);
                        } finally {
                            currentEntriesZip.closeEntry();
                        }
                    }
                    CaRequestType entry = new CaRequestType();
                    entry.setId(id);
                    entry.setUpdate(update);
                    entry.setFile(dataFilename);
                    ((CaRequestsWriter) entriesInCurrentFile).add(entry);
                } else if (CaDbEntryType.REQCERT == type) {
                    long cid = rs.getLong("CID");
                    long rid = rs.getLong("RID");
                    CaRequestCertType entry = new CaRequestCertType();
                    entry.setId(id);
                    entry.setCid(cid);
                    entry.setRid(rid);
                    ((CaRequestCertsWriter) entriesInCurrentFile).add(entry);
                } else {
                    throw new RuntimeException("unknown CaDbEntryType " + type);
                }

                numEntriesInCurrentFile++;
                sum++;

                if (numEntriesInCurrentFile == numEntriesPerZip) {
                    String currentEntriesFilename = buildFilename(type.getDirName() + "_", ".zip",
                            minIdOfCurrentFile, maxIdOfCurrentFile, maxId);
                    finalizeZip(currentEntriesZip, "overview.xml", entriesInCurrentFile);
                    currentEntriesZipFile.renameTo(new File(entriesDir, currentEntriesFilename));

                    writeLine(filenameListOs, currentEntriesFilename);
                    setCount(type, certstore, numProcessedBefore + sum);
                    echoToFile(tableName + ":" + Long.toString(id), processLogFile);

                    processLog.addNumProcessed(numEntriesInCurrentFile);
                    processLog.printStatus();

                    // reset
                    entriesInCurrentFile = createWriter(type);
                    numEntriesInCurrentFile = 0;
                    minIdOfCurrentFile = -1;
                    maxIdOfCurrentFile = -1;
                    currentEntriesZipFile = new File(baseDir,
                            "tmp-" + type.getDirName() + "-" + System.currentTimeMillis() + ".zip");
                    currentEntriesZip = getZipOutputStream(currentEntriesZipFile);
                }
            } while (rs.next());

            rs.close();
        } // end for

        if (interrupted) {
            currentEntriesZip.close();
            throw new InterruptedException("interrupted by the user");
        }

        if (numEntriesInCurrentFile > 0) {
            finalizeZip(currentEntriesZip, "overview.xml", entriesInCurrentFile);

            String currentEntriesFilename = buildFilename(type.getDirName() + "_", ".zip", minIdOfCurrentFile,
                    maxIdOfCurrentFile, maxId);
            currentEntriesZipFile.renameTo(new File(entriesDir, currentEntriesFilename));

            writeLine(filenameListOs, currentEntriesFilename);
            setCount(type, certstore, numProcessedBefore + sum);
            if (id != null) {
                echoToFile(Long.toString(id), processLogFile);
            }

            processLog.addNumProcessed(numEntriesInCurrentFile);
        } else {
            currentEntriesZip.close();
            currentEntriesZipFile.delete();
        }

    } catch (SQLException ex) {
        throw translate(null, ex);
    } finally {
        releaseResources(ps, null);
    } // end try

    processLog.printTrailer();
    // all successful, delete the processLogFile
    processLogFile.delete();
    System.out.println(getExportedText() + sum + " entries from " + tablesText);
}

From source file:org.xipki.pki.ca.dbtool.port.CaCertStoreDbImporter.java

License:Open Source License

private long doImportEntries(final CaDbEntryType type, final String entriesZipFile, final long minId,
        final File processLogFile, final ProcessLog processLog, final int numProcessedInLastProcess,
        final PreparedStatement[] statements, final String[] sqls) throws Exception {
    final int numEntriesPerCommit = Math.max(1, Math.round(type.getSqlBatchFactor() * numCertsPerCommit));

    ZipFile zipFile = new ZipFile(new File(entriesZipFile));
    ZipEntry entriesXmlEntry = zipFile.getEntry("overview.xml");

    DbiXmlReader entries;// ww w  .j ava2s .c  o  m
    try {
        entries = createReader(type, zipFile.getInputStream(entriesXmlEntry));
    } catch (Exception ex) {
        try {
            zipFile.close();
        } catch (Exception e2) {
            LOG.error("could not close ZIP file {}: {}", entriesZipFile, e2.getMessage());
            LOG.debug("could not close ZIP file " + entriesZipFile, e2);
        }
        throw ex;
    }

    disableAutoCommit();

    try {
        int numEntriesInBatch = 0;
        long lastSuccessfulEntryId = 0;

        while (entries.hasNext()) {
            if (stopMe.get()) {
                throw new InterruptedException("interrupted by the user");
            }

            IdentifidDbObjectType entry = (IdentifidDbObjectType) entries.next();
            long id = entry.getId();
            if (id < minId) {
                continue;
            }

            numEntriesInBatch++;

            if (CaDbEntryType.CERT == type) {
                CaCertType cert = (CaCertType) entry;
                int certArt = (cert.getArt() == null) ? 1 : cert.getArt();

                String filename = cert.getFile();
                // rawcert
                ZipEntry certZipEnty = zipFile.getEntry(filename);
                // rawcert
                byte[] encodedCert = IoUtil.read(zipFile.getInputStream(certZipEnty));

                TBSCertificate tbsCert;
                try {
                    Certificate cc = Certificate.getInstance(encodedCert);
                    tbsCert = cc.getTBSCertificate();
                } catch (RuntimeException ex) {
                    LOG.error("could not parse certificate in file {}", filename);
                    LOG.debug("could not parse certificate in file " + filename, ex);
                    throw new CertificateException(ex.getMessage(), ex);
                }

                byte[] encodedKey = tbsCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();

                String b64Sha1FpCert = HashAlgoType.SHA1.base64Hash(encodedCert);

                // cert
                String subjectText = X509Util.cutX500Name(tbsCert.getSubject(), maxX500nameLen);

                PreparedStatement psCert = statements[0];
                PreparedStatement psRawcert = statements[1];

                try {
                    int idx = 1;

                    psCert.setLong(idx++, id);
                    psCert.setInt(idx++, certArt);
                    psCert.setLong(idx++, cert.getUpdate());
                    psCert.setString(idx++, tbsCert.getSerialNumber().getPositiveValue().toString(16));

                    psCert.setString(idx++, subjectText);
                    long fpSubject = X509Util.fpCanonicalizedName(tbsCert.getSubject());
                    psCert.setLong(idx++, fpSubject);

                    if (cert.getFpRs() != null) {
                        psCert.setLong(idx++, cert.getFpRs());
                    } else {
                        psCert.setNull(idx++, Types.BIGINT);
                    }

                    psCert.setLong(idx++, tbsCert.getStartDate().getDate().getTime() / 1000);
                    psCert.setLong(idx++, tbsCert.getEndDate().getDate().getTime() / 1000);
                    setBoolean(psCert, idx++, cert.getRev());
                    setInt(psCert, idx++, cert.getRr());
                    setLong(psCert, idx++, cert.getRt());
                    setLong(psCert, idx++, cert.getRit());
                    setInt(psCert, idx++, cert.getPid());
                    setInt(psCert, idx++, cert.getCaId());

                    setInt(psCert, idx++, cert.getRid());
                    psCert.setString(idx++, cert.getUser());
                    psCert.setLong(idx++, FpIdCalculator.hash(encodedKey));
                    Extension extension = tbsCert.getExtensions().getExtension(Extension.basicConstraints);
                    boolean ee = true;
                    if (extension != null) {
                        ASN1Encodable asn1 = extension.getParsedValue();
                        ee = !BasicConstraints.getInstance(asn1).isCA();
                    }

                    psCert.setInt(idx++, ee ? 1 : 0);
                    psCert.setInt(idx++, cert.getReqType());
                    String tidS = null;
                    if (cert.getTid() != null) {
                        tidS = cert.getTid();
                    }
                    psCert.setString(idx++, tidS);
                    psCert.addBatch();
                } catch (SQLException ex) {
                    throw translate(SQL_ADD_CERT, ex);
                }

                try {
                    int idx = 1;
                    psRawcert.setLong(idx++, cert.getId());
                    psRawcert.setString(idx++, b64Sha1FpCert);
                    psRawcert.setString(idx++, cert.getRs());
                    psRawcert.setString(idx++, Base64.toBase64String(encodedCert));
                    psRawcert.addBatch();
                } catch (SQLException ex) {
                    throw translate(SQL_ADD_CRAW, ex);
                }
            } else if (CaDbEntryType.CRL == type) {
                PreparedStatement psAddCrl = statements[0];

                CaCrlType crl = (CaCrlType) entry;

                String filename = crl.getFile();

                // CRL
                ZipEntry zipEnty = zipFile.getEntry(filename);

                // rawcert
                byte[] encodedCrl = IoUtil.read(zipFile.getInputStream(zipEnty));

                X509CRL x509crl = null;
                try {
                    x509crl = X509Util.parseCrl(encodedCrl);
                } catch (Exception ex) {
                    LOG.error("could not parse CRL in file {}", filename);
                    LOG.debug("could not parse CRL in file " + filename, ex);
                    if (ex instanceof CRLException) {
                        throw (CRLException) ex;
                    } else {
                        throw new CRLException(ex.getMessage(), ex);
                    }
                }

                try {
                    byte[] octetString = x509crl.getExtensionValue(Extension.cRLNumber.getId());
                    if (octetString == null) {
                        LOG.warn("CRL without CRL number, ignore it");
                        continue;
                    }
                    byte[] extnValue = DEROctetString.getInstance(octetString).getOctets();
                    // CHECKSTYLE:SKIP
                    BigInteger crlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();

                    BigInteger baseCrlNumber = null;
                    octetString = x509crl.getExtensionValue(Extension.deltaCRLIndicator.getId());
                    if (octetString != null) {
                        extnValue = DEROctetString.getInstance(octetString).getOctets();
                        baseCrlNumber = ASN1Integer.getInstance(extnValue).getPositiveValue();
                    }

                    int idx = 1;
                    psAddCrl.setLong(idx++, crl.getId());
                    psAddCrl.setInt(idx++, crl.getCaId());
                    psAddCrl.setLong(idx++, crlNumber.longValue());
                    psAddCrl.setLong(idx++, x509crl.getThisUpdate().getTime() / 1000);
                    if (x509crl.getNextUpdate() != null) {
                        psAddCrl.setLong(idx++, x509crl.getNextUpdate().getTime() / 1000);
                    } else {
                        psAddCrl.setNull(idx++, Types.INTEGER);
                    }

                    if (baseCrlNumber == null) {
                        setBoolean(psAddCrl, idx++, false);
                        psAddCrl.setNull(idx++, Types.BIGINT);
                    } else {
                        setBoolean(psAddCrl, idx++, true);
                        psAddCrl.setLong(idx++, baseCrlNumber.longValue());
                    }

                    String str = Base64.toBase64String(encodedCrl);
                    psAddCrl.setString(idx++, str);

                    psAddCrl.addBatch();
                } catch (SQLException ex) {
                    System.err.println(
                            "could not import CRL with ID=" + crl.getId() + ", message: " + ex.getMessage());
                    throw ex;
                }
            } else if (CaDbEntryType.USER == type) {
                PreparedStatement psAddUser = statements[0];
                CaUserType user = (CaUserType) entry;

                try {
                    int idx = 1;
                    psAddUser.setLong(idx++, user.getId());
                    psAddUser.setString(idx++, user.getName());
                    psAddUser.setString(idx++, user.getPassword());
                    psAddUser.setString(idx++, user.getCnRegex());
                    psAddUser.addBatch();
                } catch (SQLException ex) {
                    System.err.println("could not import USERNAME with ID=" + user.getId() + ", message: "
                            + ex.getMessage());
                    throw ex;
                }
            } else if (CaDbEntryType.REQUEST == type) {
                PreparedStatement psAddRequest = statements[0];

                CaRequestType request = (CaRequestType) entry;

                String filename = request.getFile();

                ZipEntry zipEnty = zipFile.getEntry(filename);
                byte[] encodedRequest = IoUtil.read(zipFile.getInputStream(zipEnty));

                try {
                    int idx = 1;
                    psAddRequest.setLong(idx++, request.getId());
                    psAddRequest.setLong(idx++, request.getUpdate());
                    psAddRequest.setString(idx++, Base64.toBase64String(encodedRequest));
                    psAddRequest.addBatch();
                } catch (SQLException ex) {
                    System.err.println("could not import REQUEST with ID=" + request.getId() + ", message: "
                            + ex.getMessage());
                    throw ex;
                }
            } else if (CaDbEntryType.REQCERT == type) {
                PreparedStatement psAddReqCert = statements[0];

                CaRequestCertType reqCert = (CaRequestCertType) entry;

                try {
                    int idx = 1;
                    psAddReqCert.setLong(idx++, reqCert.getId());
                    psAddReqCert.setLong(idx++, reqCert.getRid());
                    psAddReqCert.setLong(idx++, reqCert.getCid());
                    psAddReqCert.addBatch();
                } catch (SQLException ex) {
                    System.err.println("could not import REQUEST with ID=" + reqCert.getId() + ", message: "
                            + ex.getMessage());
                    throw ex;
                }
            } else {
                throw new RuntimeException("Unknown CaDbEntryType " + type);
            }

            boolean isLastBlock = !entries.hasNext();
            if (numEntriesInBatch > 0 && (numEntriesInBatch % numEntriesPerCommit == 0 || isLastBlock)) {
                if (evaulateOnly) {
                    for (PreparedStatement m : statements) {
                        m.clearBatch();
                    }
                } else {
                    String sql = null;

                    try {
                        for (int i = 0; i < sqls.length; i++) {
                            sql = sqls[i];
                            statements[i].executeBatch();
                        }

                        sql = null;
                        commit("(commit import to CA)");
                    } catch (Throwable th) {
                        rollback();
                        deleteFromTableWithLargerId(type.getTableName(), "ID", id, LOG);
                        if (CaDbEntryType.CERT == type) {
                            deleteFromTableWithLargerId("CRAW", "CID", id, LOG);
                        }
                        if (th instanceof SQLException) {
                            throw translate(sql, (SQLException) th);
                        } else if (th instanceof Exception) {
                            throw (Exception) th;
                        } else {
                            throw new Exception(th);
                        }
                    }
                }

                lastSuccessfulEntryId = id;
                processLog.addNumProcessed(numEntriesInBatch);
                numEntriesInBatch = 0;
                echoToFile(type + ":" + (numProcessedInLastProcess + processLog.getNumProcessed()) + ":"
                        + lastSuccessfulEntryId, processLogFile);
                processLog.printStatus();
            }

        } // end while

        return lastSuccessfulEntryId;
    } finally {
        recoverAutoCommit();
        zipFile.close();
    }
}