Search in sources :

Example 51 with PrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.PrivateKeyInfo in project yorc-a4c-plugin by ystia.

the class RestClient method setProviderConfiguration.

public void setProviderConfiguration(ProviderConfig providerConfiguration) throws PluginConfigurationException {
    this.providerConfiguration = providerConfiguration;
    log.debug("setProviderConfiguration YorcURL=" + providerConfiguration.getUrlYorc());
    RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout(((Long) CONNECTION_TIMEOUT).intValue()).setSocketTimeout(((Long) SOCKET_TIMEOUT).intValue()).setConnectionRequestTimeout(((Long) SOCKET_TIMEOUT).intValue()).build();
    CloseableHttpClient httpClient;
    if (Boolean.TRUE.equals(providerConfiguration.getInsecureTLS())) {
        SSLContext sslContext;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, (chain, authType) -> true).build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
            e.printStackTrace();
            throw new PluginConfigurationException("Failed to create SSL socket factory", e);
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build();
        PoolingHttpClientConnectionManager poolHttpConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        configurePoolingHttpClientConnectionManager(poolHttpConnManager);
        httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(poolHttpConnManager).setDefaultRequestConfig(clientConfig).setSslcontext(sslContext).build();
    } else if (providerConfiguration.getUrlYorc().startsWith("https")) {
        SSLContext sslContext;
        // on system default keystore and truststore
        if (providerConfiguration.getCaCertificate().isEmpty() || providerConfiguration.getClientCertificate().isEmpty() || providerConfiguration.getClientKey().isEmpty()) {
            log.warn("Missing CA|Client certificate|Client key in plugin configuration, will use system defaults");
            if (System.getProperty("javax.net.ssl.keyStore") == null || System.getProperty("javax.net.ssl.keyStorePassword") == null) {
                log.warn("Using SSL but you didn't provide client keystore and password. This means that if required by Yorc client authentication will fail.\n" + "Please use -Djavax.net.ssl.keyStore <keyStorePath> -Djavax.net.ssl.keyStorePassword <password> while starting java VM");
            }
            if (System.getProperty("javax.net.ssl.trustStore") == null || System.getProperty("javax.net.ssl.trustStorePassword") == null) {
                log.warn("You didn't provide client trustore and password. Using defalut one \n" + "Please use -Djavax.net.ssl.trustStore <trustStorePath> -Djavax.net.ssl.trustStorePassword <password> while starting java VM");
            }
            sslContext = SSLContexts.createSystemDefault();
        } else {
            // Create a key store containing CA and client key/certificate provided
            // in the plugin configuration
            KeyStore keystore;
            try {
                // Create the CA certificate from its configuration string value
                CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                ByteArrayInputStream inputStream = new ByteArrayInputStream(providerConfiguration.getCaCertificate().getBytes());
                X509Certificate trustedCert = (X509Certificate) certFactory.generateCertificate(inputStream);
                inputStream.close();
                // Create the client private key from its configuration string value
                String keyContent = providerConfiguration.getClientKey().replaceFirst("-----BEGIN PRIVATE KEY-----\n", "").replaceFirst("\n-----END PRIVATE KEY-----", "").trim();
                PKCS8EncodedKeySpec clientKeySpec = new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(keyContent));
                // Getting the key algorithm
                ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(clientKeySpec.getEncoded()));
                PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
                bIn.close();
                String algorithm = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();
                // Workaround for a missing algorithm OID in the list of default providers
                if ("1.2.840.113549.1.1.1".equals(algorithm)) {
                    algorithm = "RSA";
                }
                KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
                PrivateKey clientKey = keyFactory.generatePrivate(clientKeySpec);
                // Create the client certificate from its configuration string value
                inputStream = new ByteArrayInputStream(providerConfiguration.getClientCertificate().getBytes());
                Certificate clientCert = certFactory.generateCertificate(inputStream);
                inputStream.close();
                // Create an empty keystore
                keystore = KeyStore.getInstance(KeyStore.getDefaultType());
                keystore.load(null);
                // Add the certificate authority
                keystore.setCertificateEntry(trustedCert.getSubjectX500Principal().getName(), trustedCert);
                // Add client key/certificate and chain to the Key store
                Certificate[] chain = { clientCert, trustedCert };
                keystore.setKeyEntry("Yorc Client", clientKey, "yorc".toCharArray(), chain);
            } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException | KeyStoreException e) {
                e.printStackTrace();
                throw new PluginConfigurationException("Failed to create keystore", e);
            }
            // Create a SSL context using this Key Store
            try {
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(keystore);
                sslContext = SSLContext.getInstance("TLS");
                KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
                kmf.init(keystore, "yorc".toCharArray());
                sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
            } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
                e.printStackTrace();
                throw new PluginConfigurationException("Failed to create SSL context", e);
            }
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build();
        PoolingHttpClientConnectionManager poolHttpConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        configurePoolingHttpClientConnectionManager(poolHttpConnManager);
        httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(poolHttpConnManager).setDefaultRequestConfig(clientConfig).setSslcontext(sslContext).build();
    } else {
        PoolingHttpClientConnectionManager poolHttpConnManager = new PoolingHttpClientConnectionManager();
        configurePoolingHttpClientConnectionManager(poolHttpConnManager);
        httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(poolHttpConnManager).setDefaultRequestConfig(clientConfig).build();
    }
    // Instantiate restTemplate
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    restTemplate = new RestTemplate(requestFactory);
    // Display deployments
    try {
        logDeployments();
    } catch (Exception e) {
        log.warn("Unable to retrieve deployments due to: {}", e.getMessage());
        e.printStackTrace();
        throw new PluginConfigurationException("Failed to connect to yorc", e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) CertificateFactory(java.security.cert.CertificateFactory) KeyManagementException(java.security.KeyManagementException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) KeyFactory(java.security.KeyFactory) RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) SSLContext(javax.net.ssl.SSLContext) KeyStoreException(java.security.KeyStoreException) PluginConfigurationException(alien4cloud.paas.exception.PluginConfigurationException) Registry(org.apache.http.config.Registry) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) RestClientException(org.springframework.web.client.RestClientException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) PluginConfigurationException(alien4cloud.paas.exception.PluginConfigurationException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) RestTemplate(org.springframework.web.client.RestTemplate) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 52 with PrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.PrivateKeyInfo 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 53 with PrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.PrivateKeyInfo 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 54 with PrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.PrivateKeyInfo 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 55 with PrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.PrivateKeyInfo in project android_packages_apps_Settings by SudaMod.

