Search in sources :

Example 26 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project android_frameworks_base by DirtyUnicorns.

the class AndroidKeyStoreKeyPairGeneratorSpi method generateSelfSignedCertificateWithFakeSignature.

@SuppressWarnings("deprecation")
private X509Certificate generateSelfSignedCertificateWithFakeSignature(PublicKey publicKey) throws IOException, CertificateParsingException {
    V3TBSCertificateGenerator tbsGenerator = new V3TBSCertificateGenerator();
    ASN1ObjectIdentifier sigAlgOid;
    AlgorithmIdentifier sigAlgId;
    byte[] signature;
    switch(mKeymasterAlgorithm) {
        case KeymasterDefs.KM_ALGORITHM_EC:
            sigAlgOid = X9ObjectIdentifiers.ecdsa_with_SHA256;
            sigAlgId = new AlgorithmIdentifier(sigAlgOid);
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERInteger(0));
            v.add(new DERInteger(0));
            signature = new DERSequence().getEncoded();
            break;
        case KeymasterDefs.KM_ALGORITHM_RSA:
            sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
            sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE);
            signature = new byte[1];
            break;
        default:
            throw new ProviderException("Unsupported key algorithm: " + mKeymasterAlgorithm);
    }
    try (ASN1InputStream publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded())) {
        tbsGenerator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject()));
    }
    tbsGenerator.setSerialNumber(new ASN1Integer(mSpec.getCertificateSerialNumber()));
    X509Principal subject = new X509Principal(mSpec.getCertificateSubject().getEncoded());
    tbsGenerator.setSubject(subject);
    tbsGenerator.setIssuer(subject);
    tbsGenerator.setStartDate(new Time(mSpec.getCertificateNotBefore()));
    tbsGenerator.setEndDate(new Time(mSpec.getCertificateNotAfter()));
    tbsGenerator.setSignature(sigAlgId);
    TBSCertificate tbsCertificate = tbsGenerator.generateTBSCertificate();
    ASN1EncodableVector result = new ASN1EncodableVector();
    result.add(tbsCertificate);
    result.add(sigAlgId);
    result.add(new DERBitString(signature));
    return new X509CertificateObject(Certificate.getInstance(new DERSequence(result)));
}
Also used : ASN1InputStream(com.android.org.bouncycastle.asn1.ASN1InputStream) ProviderException(java.security.ProviderException) Time(com.android.org.bouncycastle.asn1.x509.Time) DERBitString(com.android.org.bouncycastle.asn1.DERBitString) ASN1Integer(com.android.org.bouncycastle.asn1.ASN1Integer) AlgorithmIdentifier(com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERInteger(com.android.org.bouncycastle.asn1.DERInteger) DERSequence(com.android.org.bouncycastle.asn1.DERSequence) X509CertificateObject(com.android.org.bouncycastle.jce.provider.X509CertificateObject) X509Principal(com.android.org.bouncycastle.jce.X509Principal) ASN1EncodableVector(com.android.org.bouncycastle.asn1.ASN1EncodableVector) V3TBSCertificateGenerator(com.android.org.bouncycastle.asn1.x509.V3TBSCertificateGenerator) TBSCertificate(com.android.org.bouncycastle.asn1.x509.TBSCertificate) ASN1ObjectIdentifier(com.android.org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 27 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project xipki by xipki.

the class AbstractOcspRequestor method buildRequest.

// method ask
private OCSPRequest buildRequest(X509Certificate caCert, BigInteger[] serialNumbers, byte[] nonce, RequestOptions requestOptions) throws OcspRequestorException {
    HashAlgo hashAlgo = HashAlgo.getInstance(requestOptions.getHashAlgorithmId());
    if (hashAlgo == null) {
        throw new OcspRequestorException("unknown HashAlgo " + requestOptions.getHashAlgorithmId().getId());
    }
    List<AlgorithmIdentifier> prefSigAlgs = requestOptions.getPreferredSignatureAlgorithms();
    XiOCSPReqBuilder reqBuilder = new XiOCSPReqBuilder();
    List<Extension> extensions = new LinkedList<>();
    if (nonce != null) {
        extensions.add(new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce)));
    }
    if (prefSigAlgs != null && prefSigAlgs.size() > 0) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (AlgorithmIdentifier algId : prefSigAlgs) {
            vec.add(new DERSequence(algId));
        }
        ASN1Sequence extnValue = new DERSequence(vec);
        Extension extn;
        try {
            extn = new Extension(ObjectIdentifiers.id_pkix_ocsp_prefSigAlgs, false, new DEROctetString(extnValue));
        } catch (IOException ex) {
            throw new OcspRequestorException(ex.getMessage(), ex);
        }
        extensions.add(extn);
    }
    if (CollectionUtil.isNonEmpty(extensions)) {
        reqBuilder.setRequestExtensions(new Extensions(extensions.toArray(new Extension[0])));
    }
    try {
        DEROctetString issuerNameHash = new DEROctetString(hashAlgo.hash(caCert.getSubjectX500Principal().getEncoded()));
        TBSCertificate tbsCert;
        try {
            tbsCert = TBSCertificate.getInstance(caCert.getTBSCertificate());
        } catch (CertificateEncodingException ex) {
            throw new OcspRequestorException(ex);
        }
        DEROctetString issuerKeyHash = new DEROctetString(hashAlgo.hash(tbsCert.getSubjectPublicKeyInfo().getPublicKeyData().getOctets()));
        for (BigInteger serialNumber : serialNumbers) {
            CertID certId = new CertID(hashAlgo.getAlgorithmIdentifier(), issuerNameHash, issuerKeyHash, new ASN1Integer(serialNumber));
            reqBuilder.addRequest(certId);
        }
        if (requestOptions.isSignRequest()) {
            synchronized (signerLock) {
                if (signer == null) {
                    if (StringUtil.isBlank(signerType)) {
                        throw new OcspRequestorException("signerType is not configured");
                    }
                    if (StringUtil.isBlank(signerConf)) {
                        throw new OcspRequestorException("signerConf is not configured");
                    }
                    X509Certificate cert = null;
                    if (StringUtil.isNotBlank(signerCertFile)) {
                        try {
                            cert = X509Util.parseCert(signerCertFile);
                        } catch (CertificateException ex) {
                            throw new OcspRequestorException("could not parse certificate " + signerCertFile + ": " + ex.getMessage());
                        }
                    }
                    try {
                        signer = getSecurityFactory().createSigner(signerType, new SignerConf(signerConf), cert);
                    } catch (Exception ex) {
                        throw new OcspRequestorException("could not create signer: " + ex.getMessage());
                    }
                }
            // end if
            }
            // end synchronized
            reqBuilder.setRequestorName(signer.getBcCertificate().getSubject());
            X509CertificateHolder[] certChain0 = signer.getBcCertificateChain();
            Certificate[] certChain = new Certificate[certChain0.length];
            for (int i = 0; i < certChain.length; i++) {
                certChain[i] = certChain0[i].toASN1Structure();
            }
            ConcurrentBagEntrySigner signer0;
            try {
                signer0 = signer.borrowSigner();
            } catch (NoIdleSignerException ex) {
                throw new OcspRequestorException("NoIdleSignerException: " + ex.getMessage());
            }
            try {
                return reqBuilder.build(signer0.value(), certChain);
            } finally {
                signer.requiteSigner(signer0);
            }
        } else {
            return reqBuilder.build();
        }
    // end if
    } catch (OCSPException | IOException ex) {
        throw new OcspRequestorException(ex.getMessage(), ex);
    }
}
Also used : HashAlgo(org.xipki.security.HashAlgo) CertID(org.bouncycastle.asn1.ocsp.CertID) CertificateException(java.security.cert.CertificateException) Extensions(org.bouncycastle.asn1.x509.Extensions) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERSequence(org.bouncycastle.asn1.DERSequence) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) OcspRequestorException(org.xipki.ocsp.client.api.OcspRequestorException) SignerConf(org.xipki.security.SignerConf) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) ConcurrentBagEntrySigner(org.xipki.security.ConcurrentBagEntrySigner) LinkedList(java.util.LinkedList) X509Certificate(java.security.cert.X509Certificate) OcspNonceUnmatchedException(org.xipki.ocsp.client.api.OcspNonceUnmatchedException) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) OcspResponseException(org.xipki.ocsp.client.api.OcspResponseException) OcspRequestorException(org.xipki.ocsp.client.api.OcspRequestorException) CertificateEncodingException(java.security.cert.CertificateEncodingException) NoIdleSignerException(org.xipki.security.exception.NoIdleSignerException) ResponderUnreachableException(org.xipki.ocsp.client.api.ResponderUnreachableException) OcspTargetUnmatchedException(org.xipki.ocsp.client.api.OcspTargetUnmatchedException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) InvalidOcspResponseException(org.xipki.ocsp.client.api.InvalidOcspResponseException) Extension(org.bouncycastle.asn1.x509.Extension) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Example 28 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project xipki by xipki.

