Example usage for javax.net.ssl KeyManagerFactory getInstance

List of usage examples for javax.net.ssl KeyManagerFactory getInstance

Introduction

In this page you can find the example usage for javax.net.ssl KeyManagerFactory getInstance.

Prototype

public static final KeyManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyManagerFactory object that acts as a factory for key managers.

Usage

From source file:io.fabric8.kubernetes.api.KubernetesFactory.java

private void configureClientCert(WebClient webClient) {
    try (InputStream certInputStream = getInputStreamFromDataOrFile(clientCertData, clientCertFile)) {
        CertificateFactory certFactory = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

        InputStream keyInputStream = getInputStreamFromDataOrFile(clientKeyData, clientKeyFile);
        PEMReader reader = new PEMReader(keyInputStream);
        RSAPrivateCrtKeySpec keySpec = new PKCS1EncodedKeySpec(reader.getDerBytes()).getKeySpec();
        KeyFactory kf = KeyFactory.getInstance(clientKeyAlgo);
        RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null);/*from   ww w.  ja  va 2s .co  m*/

        String alias = cert.getSubjectX500Principal().getName();
        keyStore.setKeyEntry(alias, privKey, clientKeyPassword, new Certificate[] { cert });

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, clientKeyPassword);

        HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit();

        TLSClientParameters params = conduit.getTlsClientParameters();

        if (params == null) {
            params = new TLSClientParameters();
            conduit.setTlsClientParameters(params);
        }

        KeyManager[] existingKeyManagers = params.getKeyManagers();
        KeyManager[] keyManagers;

        if (existingKeyManagers == null || ArrayUtils.isEmpty(existingKeyManagers)) {
            keyManagers = keyManagerFactory.getKeyManagers();
        } else {
            keyManagers = (KeyManager[]) ArrayUtils.addAll(existingKeyManagers,
                    keyManagerFactory.getKeyManagers());
        }

        params.setKeyManagers(keyManagers);

    } catch (Exception e) {
        log.error("Could not create key manager for " + clientCertFile + " (" + clientKeyFile + ")", e);
    }
}

