Search in sources :

Example 41 with JcaPEMKeyConverter

use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project ranger by apache.

the class AzureKeyVaultClientAuthenticator method readPem.

private KeyCert readPem(String path, String password) throws IOException, CertificateException, OperatorCreationException, PKCSException {
    Security.addProvider(new BouncyCastleProvider());
    PEMParser pemParser = new PEMParser(new FileReader(new File(path)));
    PrivateKey privateKey = null;
    X509Certificate cert = null;
    Object object = pemParser.readObject();
    while (object != null) {
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        if (object instanceof X509CertificateHolder) {
            cert = new JcaX509CertificateConverter().getCertificate((X509CertificateHolder) object);
        }
        if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            PKCS8EncryptedPrivateKeyInfo pinfo = (PKCS8EncryptedPrivateKeyInfo) object;
            InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password.toCharArray());
            PrivateKeyInfo info = pinfo.decryptPrivateKeyInfo(provider);
            privateKey = converter.getPrivateKey(info);
        }
        if (object instanceof PrivateKeyInfo) {
            privateKey = converter.getPrivateKey((PrivateKeyInfo) object);
        }
        object = pemParser.readObject();
    }
    KeyCert keycert = new KeyCert();
    keycert.setCertificate(cert);
    keycert.setKey(privateKey);
    pemParser.close();
    return keycert;
}
Also used : PrivateKey(java.security.PrivateKey) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) X509Certificate(java.security.cert.X509Certificate) PEMParser(org.bouncycastle.openssl.PEMParser) InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) FileReader(java.io.FileReader) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) File(java.io.File) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 42 with JcaPEMKeyConverter

use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter 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 43 with JcaPEMKeyConverter

use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project athenz by yahoo.

the class Utils method createKeyStore.

/**
 * Create a {@link KeyStore} from suppliers of {@link InputStream} for cert and key.
 *
 * @param athenzPublicCertInputStream      Supplier of the certificate input stream
 * @param athenzPublicCertLocationSupplier Supplier of the location of the certificate (for error logging)
 * @param athenzPrivateKeyInputStream      Supplier of the private key input stream
 * @param athenzPrivateKeyLocationSupplier Supplier of the location of the certificate (for error logging)
 * @return a KeyStore with loaded key and certificate
 * @throws KeyRefresherException in case of any key refresher errors processing the request
 * @throws IOException in case of any errors with reading files
 */
public static KeyStore createKeyStore(final Supplier<InputStream> athenzPublicCertInputStream, final Supplier<String> athenzPublicCertLocationSupplier, final Supplier<InputStream> athenzPrivateKeyInputStream, final Supplier<String> athenzPrivateKeyLocationSupplier) throws IOException, KeyRefresherException {
    List<? extends Certificate> certificates;
    PrivateKey privateKey;
    KeyStore keyStore = null;
    try (InputStream publicCertStream = athenzPublicCertInputStream.get();
        InputStream privateKeyStream = athenzPrivateKeyInputStream.get();
        PEMParser pemParser = new PEMParser(new InputStreamReader(privateKeyStream))) {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
        Object key = pemParser.readObject();
        if (key instanceof PEMKeyPair) {
            PrivateKeyInfo pKeyInfo = ((PEMKeyPair) key).getPrivateKeyInfo();
            privateKey = pemConverter.getPrivateKey(pKeyInfo);
        } else if (key instanceof PrivateKeyInfo) {
            privateKey = pemConverter.getPrivateKey((PrivateKeyInfo) key);
        } else {
            throw new KeyRefresherException("Unknown object type: " + (key == null ? "null" : key.getClass().getName()));
        }
        // noinspection unchecked
        certificates = (List<? extends Certificate>) cf.generateCertificates(publicCertStream);
        if (certificates.isEmpty()) {
            throw new KeyRefresherException("Certificate file contains empty certificate or an invalid certificate.");
        }
        // We are going to assume that the first one is the main certificate which will be used for the alias
        String alias = ((X509Certificate) certificates.get(0)).getSubjectX500Principal().getName();
        if (LOG.isDebugEnabled()) {
            LOG.debug("{} number of certificates found. Using {} alias to create the keystore", certificates.size(), alias);
        }
        keyStore = KeyStore.getInstance(DEFAULT_KEYSTORE_TYPE);
        keyStore.load(null);
        keyStore.setKeyEntry(alias, privateKey, KEYSTORE_PASSWORD, certificates.toArray((Certificate[]) new X509Certificate[certificates.size()]));
    } catch (CertificateException | NoSuchAlgorithmException ex) {
        String keyStoreFailMsg = "Unable to load " + athenzPublicCertLocationSupplier.get() + " as a KeyStore. Please check the validity of the file.";
        throw new KeyRefresherException(keyStoreFailMsg, ex);
    } catch (KeyStoreException ex) {
        LOG.error("No Provider supports a KeyStoreSpi implementation for the specified type.", ex);
    }
    return keyStore;
}
Also used : JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) CertificateException(java.security.cert.CertificateException) CertificateFactory(java.security.cert.CertificateFactory) PEMParser(org.bouncycastle.openssl.PEMParser) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 44 with JcaPEMKeyConverter