the class X509CertprofileQa method checkCert.

// constructor
public ValidationResult checkCert(byte[] certBytes, X509IssuerInfo issuerInfo, X500Name requestedSubject, SubjectPublicKeyInfo requestedPublicKey, Extensions requestedExtensions) {
    ParamUtil.requireNonNull("certBytes", certBytes);
    ParamUtil.requireNonNull("issuerInfo", issuerInfo);
    ParamUtil.requireNonNull("requestedSubject", requestedSubject);
    ParamUtil.requireNonNull("requestedPublicKey", requestedPublicKey);
    List<ValidationIssue> resultIssues = new LinkedList<ValidationIssue>();
    Certificate bcCert;
    TBSCertificate tbsCert;
    X509Certificate cert;
    ValidationIssue issue;
    // certificate size
    issue = new ValidationIssue("X509.SIZE", "certificate size");
    resultIssues.add(issue);
    Integer maxSize = certProfile.getMaxSize();
    if (maxSize != 0) {
        int size = certBytes.length;
        if (size > maxSize) {
            issue.setFailureMessage(String.format("certificate exceeds the maximal allowed size: %d > %d", size, maxSize));
        }
    }
    // certificate encoding
    issue = new ValidationIssue("X509.ENCODING", "certificate encoding");
    resultIssues.add(issue);
    try {
        bcCert = Certificate.getInstance(certBytes);
        tbsCert = bcCert.getTBSCertificate();
        cert = X509Util.parseCert(certBytes);
    } catch (CertificateException ex) {
        issue.setFailureMessage("certificate is not corrected encoded");
        return new ValidationResult(resultIssues);
    }
    // syntax version
    issue = new ValidationIssue("X509.VERSION", "certificate version");
    resultIssues.add(issue);
    int versionNumber = tbsCert.getVersionNumber();
    X509CertVersion expVersion = certProfile.getVersion();
    if (versionNumber != expVersion.getVersionNumber()) {
        issue.setFailureMessage("is '" + versionNumber + "' but expected '" + expVersion.getVersionNumber() + "'");
    }
    // serialNumber
    issue = new ValidationIssue("X509.serialNumber", "certificate serial number");
    resultIssues.add(issue);
    BigInteger serialNumber = tbsCert.getSerialNumber().getValue();
    if (serialNumber.signum() != 1) {
        issue.setFailureMessage("not positive");
    } else {
        if (serialNumber.bitLength() >= 160) {
            issue.setFailureMessage("serial number has more than 20 octets");
        }
    }
    // signatureAlgorithm
    List<String> signatureAlgorithms = certProfile.getSignatureAlgorithms();
    if (CollectionUtil.isNonEmpty(signatureAlgorithms)) {
        issue = new ValidationIssue("X509.SIGALG", "signature algorithm");
        resultIssues.add(issue);
        AlgorithmIdentifier sigAlgId = bcCert.getSignatureAlgorithm();
        AlgorithmIdentifier tbsSigAlgId = tbsCert.getSignature();
        if (!tbsSigAlgId.equals(sigAlgId)) {
            issue.setFailureMessage("Certificate.tbsCertificate.signature != Certificate.signatureAlgorithm");
        }
        try {
            String sigAlgo = AlgorithmUtil.getSignatureAlgoName(sigAlgId);
            if (!issue.isFailed()) {
                if (!signatureAlgorithms.contains(sigAlgo)) {
                    issue.setFailureMessage("signatureAlgorithm '" + sigAlgo + "' is not allowed");
                }
            }
            // check parameters
            if (!issue.isFailed()) {
                AlgorithmIdentifier expSigAlgId = AlgorithmUtil.getSigAlgId(sigAlgo);
                if (!expSigAlgId.equals(sigAlgId)) {
                    issue.setFailureMessage("invalid parameters");
                }
            }
        } catch (NoSuchAlgorithmException ex) {
            issue.setFailureMessage("unsupported signature algorithm " + sigAlgId.getAlgorithm().getId());
        }
    }
    // notBefore encoding
    issue = new ValidationIssue("X509.NOTBEFORE.ENCODING", "notBefore encoding");
    checkTime(tbsCert.getStartDate(), issue);
    // notAfter encoding
    issue = new ValidationIssue("X509.NOTAFTER.ENCODING", "notAfter encoding");
    checkTime(tbsCert.getStartDate(), issue);
    // notBefore
    if (certProfile.isNotBeforeMidnight()) {
        issue = new ValidationIssue("X509.NOTBEFORE", "notBefore midnight");
        resultIssues.add(issue);
        Calendar cal = Calendar.getInstance(UTC);
        cal.setTime(cert.getNotBefore());
        int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        if (hourOfDay != 0 || minute != 0 || second != 0) {
            issue.setFailureMessage(" '" + cert.getNotBefore() + "' is not midnight time (UTC)");
        }
    }
    // validity
    issue = new ValidationIssue("X509.VALIDITY", "cert validity");
    resultIssues.add(issue);
    if (cert.getNotAfter().before(cert.getNotBefore())) {
        issue.setFailureMessage("notAfter must not be before notBefore");
    } else if (cert.getNotBefore().before(issuerInfo.getCaNotBefore())) {
        issue.setFailureMessage("notBefore must not be before CA's notBefore");
    } else {
        CertValidity validity = certProfile.getValidity();
        Date expectedNotAfter = validity.add(cert.getNotBefore());
        if (expectedNotAfter.getTime() > MAX_CERT_TIME_MS) {
            expectedNotAfter = new Date(MAX_CERT_TIME_MS);
        }
        if (issuerInfo.isCutoffNotAfter() && expectedNotAfter.after(issuerInfo.getCaNotAfter())) {
            expectedNotAfter = issuerInfo.getCaNotAfter();
        }
        if (Math.abs(expectedNotAfter.getTime() - cert.getNotAfter().getTime()) > 60 * SECOND) {
            issue.setFailureMessage("cert validity is not within " + validity.toString());
        }
    }
    // subjectPublicKeyInfo
    resultIssues.addAll(publicKeyChecker.checkPublicKey(bcCert.getSubjectPublicKeyInfo(), requestedPublicKey));
    // Signature
    issue = new ValidationIssue("X509.SIG", "whether certificate is signed by CA");
    resultIssues.add(issue);
    try {
        cert.verify(issuerInfo.getCert().getPublicKey(), "BC");
    } catch (Exception ex) {
        issue.setFailureMessage("invalid signature");
    }
    // issuer
    issue = new ValidationIssue("X509.ISSUER", "certificate issuer");
    resultIssues.add(issue);
    if (!cert.getIssuerX500Principal().equals(issuerInfo.getCert().getSubjectX500Principal())) {
        issue.setFailureMessage("issue in certificate does not equal the subject of CA certificate");
    }
    // subject
    resultIssues.addAll(subjectChecker.checkSubject(bcCert.getSubject(), requestedSubject));
    // issuerUniqueID
    issue = new ValidationIssue("X509.IssuerUniqueID", "issuerUniqueID");
    resultIssues.add(issue);
    if (tbsCert.getIssuerUniqueId() != null) {
        issue.setFailureMessage("is present but not permitted");
    }
    // subjectUniqueID
    issue = new ValidationIssue("X509.SubjectUniqueID", "subjectUniqueID");
    resultIssues.add(issue);
    if (tbsCert.getSubjectUniqueId() != null) {
        issue.setFailureMessage("is present but not permitted");
    }
    // extensions
    issue = new ValidationIssue("X509.GrantedSubject", "grantedSubject");
    resultIssues.add(issue);
    resultIssues.addAll(extensionsChecker.checkExtensions(bcCert, issuerInfo, requestedExtensions, requestedSubject));
    return new ValidationResult(resultIssues);
}
Also used : CertValidity(org.xipki.ca.api.profile.CertValidity) Calendar(java.util.Calendar) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ValidationResult(org.xipki.common.qa.ValidationResult) ValidationIssue(org.xipki.common.qa.ValidationIssue) LinkedList(java.util.LinkedList) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) CertprofileException(org.xipki.ca.api.profile.CertprofileException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) BigInteger(java.math.BigInteger) X509CertVersion(org.xipki.ca.api.profile.x509.X509CertVersion) BigInteger(java.math.BigInteger) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Example 29 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project pdfbox by apache.