From source file:org.kuali.coeus.propdev.impl.s2s.connect.S2SConnectorServiceBase.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig/*w  w  w. j  av  a 2  s.  co m*/
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2sCommunicationException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2sCommunicationException {
    KeyStore keyStore = s2sCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(s2sCertificateReader.getJksType());
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(
                    alias, key, s2SConfigurationService
                            .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        } else {
            keyManagerFactory.init(keyStore, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        }
        KeyManager[] km = keyManagerFactory.getKeyManagers();
        tlsConfig.setKeyManagers(km);
        KeyStore trustStore = s2sCertificateReader.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();
        tlsConfig.setTrustManagers(tm);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | CertificateException
            | IOException e) {
        LOG.error(e.getMessage(), e);
        throw new S2sCommunicationException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:test.integ.be.fedict.commons.eid.client.SSLTest.java

@Test
public void testKeyManagerFactory() throws Exception {
    Security.addProvider(new BeIDProvider());
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("BeID");
    assertNotNull(keyManagerFactory);//  ww w .  j av a 2s .  com

    final String algo = keyManagerFactory.getAlgorithm();
    LOG.debug("key manager factory algo: " + algo);
    assertEquals("BeID", algo);

    final KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
    assertNotNull(keyManagers);
}

From source file:ddf.security.realm.sts.StsRealm.java

/**
 * Setup key store for SSL client.//from  w  w w .  jav a  2 s.c om
 */
private void setupKeyStore(TLSClientParameters tlsParams, String keyStorePath, String keyStorePassword) {
    File keyStoreFile = new File(keyStorePath);

    if (keyStoreFile.exists() && keyStorePassword != null) {
        FileInputStream fis = null;
        KeyStore keyStore = null;

        try {
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            fis = new FileInputStream(keyStoreFile);

            LOGGER.debug("Loading keyStore");
            keyStore.load(fis, keyStorePassword.toCharArray());

            KeyManagerFactory keyFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyFactory.init(keyStore, keyStorePassword.toCharArray());
            LOGGER.debug("key manager factory initialized");
            KeyManager[] km = keyFactory.getKeyManagers();
            tlsParams.setKeyManagers(km);
        } catch (FileNotFoundException e) {
            LOGGER.error("Unable to find SSL store: " + keyStorePath, e);
        } catch (IOException e) {
            LOGGER.error("Unable to load key store. " + keyStoreFile, e);
        } catch (CertificateException e) {
            LOGGER.error("Unable to load certificates from key store. " + keyStoreFile, e);
        } catch (KeyStoreException e) {
            LOGGER.error("Unable to read key store: ", e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("Problems creating SSL socket. Usually this is "
                    + "referring to the certificate sent by the server not being trusted by the client.", e);
        } catch (UnrecoverableKeyException e) {
            LOGGER.error("Unable to read key store: ", e);
        } finally {
            IOUtils.closeQuietly(fis);
        }

    }
}

From source file:org.hyperic.hq.hqapi1.HQConnection.java

private KeyManagerFactory getKeyManagerFactory(final KeyStore keystore, final String password)
        throws KeyStoreException {
    try {/*from   ww w  . ja v  a2  s.c  om*/
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());

        keyManagerFactory.init(keystore, password.toCharArray());

        return keyManagerFactory;
    } catch (NoSuchAlgorithmException e) {
        // no support for algorithm, if this happens we're kind of screwed
        // we're using the default so it should never happen
        throw new KeyStoreException(e);
    } catch (UnrecoverableKeyException e) {
        // invalid password, should never happen
        throw new KeyStoreException(e);
    }
}

From source file:com.jms.notify.utils.httpclient.SimpleHttpUtils.java

public static ClientKeyStore loadClientKeyStore(InputStream keyStoreStream, String keyStorePass,
        String privateKeyPass) {/*from www .  ja  v a  2 s. c  o m*/
    try {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(keyStoreStream, keyStorePass.toCharArray());
        kmf.init(ks, privateKeyPass.toCharArray());
        return new ClientKeyStore(kmf);
    } catch (Exception e) {
        logger.error("loadClientKeyFactory fail : " + e.getMessage(), e);
        return null;
    }
}

From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java

public SSLContext getSSLContext(String clientCertConfig, X509TrustManager trustManager)
        throws GeneralSecurityException {
    try {//w w w . jav a  2  s.com
        if (clientCertConfig == null)
            return getSSLContext(trustManager);

        CertificateConfigEntry entry = null;
        for (CertificateConfigEntry e : getClientAuthCertificateConfigs()) {
            if (e.getId().equals(clientCertConfig)) {
                entry = e;
                break;
            }
        }
        if (entry == null)
            throw new GeneralSecurityException(
                    "Client certificate config with id <" + clientCertConfig + "> not found.");

        final KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(new KeyStoreBuilderParameters(loadKeyStore(entry)));

        return getSSLContext(kmf.getKeyManagers(), trustManager);
    } catch (Exception e) {
        throw new GeneralSecurityException("Cannot init SSLContext", e);
    }
}

From source file:org.springframework.amqp.rabbit.connection.RabbitConnectionFactoryBean.java

/**
 * Override this method to take complete control over the SSL setup.
 * @throws Exception an Exception./*ww  w  .j a v a2  s.  c o m*/
 * @since 1.4.4
 */
protected void setUpSSL() throws Exception {
    if (this.sslPropertiesLocation == null && this.keyStore == null && this.trustStore == null
            && this.keyStoreResource == null && this.trustStoreResource == null) {
        if (this.sslAlgorithmSet) {
            this.connectionFactory.useSslProtocol(this.sslAlgorithm);
        } else {
            this.connectionFactory.useSslProtocol();
        }
    } else {
        if (this.sslPropertiesLocation != null) {
            this.sslProperties.load(this.sslPropertiesLocation.getInputStream());
        }
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String keyStoreName = getKeyStore();
        String trustStoreName = getTrustStore();
        String keyStorePassword = getKeyStorePassphrase();
        String trustStorePassword = getTrustStorePassphrase();
        String keyStoreType = getKeyStoreType();
        String trustStoreType = getTrustStoreType();
        char[] keyPassphrase = null;
        if (StringUtils.hasText(keyStorePassword)) {
            keyPassphrase = keyStorePassword.toCharArray();
        }
        char[] trustPassphrase = null;
        if (StringUtils.hasText(trustStorePassword)) {
            trustPassphrase = trustStorePassword.toCharArray();
        }
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;
        if (StringUtils.hasText(keyStoreName) || this.keyStoreResource != null) {
            Resource keyStoreResource = this.keyStoreResource != null ? this.keyStoreResource
                    : resolver.getResource(keyStoreName);
            KeyStore ks = KeyStore.getInstance(keyStoreType);
            ks.load(keyStoreResource.getInputStream(), keyPassphrase);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, keyPassphrase);
            keyManagers = kmf.getKeyManagers();
        }
        if (StringUtils.hasText(trustStoreName) || this.trustStoreResource != null) {
            Resource trustStoreResource = this.trustStoreResource != null ? this.trustStoreResource
                    : resolver.getResource(trustStoreName);
            KeyStore tks = KeyStore.getInstance(trustStoreType);
            tks.load(trustStoreResource.getInputStream(), trustPassphrase);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(tks);
            trustManagers = tmf.getTrustManagers();
        }

        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Initializing SSLContext with KM: " + Arrays.toString(keyManagers) + ", TM: "
                    + Arrays.toString(trustManagers) + ", random: " + this.secureRandom);
        }
        SSLContext context = createSSLContext();
        context.init(keyManagers, trustManagers, this.secureRandom);
        this.connectionFactory.useSslProtocol(context);
    }
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java

private SSLSocketFactory getSSLFactory() throws IOException, NoSuchAlgorithmException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, KeyManagementException {

    final KeyManager km[];
    final TrustManager tm[];

    // Put the key and certs in the user keystore (if available)
    if (this.ks != null) {
        final KeyManagerFactory kmf;
        kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(this.ks, this.passphrase.toCharArray());
        km = kmf.getKeyManagers();//w w  w.  j ava 2s.co  m
    } else {
        km = null;
    }
    // Now make a truststore to verify the server
    if (this.certChain != null && this.certChain.length > 0) {
        final KeyStore trustks = KeyStore.getInstance("jks");
        trustks.load(null, "foo123".toCharArray());
        // add trusted CA cert
        trustks.setCertificateEntry("trusted", this.certChain[this.certChain.length - 1]);
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(trustks);
        tm = tmf.getTrustManagers();
    } else {
        tm = null;
    }
    if (km == null && tm == null) {
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    }
    final SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(km, tm, null);

    return ctx.getSocketFactory();
}