Search in sources :

Example 71 with Certificate

use of com.android.apksig.internal.x509.Certificate in project jasn1 by openmuc.

the class OtherSignedNotification method decode.

public int decode(InputStream is, boolean withTag) throws IOException {
    int tlByteCount = 0;
    int vByteCount = 0;
    BerTag berTag = new BerTag();
    if (withTag) {
        tlByteCount += tag.decodeAndCheck(is);
    }
    BerLength length = new BerLength();
    tlByteCount += length.decode(is);
    int lengthVal = length.val;
    vByteCount += berTag.decode(is);
    if (berTag.equals(NotificationMetadata.tag)) {
        tbsOtherNotification = new NotificationMetadata();
        vByteCount += tbsOtherNotification.decode(is, false);
        vByteCount += berTag.decode(is);
    } else {
        throw new IOException("Tag does not match mandatory sequence component.");
    }
    if (berTag.equals(BerTag.APPLICATION_CLASS, BerTag.PRIMITIVE, 55)) {
        euiccNotificationSignature = new BerOctetString();
        vByteCount += euiccNotificationSignature.decode(is, false);
        vByteCount += berTag.decode(is);
    } else {
        throw new IOException("Tag does not match mandatory sequence component.");
    }
    if (berTag.equals(Certificate.tag)) {
        euiccCertificate = new Certificate();
        vByteCount += euiccCertificate.decode(is, false);
        vByteCount += berTag.decode(is);
    } else {
        throw new IOException("Tag does not match mandatory sequence component.");
    }
    if (berTag.equals(Certificate.tag)) {
        eumCertificate = new Certificate();
        vByteCount += eumCertificate.decode(is, false);
        if (lengthVal >= 0 && vByteCount == lengthVal) {
            return tlByteCount + vByteCount;
        }
        vByteCount += berTag.decode(is);
    } else {
        throw new IOException("Tag does not match mandatory sequence component.");
    }
    if (lengthVal < 0) {
        while (!berTag.equals(0, 0, 0)) {
            vByteCount += DecodeUtil.decodeUnknownComponent(is);
            vByteCount += berTag.decode(is);
        }
        vByteCount += BerLength.readEocByte(is);
        return tlByteCount + vByteCount;
    } else {
        while (vByteCount < lengthVal) {
            vByteCount += DecodeUtil.decodeUnknownComponent(is);
            if (vByteCount == lengthVal) {
                return tlByteCount + vByteCount;
            }
            vByteCount += berTag.decode(is);
        }
    }
    throw new IOException("Unexpected end of sequence, length tag: " + lengthVal + ", bytes decoded: " + vByteCount);
}
Also used : IOException(java.io.IOException) Certificate(com.beanit.asn1bean.compiler.pkix1explicit88.Certificate)

Example 72 with Certificate

use of com.android.apksig.internal.x509.Certificate in project jasn1 by openmuc.

the class PrepareDownloadRequest method decode.

public int decode(InputStream is, boolean withTag) throws IOException {
    int tlByteCount = 0;
    int vByteCount = 0;
    BerTag berTag = new BerTag();
    if (withTag) {
        tlByteCount += tag.decodeAndCheck(is);
    }
    BerLength length = new BerLength();
    tlByteCount += length.decode(is);
    int lengthVal = length.val;
    vByteCount += berTag.decode(is);
    if (berTag.equals(SmdpSigned2.tag)) {
        smdpSigned2 = new SmdpSigned2();
        vByteCount += smdpSigned2.decode(is, false);
        vByteCount += berTag.decode(is);
    } else {
        throw new IOException("Tag does not match mandatory sequence component.");
    }
    if (berTag.equals(BerTag.APPLICATION_CLASS, BerTag.PRIMITIVE, 55)) {
        smdpSignature2 = new BerOctetString();
        vByteCount += smdpSignature2.decode(is, false);
        vByteCount += berTag.decode(is);
    } else {
        throw new IOException("Tag does not match mandatory sequence component.");
    }
    if (berTag.equals(Octet32.tag)) {
        hashCc = new Octet32();
        vByteCount += hashCc.decode(is, false);
        vByteCount += berTag.decode(is);
    }
    if (berTag.equals(Certificate.tag)) {
        smdpCertificate = new Certificate();
        vByteCount += smdpCertificate.decode(is, false);
        if (lengthVal >= 0 && vByteCount == lengthVal) {
            return tlByteCount + vByteCount;
        }
        vByteCount += berTag.decode(is);
    } else {
        throw new IOException("Tag does not match mandatory sequence component.");
    }
    if (lengthVal < 0) {
        while (!berTag.equals(0, 0, 0)) {
            vByteCount += DecodeUtil.decodeUnknownComponent(is);
            vByteCount += berTag.decode(is);
        }
        vByteCount += BerLength.readEocByte(is);
        return tlByteCount + vByteCount;
    } else {
        while (vByteCount < lengthVal) {
            vByteCount += DecodeUtil.decodeUnknownComponent(is);
            if (vByteCount == lengthVal) {
                return tlByteCount + vByteCount;
            }
            vByteCount += berTag.decode(is);
        }
    }
    throw new IOException("Unexpected end of sequence, length tag: " + lengthVal + ", bytes decoded: " + vByteCount);
}
Also used : IOException(java.io.IOException) Certificate(com.beanit.asn1bean.compiler.pkix1explicit88.Certificate)