the class PublicKeySecurityHandler method computeRecipientInfo.

private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) throws IOException, CertificateEncodingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    TBSCertificate certificate;
    try (ASN1InputStream input = new ASN1InputStream(x509certificate.getTBSCertificate())) {
        certificate = TBSCertificate.getInstance(input.readObject());
    }
    AlgorithmIdentifier algorithmId = certificate.getSubjectPublicKeyInfo().getAlgorithm();
    IssuerAndSerialNumber serial = new IssuerAndSerialNumber(certificate.getIssuer(), certificate.getSerialNumber().getValue());
    Cipher cipher;
    try {
        cipher = Cipher.getInstance(algorithmId.getAlgorithm().getId(), SecurityProvider.getProvider());
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        // should never happen, if this happens throw IOException instead
        throw new RuntimeException("Could not find a suitable javax.crypto provider", e);
    }
    cipher.init(1, x509certificate.getPublicKey());
    DEROctetString octets = new DEROctetString(cipher.doFinal(abyte0));
    RecipientIdentifier recipientId = new RecipientIdentifier(serial);
    return new KeyTransRecipientInfo(recipientId, algorithmId, octets);
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyTransRecipientInfo(org.bouncycastle.asn1.cms.KeyTransRecipientInfo) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RecipientIdentifier(org.bouncycastle.asn1.cms.RecipientIdentifier) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 30 with TBSCertificate