the class CredentialStorage method isHardwareBackedKey.

private boolean isHardwareBackedKey(byte[] keyData) {
    try {
        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(keyData));
        PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
        String algOid = pki.getAlgorithmId().getAlgorithm().getId();
        String algName = new AlgorithmId(new ObjectIdentifier(algOid)).getName();
        return KeyChain.isBoundKeyAlgorithm(algName);
    } catch (IOException e) {
        Log.e(TAG, "Failed to parse key data");
        return false;
    }
}
Also used : ASN1InputStream(com.android.org.bouncycastle.asn1.ASN1InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) AlgorithmId(sun.security.x509.AlgorithmId) IOException(java.io.IOException) PrivateKeyInfo(com.android.org.bouncycastle.asn1.pkcs.PrivateKeyInfo) ObjectIdentifier(sun.security.util.ObjectIdentifier)

Aggregations

PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)48 IOException (java.io.IOException)31 JcaPEMKeyConverter (org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter)27 PEMParser (org.bouncycastle.openssl.PEMParser)25 PrivateKey (java.security.PrivateKey)22 PEMKeyPair (org.bouncycastle.openssl.PEMKeyPair)20 PKCS8EncryptedPrivateKeyInfo (org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)18 ByteArrayInputStream (java.io.ByteArrayInputStream)14 InputDecryptorProvider (org.bouncycastle.operator.InputDecryptorProvider)13 JceOpenSSLPKCS8DecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder)11 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)10 X9ECParameters (org.bouncycastle.asn1.x9.X9ECParameters)10 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)9 JcePEMDecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder)9 PemObject (org.bouncycastle.util.io.pem.PemObject)9 ASN1InputStream (com.android.org.bouncycastle.asn1.ASN1InputStream)8 PrivateKeyInfo (com.android.org.bouncycastle.asn1.pkcs.PrivateKeyInfo)8 StringReader (java.io.StringReader)8 GeneralSecurityException (java.security.GeneralSecurityException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8