Search in sources :

Example 66 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project box-java-sdk by box.

the class BoxDeveloperEditionAPIConnection method decryptPrivateKey.

private PrivateKey decryptPrivateKey() {
    PrivateKey decryptedPrivateKey;
    try {
        PEMParser keyReader = new PEMParser(new StringReader(this.privateKey));
        Object keyPair = keyReader.readObject();
        keyReader.close();
        if (keyPair instanceof PrivateKeyInfo) {
            PrivateKeyInfo keyInfo = (PrivateKeyInfo) keyPair;
            decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
        } else if (keyPair instanceof PEMEncryptedKeyPair) {
            JcePEMDecryptorProviderBuilder builder = new JcePEMDecryptorProviderBuilder();
            PEMDecryptorProvider decryptionProvider = builder.build(this.privateKeyPassword.toCharArray());
            keyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptionProvider);
            PrivateKeyInfo keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
            decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
        } else if (keyPair instanceof PKCS8EncryptedPrivateKeyInfo) {
            InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder().setProvider("BC").build(this.privateKeyPassword.toCharArray());
            PrivateKeyInfo keyInfo = ((PKCS8EncryptedPrivateKeyInfo) keyPair).decryptPrivateKeyInfo(pkcs8Prov);
            decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
        } else {
            PrivateKeyInfo keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
            decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
        }
    } catch (IOException e) {
        throw new BoxAPIException("Error parsing private key for Box Developer Edition.", e);
    } catch (OperatorCreationException e) {
        throw new BoxAPIException("Error parsing PKCS#8 private key for Box Developer Edition.", e);
    } catch (PKCSException e) {
        throw new BoxAPIException("Error parsing PKCS private key for Box Developer Edition.", e);
    }
    return decryptedPrivateKey;
}
Also used : PrivateKey(java.security.PrivateKey) PEMDecryptorProvider(org.bouncycastle.openssl.PEMDecryptorProvider) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) IOException(java.io.IOException) PKCSException(org.bouncycastle.pkcs.PKCSException) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMParser(org.bouncycastle.openssl.PEMParser) InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) StringReader(java.io.StringReader) JsonObject(com.eclipsesource.json.JsonObject) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)

Example 67 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project jmeter by apache.

the class SMIMEAssertion method verifySignature.

private static void verifySignature(SignerInformation signer, AssertionResult res, X509CertificateHolder cert) throws CertificateException, CMSException {
    SignerInformationVerifier verifier = null;
    try {
        verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert);
    } catch (OperatorCreationException e) {
        log.error("Can't create a provider.", e);
    }
    if (verifier == null || !signer.verify(verifier)) {
        res.setFailure(true);
        res.setFailureMessage("Signature is invalid");
    }
}
Also used : JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) SignerInformationVerifier(org.bouncycastle.cms.SignerInformationVerifier) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 68 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project ddf by codice.

the class OcspChecker method generateOcspRequest.

/**
 * Creates an {@link OCSPReq} to send to the OCSP server for the given certificate.
 *
 * @param cert - the certificate to verify
 * @return the created OCSP request
 * @throws OcspCheckerException after posting an alert to the admin console, if any error occurs
 */
@VisibleForTesting
OCSPReq generateOcspRequest(Certificate cert) throws OcspCheckerException {
    try {
        X509CertificateHolder issuerCert = resolveIssuerCertificate(cert);
        JcaDigestCalculatorProviderBuilder digestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder();
        DigestCalculatorProvider digestCalculatorProvider = digestCalculatorProviderBuilder.build();
        DigestCalculator digestCalculator = digestCalculatorProvider.get(CertificateID.HASH_SHA1);
        CertificateID certId = new CertificateID(digestCalculator, issuerCert, cert.getSerialNumber().getValue());
        OCSPReqBuilder ocspReqGenerator = new OCSPReqBuilder();
        ocspReqGenerator.addRequest(certId);
        return ocspReqGenerator.build();
    } catch (OCSPException | OperatorCreationException e) {
        throw new OcspCheckerException("Unable to create an OCSP request." + NOT_VERIFIED_MSG, e);
    }
}
Also used : DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) DigestCalculator(org.bouncycastle.operator.DigestCalculator) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 69 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project zm-mailbox by Zimbra.

the class MobileConfigFormatter method signConfig.