use of com.github.zhenwei.core.asn1.x509.TBSCertificate in project xipki by xipki.

the class OcspCertStoreFromCaDbImporter method importCert0.

// method importCert
private long importCert0(HashAlgo certhashAlgo, PreparedStatement psCert, String certsZipFile, boolean revokedOnly, List<Integer> caIds, long minId, File processLogFile, ProcessLog processLog, int numProcessedInLastProcess, ProcessLog importLog) throws Exception {
    ZipFile zipFile = new ZipFile(new File(certsZipFile));
    ZipEntry certsEntry = zipFile.getEntry("overview.json");
    CaCertstore.Certs certs;
    try {
        certs = JSON.parseObject(zipFile.getInputStream(certsEntry), StandardCharsets.UTF_8, CaCertstore.Certs.class);
    } catch (Exception ex) {
        try {
            zipFile.close();
        } catch (Exception e2) {
            LOG.error("could not close ZIP file {}: {}", certsZipFile, e2.getMessage());
            LOG.debug("could not close ZIP file " + certsZipFile, e2);
        }
        throw ex;
    }
    certs.validate();
    disableAutoCommit();
    try {
        int numProcessedEntriesInBatch = 0;
        int numImportedEntriesInBatch = 0;
        long lastSuccessfulCertId = 0;
        List<CaCertstore.Cert> list = certs.getCerts();
        final int n = list.size();
        for (int i = 0; i < n; i++) {
            if (stopMe.get()) {
                throw new InterruptedException("interrupted by the user");
            }
            CaCertstore.Cert cert = list.get(i);
            long id = cert.getId();
            lastSuccessfulCertId = id;
            if (id < minId) {
                continue;
            }
            numProcessedEntriesInBatch++;
            if (!revokedOnly || (cert.getRev() != null && cert.getRev() == 1)) {
                int caId = cert.getCaId();
                if (caIds.contains(caId)) {
                    numImportedEntriesInBatch++;
                    String filename = cert.getFile();
                    // rawcert
                    ZipEntry certZipEnty = zipFile.getEntry(filename);
                    // rawcert
                    byte[] encodedCert = IoUtil.read(zipFile.getInputStream(certZipEnty));
                    String certhash = certhashAlgo.base64Hash(encodedCert);
                    TBSCertificate tbsCert;
                    try {
                        Certificate cc = Certificate.getInstance(encodedCert);
                        tbsCert = cc.getTBSCertificate();
                    } catch (RuntimeException ex) {
                        LogUtil.error(LOG, ex, "could not parse certificate in file " + filename);
                        throw new CertificateException(ex.getMessage(), ex);
                    }
                    String subject = X509Util.cutX500Name(tbsCert.getSubject(), maxX500nameLen);
                    // cert
                    try {
                        int idx = 1;
                        psCert.setLong(idx++, id);
                        psCert.setInt(idx++, caId);
                        psCert.setString(idx++, tbsCert.getSerialNumber().getPositiveValue().toString(16));
                        psCert.setLong(idx++, cert.getUpdate());
                        psCert.setLong(idx++, tbsCert.getStartDate().getDate().getTime() / 1000);
                        psCert.setLong(idx++, tbsCert.getEndDate().getDate().getTime() / 1000);
                        setInt(psCert, idx++, cert.getRev());
                        setInt(psCert, idx++, cert.getRr());
                        setLong(psCert, idx++, cert.getRt());
                        setLong(psCert, idx++, cert.getRit());
                        psCert.setString(idx++, certhash);
                        psCert.setString(idx++, subject);
                        psCert.setNull(idx, Types.INTEGER);
                        psCert.addBatch();
                    } catch (SQLException ex) {
                        throw translate(SQL_ADD_CERT, ex);
                    }
                }
            // end if (caIds.contains(caId))
            }
            // end if (revokedOnly
            boolean isLastBlock = i == n - 1;
            if (numImportedEntriesInBatch > 0 && (numImportedEntriesInBatch % this.numCertsPerCommit == 0 || isLastBlock)) {
                try {
                    psCert.executeBatch();
                    commit("(commit import cert to OCSP)");
                } catch (Throwable th) {
                    rollback();
                    deleteCertGreatherThan(lastSuccessfulCertId, LOG);
                    if (th instanceof SQLException) {
                        throw translate(SQL_ADD_CERT, (SQLException) th);
                    } else if (th instanceof Exception) {
                        throw (Exception) th;
                    } else {
                        throw new Exception(th);
                    }
                }
                lastSuccessfulCertId = id;
                processLog.addNumProcessed(numProcessedEntriesInBatch);
                importLog.addNumProcessed(numImportedEntriesInBatch);
                numProcessedEntriesInBatch = 0;
                numImportedEntriesInBatch = 0;
                String filename = (numProcessedInLastProcess + processLog.numProcessed()) + ":" + lastSuccessfulCertId;
                echoToFile(filename, processLogFile);
                processLog.printStatus();
            } else if (isLastBlock) {
                lastSuccessfulCertId = id;
                processLog.addNumProcessed(numProcessedEntriesInBatch);
                importLog.addNumProcessed(numImportedEntriesInBatch);
                numProcessedEntriesInBatch = 0;
                numImportedEntriesInBatch = 0;
                String filename = (numProcessedInLastProcess + processLog.numProcessed()) + ":" + lastSuccessfulCertId;
                echoToFile(filename, processLogFile);
                processLog.printStatus();
            }
        // if (numImportedEntriesInBatch)
        }
        return lastSuccessfulCertId;
    } finally {
        recoverAutoCommit();
        zipFile.close();
    }
}
Also used : SQLException(java.sql.SQLException) ZipEntry(java.util.zip.ZipEntry) CertificateException(java.security.cert.CertificateException) SQLException(java.sql.SQLException) DataAccessException(org.xipki.datasource.DataAccessException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ZipFile(java.util.zip.ZipFile) ZipFile(java.util.zip.ZipFile) File(java.io.File) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Aggregations

IOException (java.io.IOException)22 TBSCertificate (org.bouncycastle.asn1.x509.TBSCertificate)22 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 CertificateException (java.security.cert.CertificateException)7 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)6 DERSequence (com.github.zhenwei.core.asn1.DERSequence)6 ByteArrayInputStream (java.io.ByteArrayInputStream)6 CertificateEncodingException (java.security.cert.CertificateEncodingException)6 X509Certificate (java.security.cert.X509Certificate)6 DEROctetString (org.bouncycastle.asn1.DEROctetString)6 ASN1EncodableVector (com.android.org.bouncycastle.asn1.ASN1EncodableVector)5 ASN1InputStream (com.android.org.bouncycastle.asn1.ASN1InputStream)5 ASN1Integer (com.android.org.bouncycastle.asn1.ASN1Integer)5 ASN1ObjectIdentifier (com.android.org.bouncycastle.asn1.ASN1ObjectIdentifier)5 DERBitString (com.android.org.bouncycastle.asn1.DERBitString)5 DERInteger (com.android.org.bouncycastle.asn1.DERInteger)5 DERSequence (com.android.org.bouncycastle.asn1.DERSequence)5 AlgorithmIdentifier (com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier)5 TBSCertificate (com.android.org.bouncycastle.asn1.x509.TBSCertificate)5 Time (com.android.org.bouncycastle.asn1.x509.Time)5