Example 73 with Certificate

use of com.android.apksig.internal.x509.Certificate 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)

Example 74 with Certificate

use of com.android.apksig.internal.x509.Certificate in project xipki by xipki.

the class OcspCertstoreDbImporter method importIssuer.

private void importIssuer(List<OcspCertstore.Issuer> issuers) throws DataAccessException, CertificateException, IOException {
    if (CollectionUtil.isEmpty(issuers)) {
        return;
    }
    System.out.println("importing table ISSUER");
    PreparedStatement ps = prepareStatement(SQL_ADD_ISSUER);
    try {
        for (OcspCertstore.Issuer issuer : issuers) {
            try {
                String certFilename = issuer.getCertFile();
                String b64Cert = StringUtil.toUtf8String(IoUtil.read(new File(baseDir, certFilename)));
                byte[] encodedCert = Base64.decode(b64Cert);
                Certificate cert;
                try {
                    cert = Certificate.getInstance(encodedCert);
                } catch (RuntimeException ex) {
                    LOG.error("could not parse certificate of issuer {}", issuer.getId());
                    LOG.debug("could not parse certificate of issuer " + issuer.getId(), ex);
                    throw new CertificateException(ex.getMessage(), ex);
                }
                int idx = 1;
                ps.setInt(idx++, issuer.getId());
                ps.setString(idx++, X509Util.cutX500Name(cert.getSubject(), maxX500nameLen));
                ps.setLong(idx++, cert.getTBSCertificate().getStartDate().getDate().getTime() / 1000);
                ps.setLong(idx++, cert.getTBSCertificate().getEndDate().getDate().getTime() / 1000);
                ps.setString(idx++, sha1(encodedCert));
                ps.setString(idx++, issuer.getRevInfo());
                ps.setString(idx++, b64Cert);
                if (issuer.getCrlId() == null) {
                    ps.setNull(idx, Types.INTEGER);
                } else {
                    ps.setInt(idx, issuer.getCrlId());
                }
                ps.execute();
            } catch (SQLException ex) {
                System.err.println("could not import issuer with id=" + issuer.getId());
                throw translate(SQL_ADD_ISSUER, ex);
            } catch (CertificateException ex) {
                System.err.println("could not import issuer with id=" + issuer.getId());
                throw ex;
            }
        }
    } finally {
        releaseResources(ps, null);
    }
    System.out.println(" imported table ISSUER");
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) CertificateException(java.security.cert.CertificateException) File(java.io.File) ZipFile(java.util.zip.ZipFile) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 75 with Certificate

use of com.android.apksig.internal.x509.Certificate in project keystore-explorer by kaikramer.

the class GenerateCsrAction method doAction.

/**
 * Do action.
 */
