Search in sources :

Example 81 with Certificate

use of com.google.cloud.security.privateca.v1.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 82 with Certificate

use of com.google.cloud.security.privateca.v1.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)

Example 83 with Certificate

use of com.google.cloud.security.privateca.v1.Certificate in project xipki by xipki.

the class AbstractOcspRequestor method buildRequest.

// method ask
private OCSPRequest buildRequest(X509Cert caCert, BigInteger[] serialNumbers, byte[] nonce, RequestOptions requestOptions) throws OcspRequestorException {
    HashAlgo hashAlgo = requestOptions.getHashAlgorithm();
    List<SignAlgo> 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 (SignAlgo algId : prefSigAlgs) {
            vec.add(new DERSequence(algId.getAlgorithmIdentifier()));
        }
        ASN1Sequence extnValue = new DERSequence(vec);
        Extension extn;
        try {
            extn = new Extension(ObjectIdentifiers.Extn.id_pkix_ocsp_prefSigAlgs, false, new DEROctetString(extnValue));
        } catch (IOException ex) {
            throw new OcspRequestorException(ex.getMessage(), ex);
        }
        extensions.add(extn);
    }
    if (CollectionUtil.isNotEmpty(extensions)) {
        reqBuilder.setRequestExtensions(new Extensions(extensions.toArray(new Extension[0])));
    }
    try {
        DEROctetString issuerNameHash = new DEROctetString(hashAlgo.hash(caCert.getSubject().getEncoded()));
        TBSCertificate tbsCert = caCert.toBcCert().toASN1Structure().getTBSCertificate();
        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");
                    }
                    X509Cert cert = null;
                    if (StringUtil.isNotBlank(signerCertFile)) {
                        try {
                            cert = X509Util.parseCert(new File(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.getCertificate().getSubject());
            X509Cert[] certChain0 = signer.getCertificateChain();
            Certificate[] certChain = new Certificate[certChain0.length];
            for (int i = 0; i < certChain.length; i++) {
                certChain[i] = certChain0[i].toBcCert().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 : CertID(org.bouncycastle.asn1.ocsp.CertID) CertificateException(java.security.cert.CertificateException) Extensions(org.bouncycastle.asn1.x509.Extensions) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) IOException(java.io.IOException) LinkedList(java.util.LinkedList) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) CertificateEncodingException(java.security.cert.CertificateEncodingException) Extension(org.bouncycastle.asn1.x509.Extension) BigInteger(java.math.BigInteger) File(java.io.File) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 84 with Certificate

use of com.google.cloud.security.privateca.v1.Certificate in project xipki by xipki.

the class X509Cert method checkBcSignature.

private void checkBcSignature(PublicKey key, Signature signature) throws CertificateException, SignatureException, InvalidKeyException {
    Certificate c = bcInstance.toASN1Structure();
    if (!c.getSignatureAlgorithm().equals(c.getTBSCertificate().getSignature())) {
        throw new CertificateException("signature algorithm in TBS cert not same as outer cert");
    }
    signature.initVerify(key);
    try {
        signature.update(c.getTBSCertificate().getEncoded());
    } catch (IOException ex) {
        throw new CertificateException("error encoding TBSCertificate");
    }
    if (!signature.verify(c.getSignature().getBytes())) {
        throw new SignatureException("certificate does not verify with supplied key");
    }
}
Also used : CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 85 with Certificate

use of com.google.cloud.security.privateca.v1.Certificate in project xipki by xipki.

the class CrlStreamParserTest method parseCrlWithNoRevokedCerts.

@Test
public void parseCrlWithNoRevokedCerts() throws Exception {
    Certificate issuerSigner = getIssuerSigner();
    CrlStreamParser parser = getParser("no-revoked-certs.crl");
    Assert.assertEquals("version", 1, parser.getVersion());
    Assert.assertEquals("CRL number", BigInteger.valueOf(1), parser.getCrlNumber());
    Assert.assertTrue("signature", parser.verifySignature(issuerSigner.getSubjectPublicKeyInfo()));
    int numRevokedCerts = 0;
    try (RevokedCertsIterator iterator = parser.revokedCertificates()) {
        while (iterator.hasNext()) {
            iterator.next();
            numRevokedCerts++;
        }
    }
    Assert.assertEquals("#revokedCertificates", 0, numRevokedCerts);
}
Also used : CrlStreamParser(org.xipki.security.asn1.CrlStreamParser) RevokedCertsIterator(org.xipki.security.asn1.CrlStreamParser.RevokedCertsIterator) Certificate(org.bouncycastle.asn1.x509.Certificate) Test(org.junit.Test)

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 CertificateAuthorityServiceClient (com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient)24 Test (org.junit.Test)14 Operation (com.google.longrunning.Operation)13 File (java.io.File)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 SQLException (java.sql.SQLException)8 X500Name (org.bouncycastle.asn1.x500.X500Name)8 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 Date (java.util.Date)5