use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter 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 45 with JcaPEMKeyConverter

use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project incubator-pulsar by apache.

the class MessageCrypto method loadPublicKey.

private PublicKey loadPublicKey(byte[] keyBytes) throws Exception {
    Reader keyReader = new StringReader(new String(keyBytes));
    PublicKey publicKey = null;
    try (org.bouncycastle.openssl.PEMParser pemReader = new org.bouncycastle.openssl.PEMParser(keyReader)) {
        Object pemObj = pemReader.readObject();
        JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
        SubjectPublicKeyInfo keyInfo = null;
        X9ECParameters ecParam = null;
        if (pemObj instanceof ASN1ObjectIdentifier) {
            // make sure this is EC Parameter we're handling. In which case
            // we'll store it and read the next object which should be our
            // EC Public Key
            ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier) pemObj;
            ecParam = ECNamedCurveTable.getByOID(ecOID);
            if (ecParam == null) {
                throw new PEMException("Unable to find EC Parameter for the given curve oid: " + ((ASN1ObjectIdentifier) pemObj).getId());
            }
            pemObj = pemReader.readObject();
        } else if (pemObj instanceof X9ECParameters) {
            ecParam = (X9ECParameters) pemObj;
            pemObj = pemReader.readObject();
        }
        if (pemObj instanceof org.bouncycastle.cert.X509CertificateHolder) {
            keyInfo = ((org.bouncycastle.cert.X509CertificateHolder) pemObj).getSubjectPublicKeyInfo();
        } else {
            keyInfo = (SubjectPublicKeyInfo) pemObj;
        }
        publicKey = pemConverter.getPublicKey(keyInfo);
        if (ecParam != null && ECDSA.equals(publicKey.getAlgorithm())) {
            ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(), ecParam.getH(), ecParam.getSeed());
            KeyFactory keyFactory = KeyFactory.getInstance(ECDSA, BouncyCastleProvider.PROVIDER_NAME);
            ECPublicKeySpec keySpec = new ECPublicKeySpec(((BCECPublicKey) publicKey).getQ(), ecSpec);
            publicKey = (PublicKey) keyFactory.generatePublic(keySpec);
        }
    } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException e) {
        throw new Exception(e);
    }
    return publicKey;
}
Also used : X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) Reader(java.io.Reader) CryptoKeyReader(org.apache.pulsar.client.api.CryptoKeyReader) StringReader(java.io.StringReader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) ByteString(com.google.protobuf.ByteString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) ECPublicKeySpec(org.bouncycastle.jce.spec.ECPublicKeySpec) PEMParser(org.bouncycastle.openssl.PEMParser) StringReader(java.io.StringReader) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory) BCECPublicKey(org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey) PublicKey(java.security.PublicKey) PEMParser(org.bouncycastle.openssl.PEMParser) IOException(java.io.IOException) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) ShortBufferException(javax.crypto.ShortBufferException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) CryptoException(org.apache.pulsar.client.api.PulsarClientException.CryptoException) PEMException(org.bouncycastle.openssl.PEMException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchProviderException(java.security.NoSuchProviderException) ECParameterSpec(org.bouncycastle.jce.spec.ECParameterSpec) PEMException(org.bouncycastle.openssl.PEMException) NoSuchProviderException(java.security.NoSuchProviderException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

JcaPEMKeyConverter (org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter)55 PEMParser (org.bouncycastle.openssl.PEMParser)48 PEMKeyPair (org.bouncycastle.openssl.PEMKeyPair)31 PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)26 IOException (java.io.IOException)20 InputStreamReader (java.io.InputStreamReader)19 PrivateKey (java.security.PrivateKey)19 Reader (java.io.Reader)15 JcePEMDecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder)14 PKCS8EncryptedPrivateKeyInfo (org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)14 StringReader (java.io.StringReader)13 PEMEncryptedKeyPair (org.bouncycastle.openssl.PEMEncryptedKeyPair)13 InputStream (java.io.InputStream)12 InputDecryptorProvider (org.bouncycastle.operator.InputDecryptorProvider)12 PEMDecryptorProvider (org.bouncycastle.openssl.PEMDecryptorProvider)11 JceOpenSSLPKCS8DecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder)11 BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)10 KeyPair (java.security.KeyPair)9 PemObject (org.bouncycastle.util.io.pem.PemObject)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6