@Override
protected void doAction() {
    File csrFile = null;
    FileOutputStream fos = null;
    try {
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStoreState currentState = history.getCurrentState();
        Provider provider = history.getExplicitProvider();
        String alias = kseFrame.getSelectedEntryAlias();
        Password password = getEntryPassword(alias, currentState);
        if (password == null) {
            return;
        }
        KeyStore keyStore = currentState.getKeyStore();
        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
        String keyPairAlg = privateKey.getAlgorithm();
        KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey);
        if (keyPairType == null) {
            throw new CryptoException(MessageFormat.format(res.getString("GenerateCsrAction.NoCsrForKeyPairAlg.message"), keyPairAlg));
        }
        // determine dir of current keystore as proposal for CSR file location
        String path = CurrentDirectory.get().getAbsolutePath();
        File keyStoreFile = history.getFile();
        if (keyStoreFile != null) {
            path = keyStoreFile.getAbsoluteFile().getParent();
        }
        X509Certificate firstCertInChain = X509CertUtil.orderX509CertChain(X509CertUtil.convertCertificates(keyStore.getCertificateChain(alias)))[0];
        X500Principal subjectDN = firstCertInChain.getSubjectX500Principal();
        DGenerateCsr dGenerateCsr = new DGenerateCsr(frame, alias, subjectDN, privateKey, keyPairType, path);
        dGenerateCsr.setLocationRelativeTo(frame);
        dGenerateCsr.setVisible(true);
        if (!dGenerateCsr.generateSelected()) {
            return;
        }
        csrFile = dGenerateCsr.getCsrFile();
        subjectDN = dGenerateCsr.getSubjectDN();
        CsrType format = dGenerateCsr.getFormat();
        SignatureType signatureType = dGenerateCsr.getSignatureType();
        String challenge = dGenerateCsr.getChallenge();
        String unstructuredName = dGenerateCsr.getUnstructuredName();
        boolean useCertificateExtensions = dGenerateCsr.isAddExtensionsWanted();
        PublicKey publicKey = firstCertInChain.getPublicKey();
        // add extensionRequest attribute with all extensions from the certificate
        Extensions extensions = null;
        if (useCertificateExtensions) {
            Certificate certificate = Certificate.getInstance(firstCertInChain.getEncoded());
            extensions = certificate.getTBSCertificate().getExtensions();
        }
        fos = new FileOutputStream(csrFile);
        if (format == CsrType.PKCS10) {
            String csr = Pkcs10Util.getCsrEncodedDerPem(Pkcs10Util.generateCsr(subjectDN, publicKey, privateKey, signatureType, challenge, unstructuredName, extensions, provider));
            fos.write(csr.getBytes());
        } else {
            SpkacSubject subject = new SpkacSubject(X500NameUtils.x500PrincipalToX500Name(firstCertInChain.getSubjectX500Principal()));
            // TODO handle other providers (PKCS11 etc)
            Spkac spkac = new Spkac(challenge, signatureType, subject, publicKey, privateKey);
            spkac.output(fos);
        }
        JOptionPane.showMessageDialog(frame, res.getString("GenerateCsrAction.CsrGenerationSuccessful.message"), res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.INFORMATION_MESSAGE);
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(frame, MessageFormat.format(res.getString("GenerateCsrAction.NoWriteFile.message"), csrFile), res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.WARNING_MESSAGE);
    } catch (Exception ex) {
        DError.displayError(frame, ex);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}
Also used : KeyStoreState(org.kse.utilities.history.KeyStoreState) SpkacSubject(org.kse.crypto.csr.spkac.SpkacSubject) KeyStoreHistory(org.kse.utilities.history.KeyStoreHistory) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) FileNotFoundException(java.io.FileNotFoundException) SignatureType(org.kse.crypto.signing.SignatureType) Extensions(org.bouncycastle.asn1.x509.Extensions) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) CryptoException(org.kse.crypto.CryptoException) FileNotFoundException(java.io.FileNotFoundException) Provider(java.security.Provider) CsrType(org.kse.crypto.csr.CsrType) Spkac(org.kse.crypto.csr.spkac.Spkac) FileOutputStream(java.io.FileOutputStream) X500Principal(javax.security.auth.x500.X500Principal) DGenerateCsr(org.kse.gui.dialogs.DGenerateCsr) KeyPairType(org.kse.crypto.keypair.KeyPairType) CryptoException(org.kse.crypto.CryptoException) File(java.io.File) Password(org.kse.crypto.Password) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Aggregations

Certificate (org.bouncycastle.asn1.x509.Certificate)53 IOException (java.io.IOException)40 X509Certificate (java.security.cert.X509Certificate)37 CertificateException (java.security.cert.CertificateException)27 File (java.io.File)12 Test (org.junit.Test)11 BigInteger (java.math.BigInteger)9 CertificateEncodingException (java.security.cert.CertificateEncodingException)9 TBSCertificate (org.bouncycastle.asn1.x509.TBSCertificate)9 Test (org.junit.jupiter.api.Test)9 Certificate (com.google.cloud.security.privateca.v1.Certificate)8 CertificateAuthorityServiceClient (com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient)8 SQLException (java.sql.SQLException)8 X500Name (org.bouncycastle.asn1.x500.X500Name)8 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)7 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)7 Certificate (com.beanit.asn1bean.compiler.pkix1explicit88.Certificate)6 Extension (org.bouncycastle.asn1.x509.Extension)6 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)6 ArrayList (java.util.ArrayList)5