private byte[] signConfig(Domain domain, Server server, byte[] config) {
    byte[] signedConfig = config;
    String certStr = null;
    String pvtKeyStr = null;
    if (domain != null) {
        certStr = domain.getSSLCertificate();
        pvtKeyStr = domain.getSSLPrivateKey();
        if (StringUtil.isNullOrEmpty(certStr) && server != null) {
            certStr = server.getSSLCertificate();
            pvtKeyStr = server.getSSLPrivateKey();
        }
    }
    if (!StringUtil.isNullOrEmpty(certStr) && !StringUtil.isNullOrEmpty(pvtKeyStr)) {
        try (InputStream targetStream = new ByteArrayInputStream(certStr.getBytes())) {
            CertificateFactory certFactory = CertificateFactory.getInstance(SmimeConstants.PUB_CERT_TYPE);
            X509Certificate cert = (X509Certificate) certFactory.generateCertificate(targetStream);
            StringReader reader = new StringReader(pvtKeyStr);
            PrivateKey privateKey = null;
            try (PEMParser pp = new PEMParser(reader)) {
                Object pemKP = pp.readObject();
                JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
                PrivateKeyInfo pkInfo = null;
                if (pemKP instanceof PrivateKeyInfo) {
                    pkInfo = (PrivateKeyInfo) pemKP;
                } else {
                    pkInfo = ((PEMKeyPair) pemKP).getPrivateKeyInfo();
                }
                privateKey = converter.getPrivateKey(pkInfo);
            }
            signedConfig = DataSigner.signData(config, cert, privateKey);
        } catch (IOException | CertificateException | OperatorCreationException | CMSException e) {
            ZimbraLog.misc.debug("exception occurred during signing config", e);
        }
    } else {
        ZimbraLog.misc.debug("SSLCertificate/SSLPrivateKey is not set, config will not be signed");
    }
    return signedConfig;
}
Also used : PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) PEMParser(org.bouncycastle.openssl.PEMParser) ByteArrayInputStream(java.io.ByteArrayInputStream) StringReader(java.io.StringReader) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) CMSException(org.bouncycastle.cms.CMSException)

Example 70 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project athenz by yahoo.

the class Crypto method generateX509Certificate.

public static X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq, PrivateKey caPrivateKey, X500Name issuer, int validityTimeout, boolean basicConstraints) {
    // set validity for the given number of minutes from now
    Date notBefore = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(notBefore);
    cal.add(Calendar.MINUTE, validityTimeout);
    Date notAfter = cal.getTime();
    // Generate self-signed certificate
    X509Certificate cert;
    try {
        JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(certReq);
        PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey();
        X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuer, BigInteger.valueOf(System.currentTimeMillis()), notBefore, notAfter, certReq.getSubject(), publicKey).addExtension(Extension.basicConstraints, false, new BasicConstraints(basicConstraints)).addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment)).addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
        // see if we have the dns/rfc822/ip address extensions specified in the csr
        ArrayList<GeneralName> altNames = new ArrayList<>();
        Attribute[] certAttributes = jcaPKCS10CertificationRequest.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (certAttributes != null && certAttributes.length > 0) {
            for (Attribute attribute : certAttributes) {
                Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                // /CLOVER:OFF
                if (gns == null) {
                    continue;
                }
                // /CLOVER:ON
                GeneralName[] names = gns.getNames();
                for (GeneralName name : names) {
                    switch(name.getTagNo()) {
                        case GeneralName.dNSName:
                        case GeneralName.iPAddress:
                        case GeneralName.rfc822Name:
                        case GeneralName.uniformResourceIdentifier:
                            altNames.add(name);
                            break;
                    }
                }
            }
            if (!altNames.isEmpty()) {
                caBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(altNames.toArray(new GeneralName[0])));
            }
        }
        String signatureAlgorithm = getSignatureAlgorithm(caPrivateKey.getAlgorithm(), SHA256);
        ContentSigner caSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC_PROVIDER).build(caPrivateKey);
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC_PROVIDER);
        cert = converter.getCertificate(caBuilder.build(caSigner));
    // /CLOVER:OFF
    } catch (CertificateException ex) {
        LOG.error("generateX509Certificate: Caught CertificateException when generating certificate: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error("generateX509Certificate: Caught OperatorCreationException when creating JcaContentSignerBuilder: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (InvalidKeyException ex) {
        LOG.error("generateX509Certificate: Caught InvalidKeySpecException, invalid key spec is being used: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error("generateX509Certificate: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (Exception ex) {
        LOG.error("generateX509Certificate: unable to generate X509 Certificate: {}", ex.getMessage());
        throw new CryptoException("Unable to generate X509 Certificate");
    }
    // /CLOVER:ON
    return cert;
}
Also used : Attribute(org.bouncycastle.asn1.pkcs.Attribute) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) Extensions(org.bouncycastle.asn1.x509.Extensions) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) X509KeyUsage(org.bouncycastle.jce.X509KeyUsage) JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) BCECPublicKey(org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey) ContentSigner(org.bouncycastle.operator.ContentSigner) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CMSException(org.bouncycastle.cms.CMSException) PKCSException(org.bouncycastle.pkcs.PKCSException) PEMException(org.bouncycastle.openssl.PEMException) UnknownHostException(java.net.UnknownHostException) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Aggregations

OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)93 IOException (java.io.IOException)52 ContentSigner (org.bouncycastle.operator.ContentSigner)40 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)38 CertificateException (java.security.cert.CertificateException)32 X509Certificate (java.security.cert.X509Certificate)31 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)23 Date (java.util.Date)21 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)20 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)17 CMSException (org.bouncycastle.cms.CMSException)17 X500Name (org.bouncycastle.asn1.x500.X500Name)16 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)16 GeneralName (org.bouncycastle.asn1.x509.GeneralName)15 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)14 CMSSignedData (org.bouncycastle.cms.CMSSignedData)12 GeneralSecurityException (java.security.GeneralSecurityException)11 BigInteger (java.math.BigInteger)10 NoSuchProviderException (java.security.NoSuchProviderException)10 CertificateEncodingException (java.security.cert.CertificateEncodingException)10