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:org.apache.james.protocols.lib.netty.AbstractConfigurableAsyncServer.java

/**
 * Build the SSLEngine/*from  w ww  . j av a2s  . c  o m*/
 * 
 * @throws Exception
 */

private void buildSSLContext() throws Exception {
    if (useStartTLS || useSSL) {
        FileInputStream fis = null;
        try {
            KeyStore ks = KeyStore.getInstance("JKS");
            fis = new FileInputStream(fileSystem.getFile(keystore));
            ks.load(fis, secret.toCharArray());

            // Set up key manager factory to use our key store
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(x509Algorithm);
            kmf.init(ks, secret.toCharArray());

            // Initialize the SSLContext to work with our key managers.
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(kmf.getKeyManagers(), null, null);
            if (useStartTLS) {
                encryption = Encryption.createStartTls(context, enabledCipherSuites);
            } else {
                encryption = Encryption.createTls(context, enabledCipherSuites);
            }
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    }
}

From source file:ddf.metrics.plugin.webconsole.MetricsWebConsolePlugin.java

private void configureHttps(WebClient client) {
    LOGGER.debug("Configuring client for HTTPS");
    HTTPConduit conduit = WebClient.getConfig(client).getHttpConduit();
    if (null != conduit) {
        TLSClientParameters params = conduit.getTlsClientParameters();

        if (params == null) {
            params = new TLSClientParameters();
        }/*  ww w  . j a va  2 s .c o m*/

        params.setDisableCNCheck(true);

        KeyStore keyStore;
        KeyStore trustStore;
        FileInputStream tsFIS = null;
        FileInputStream ksFIS = null;
        try {
            String trustStorePath = System.getProperty("javax.net.ssl.trustStore");
            String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType");
            String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");

            trustStore = KeyStore.getInstance(trustStoreType);
            File trustStoreFile = new File(trustStorePath);
            tsFIS = new FileInputStream(trustStoreFile);
            trustStore.load(tsFIS, trustStorePassword.toCharArray());

            String keyStorePath = System.getProperty("javax.net.ssl.keyStore");
            String keyStoreType = System.getProperty("javax.net.ssl.keyStoreType");
            String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");

            keyStore = KeyStore.getInstance(keyStoreType);
            File keyStoreFile = new File(keyStorePath);
            ksFIS = new FileInputStream(keyStoreFile);
            keyStore.load(ksFIS, keyStorePassword.toCharArray());

            TrustManagerFactory trustFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustFactory.init(trustStore);
            TrustManager[] tm = trustFactory.getTrustManagers();
            params.setTrustManagers(tm);

            KeyManagerFactory keyFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyFactory.init(keyStore, keyStorePassword.toCharArray());
            KeyManager[] km = keyFactory.getKeyManagers();
            params.setKeyManagers(km);

            conduit.setTlsClientParameters(params);
        } catch (KeyStoreException e) {
            handleKeyStoreException(e);
        } catch (NoSuchAlgorithmException e) {
            handleKeyStoreException(e);
        } catch (CertificateException e) {
            handleKeyStoreException(e);
        } catch (FileNotFoundException e) {
            handleKeyStoreException(e);
        } catch (IOException e) {
            handleKeyStoreException(e);
        } catch (UnrecoverableKeyException e) {
            handleKeyStoreException(e);
        } finally {
            if (null != tsFIS) {
                IOUtils.closeQuietly(tsFIS);
            }
            if (null != ksFIS) {
                IOUtils.closeQuietly(ksFIS);
            }
        }
    } else {
        LOGGER.warn("HTTP Conduit returned by the web client was NULL.");
    }
}

From source file:com.vmware.photon.controller.core.Main.java

private static PhotonControllerXenonHost startXenonHost(PhotonControllerConfig photonControllerConfig,
        ThriftModule thriftModule, DeployerConfig deployerConfig, SSLContext sslContext) throws Throwable {
    // Values for CloudStore
    final HostClientFactory hostClientFactory = thriftModule.getHostClientFactory();
    final AgentControlClientFactory agentControlClientFactory = thriftModule.getAgentControlClientFactory();
    final NsxClientFactory nsxClientFactory = new NsxClientFactory();

    // Values for Scheduler
    final ServerSet cloudStoreServerSet = new StaticServerSet(
            new InetSocketAddress(photonControllerConfig.getXenonConfig().getRegistrationAddress(),
                    Constants.PHOTON_CONTROLLER_PORT));
    final CloudStoreHelper cloudStoreHelper = new CloudStoreHelper(cloudStoreServerSet);

    final CloseableHttpAsyncClient httpClient;
    try {/*from   www  .  j a  v  a2 s.c o m*/
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial((chain, authtype) -> true).build();
        httpClient = HttpAsyncClientBuilder.create()
                .setHostnameVerifier(SSLIOSessionStrategy.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslcontext)
                .build();
        httpClient.start();
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }

    ServerSet apiFeServerSet = new StaticServerSet(new InetSocketAddress(
            photonControllerConfig.getXenonConfig().getRegistrationAddress(), Constants.MANAGEMENT_API_PORT));

    logger.info("Creating PhotonController Xenon Host");
    final PhotonControllerXenonHost photonControllerXenonHost = new PhotonControllerXenonHost(
            photonControllerConfig.getXenonConfig(), hostClientFactory, agentControlClientFactory,
            nsxClientFactory, cloudStoreHelper, sslContext);
    logger.info("Created PhotonController Xenon Host");

    // Set referer Uri from the xenon host, because we do not want to rely on
    // CloudStoreHelper's default mechanise to create referer based on local address,
    // because CloudStoreHelper uses InetAddress.getLocalHost() which depends on
    // /etc/hosts having a hostname entry, which is not always available.
    // This change will allow people to run this service without need to
    // update their /etc/hosts file.
    cloudStoreHelper.setRefererUri(photonControllerXenonHost.getUri());

    final ConstraintChecker checker = new CloudStoreConstraintChecker(cloudStoreHelper,
            photonControllerXenonHost);

    logger.info("Creating Cloud Store Xenon Service Group");
    CloudStoreServiceGroup cloudStoreServiceGroup = createCloudStoreServiceGroup(deployerConfig.isInstaller());
    logger.info("Created Cloud Store Xenon Service Group");

    logger.info("Registering Cloud Store Xenon Service Group");
    photonControllerXenonHost.registerCloudStore(cloudStoreServiceGroup);
    logger.info("Registered Cloud Store Xenon Service Group");

    logger.info("Creating Scheduler Xenon Service Group");
    SchedulerServiceGroup schedulerServiceGroup = createSchedulerServiceGroup(photonControllerConfig.getRoot(),
            checker);
    logger.info("Created Scheduler Xenon Service Group");

    logger.info("Registering Scheduler Xenon Service Group");
    photonControllerXenonHost.registerScheduler(schedulerServiceGroup);
    logger.info("Registered Scheduler Xenon Service Group");

    logger.info("Creating Housekeeper Xenon Service Group");
    HousekeeperServiceGroup housekeeperServiceGroup = createHousekeeperServiceGroup();
    logger.info("Created Housekeeper Xenon Service Group");

    logger.info("Registering Housekeeper Xenon Service Group");
    photonControllerXenonHost.registerHousekeeper(housekeeperServiceGroup);
    logger.info("Registered Housekeeper Xenon Service Group");

    logger.info("Creating Deployer Xenon Service Group");
    DeployerServiceGroup deployerServiceGroup = createDeployerServiceGroup(photonControllerConfig,
            deployerConfig, apiFeServerSet, cloudStoreServerSet, httpClient);
    logger.info("Created Deployer Xenon Service Group");

    logger.info("Registering Deployer Xenon Service Group");
    photonControllerXenonHost.registerDeployer(deployerServiceGroup);
    logger.info("Registered Deployer Xenon Service Group");

    DeployerContext deployerContext = deployerConfig.getDeployerContext();
    if (deployerContext.isAuthEnabled()) {
        ServiceClient serviceClient = NettyHttpServiceClient.create(Main.class.getSimpleName(),
                Executors.newFixedThreadPool(Utils.DEFAULT_THREAD_COUNT),
                Executors.newScheduledThreadPool(Utils.DEFAULT_IO_THREAD_COUNT), photonControllerXenonHost);

        /*
        To make sure that Xenon uses only TLSv1.2 and disallows SSLv3, TLSv1,
        TLSv1.1 the Docker file for the photon-controller-core container is edited.
        The java.security file located inside the container at the location
        /var/opt/OpenJDK-* /jre/lib/security has the information under the
        jdk.tls.disabledAlgorithms
        */

        SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        KeyStore keyStore = KeyStore.getInstance("JKS");
        try (FileInputStream fis = new FileInputStream(deployerContext.getKeyStorePath())) {
            keyStore.load(fis, deployerContext.getKeyStorePassword().toCharArray());
        }
        keyManagerFactory.init(keyStore, deployerContext.getKeyStorePassword().toCharArray());
        clientContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        serviceClient.setSSLContext(clientContext);
        photonControllerXenonHost.setClient(serviceClient);
    }

    logger.info("Starting PhotonController Xenon Host");
    photonControllerXenonHost.start();
    logger.info("Started PhotonController Xenon Host");

    logger.info("Creating SystemConfig instance");
    SystemConfig.createInstance(photonControllerXenonHost);
    logger.info("Created SystemConfig instance");
    return photonControllerXenonHost;
}

From source file:org.kuali.kra.s2s.service.impl.S2SConnectorServiceBase.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig/*  ww  w.j  av  a 2 s.  com*/
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2SException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2SException {
    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,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(alias, key,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        } else {
            keyManagerFactory.init(keyStore,
                    s2SUtilService.getProperty(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 e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (UnrecoverableKeyException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (CertificateException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (IOException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:com.liferay.sync.engine.lan.session.LanSession.java

private static SSLConnectionSocketFactory _getSSLSocketFactory() throws Exception {

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    keyStore.load(null, null);//from   w w  w  .j  a  v  a 2  s.  co m

    for (SyncAccount syncAccount : SyncAccountService.findAll()) {
        if (!syncAccount.isActive() || !syncAccount.isLanEnabled()) {
            continue;
        }

        try {
            PrivateKey privateKey = LanPEMParserUtil.parsePrivateKey(syncAccount.getLanKey());

            if (privateKey == null) {
                _logger.error("SyncAccount {} missing valid private key", syncAccount.getSyncAccountId());

                continue;
            }

            X509Certificate x509Certificate = LanPEMParserUtil
                    .parseX509Certificate(syncAccount.getLanCertificate());

            if (x509Certificate == null) {
                _logger.error("SyncAccount {} missing valid certificate", syncAccount.getSyncAccountId());

                continue;
            }

            keyStore.setCertificateEntry(syncAccount.getLanServerUuid(), x509Certificate);

            keyStore.setKeyEntry(syncAccount.getLanServerUuid(), privateKey, "".toCharArray(),
                    new Certificate[] { x509Certificate });
        } catch (Exception e) {
            _logger.error(e.getMessage(), e);
        }
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    keyManagerFactory.init(keyStore, "".toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    trustManagerFactory.init(keyStore);

    SSLContext sslContext = SSLContext.getInstance("TLS");

    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    return new SNISSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
}

From source file:org.eclipse.emf.emfstore.internal.client.model.connectionmanager.KeyStoreManager.java

/**
 * Returns a SSL Context. This is need for encryption, used by the
 * SSLSocketFactory.//w  w  w.  j a  v a2  s  .  c o m
 * 
 * @return SSL Context
 * @throws ESCertificateException
 *             in case of failure retrieving the context
 */
public SSLContext getSSLContext() throws ESCertificateException {
    try {
        loadKeyStore();
        final KeyManagerFactory managerFactory = KeyManagerFactory.getInstance("SunX509"); //$NON-NLS-1$
        managerFactory.init(keyStore, KEYSTOREPASSWORD.toCharArray());
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); //$NON-NLS-1$
        trustManagerFactory.init(keyStore);
        final SSLContext sslContext = SSLContext.getInstance("TLS"); //$NON-NLS-1$
        sslContext.init(managerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        return sslContext;
    } catch (final NoSuchAlgorithmException e) {
        throw new ESCertificateException(Messages.KeyStoreManager_29, e);
    } catch (final UnrecoverableKeyException e) {
        throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$
    } catch (final KeyStoreException e) {
        throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$
    } catch (final KeyManagementException e) {
        throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$
    }
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.mqtt.MqttConnectionFactory.java

protected SSLSocketFactory getSocketFactory(String keyStoreLocation, String keyStoreType,
        String keyStorePassword, String trustStoreLocation, String trustStoreType, String trustStorePassword,
        String sslVersion) throws Exception {

    char[] keyPassphrase = keyStorePassword.toCharArray();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(new FileInputStream(keyStoreLocation), keyPassphrase);

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

    char[] trustPassphrase = trustStorePassword.toCharArray();
    KeyStore trustStore = KeyStore.getInstance(trustStoreType);
    trustStore.load(new FileInputStream(trustStoreLocation), trustPassphrase);

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    SSLContext sslContext = SSLContext.getInstance(sslVersion);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    return sslContext.getSocketFactory();
}

From source file:org.apache.jmeter.protocol.amf.proxy.AmfProxy.java

/**
 * Get SSL connection from hashmap, creating it if necessary.
 *
 * @param host/*from w  ww  .  j  a v  a  2  s  .c  o  m*/
 * @return a ssl socket factory
 * @throws IOException
 */
private SSLSocketFactory getSSLSocketFactory(String host) throws IOException {
    synchronized (hashHost) {
        if (hashHost.containsKey(host)) {
            log.debug("Good, already in map, host=" + host);
            return hashHost.get(host);
        }
        InputStream in = getCertificate();
        Exception except = null;
        if (in != null) {
            KeyStore ks = null;
            KeyManagerFactory kmf = null;
            SSLContext sslcontext = null;
            try {
                ks = KeyStore.getInstance(KEYSTORE_TYPE);
                ks.load(in, KEYSTORE_PASSWORD);
                kmf = KeyManagerFactory.getInstance(KEYMANAGERFACTORY);
                kmf.init(ks, KEY_PASSWORD);
                sslcontext = SSLContext.getInstance(SSLCONTEXT_PROTOCOL);
                sslcontext.init(kmf.getKeyManagers(), null, null);
                SSLSocketFactory sslFactory = sslcontext.getSocketFactory();
                hashHost.put(host, sslFactory);
                log.info("KeyStore for SSL loaded OK and put host in map (" + host + ")");
                return sslFactory;
            } catch (NoSuchAlgorithmException e) {
                except = e;
            } catch (KeyManagementException e) {
                except = e;
            } catch (KeyStoreException e) {
                except = e;
            } catch (UnrecoverableKeyException e) {
                except = e;
            } catch (CertificateException e) {
                except = e;
            } finally {
                if (except != null) {
                    log.error("Problem with SSL certificate", except);
                }
                IOUtils.closeQuietly(in);
            }
        } else {
            throw new IOException("Unable to read keystore");
        }
        return null;
    }
}

From source file:org.kuali.kra.s2s.service.impl.GrantsGovConnectorServiceImpl.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig/*from  w  ww  . j av  a  2s  .  co  m*/
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2SException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2SException {
    KeyStore keyStore = S2SCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(JKS_TYPE);
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(alias, key, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
        } else {
            keyManagerFactory.init(keyStore, s2SUtilService.getProperty(KEYSTORE_PASSWORD).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 e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (UnrecoverableKeyException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (CertificateException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (IOException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:com.hypersocket.server.HypersocketServerImpl.java

public void initializeSSL() throws FileNotFoundException, IOException {

    CertificateResourceService certificateService = (CertificateResourceService) applicationContext
            .getBean("certificateResourceServiceImpl");
    RealmService realmService = (RealmService) applicationContext.getBean("realmServiceImpl");

    certificateService.setCurrentPrincipal(realmService.getSystemPrincipal(), Locale.getDefault(),
            realmService.getSystemPrincipal().getRealm());

    try {//ww  w  .j  a v a  2 s .  c  om

        if (log.isInfoEnabled()) {
            log.info("Initializing SSL contexts");
        }

        KeyStore ks = certificateService.getDefaultCertificate();

        // Get the default context
        defaultSSLContext = SSLContext.getInstance("TLS");

        // KeyManager's decide which key material to use.
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, "changeit".toCharArray());
        defaultSSLContext.init(kmf.getKeyManagers(), null, null);

        if (log.isInfoEnabled()) {
            log.info("Completed SSL initialization");
        }
    } catch (Exception ex) {
        log.error("SSL initalization failed", ex);
        throw new IOException("SSL initialization failed: " + ex.getMessage());
    } finally {
        certificateService.clearPrincipalContext();
    }
}