Example usage for javax.net.ssl TrustManagerFactory getTrustManagers

List of usage examples for javax.net.ssl TrustManagerFactory getTrustManagers

Introduction

In this page you can find the example usage for javax.net.ssl TrustManagerFactory getTrustManagers.

Prototype

public final TrustManager[] getTrustManagers() 

Source Link

Document

Returns one trust manager for each type of trust material.

Usage

From source file:com.evolveum.midpoint.prism.crypto.AESProtector.java

/**
 * @throws SystemException if jceks keystore is not available on {@link AESProtector#getKeyStorePath}
 *///from  ww w . j a v a  2s .c o m
public void init() {
    InputStream stream = null;
    try {
        // Test if use file or classpath resource
        File f = new File(getKeyStorePath());
        if (f.exists()) {
            LOGGER.info("Using file keystore at {}", getKeyStorePath());
            if (!f.canRead()) {
                LOGGER.error("Provided keystore file {} is unreadable.", getKeyStorePath());
                throw new EncryptionException(
                        "Provided keystore file " + getKeyStorePath() + " is unreadable.");
            }
            stream = new FileInputStream(f);

            // Use class path keystore
        } else {
            LOGGER.warn("Using default keystore from classpath ({}).", getKeyStorePath());
            // Read from class path

            stream = AESProtector.class.getClassLoader().getResourceAsStream(getKeyStorePath());
            // ugly dirty hack to have second chance to find keystore on
            // class path
            if (stream == null) {
                stream = AESProtector.class.getClassLoader()
                        .getResourceAsStream("com/../../" + getKeyStorePath());
            }
        }
        // Test if we have valid stream
        if (stream == null) {
            throw new EncryptionException("Couldn't load keystore as resource '" + getKeyStorePath() + "'");
        }
        // Load keystore
        keyStore.load(stream, getKeyStorePassword().toCharArray());
        stream.close();

        // Initialze trust manager list

        TrustManagerFactory tmFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmFactory.init(keyStore);
        trustManagers = new ArrayList<TrustManager>();
        for (TrustManager trustManager : tmFactory.getTrustManagers()) {
            trustManagers.add(trustManager);
        }

        //init apache crypto library
        Init.init();

    } catch (Exception ex) {
        LOGGER.error("Unable to work with keystore {}, reason {}.",
                new Object[] { getKeyStorePath(), ex.getMessage() }, ex);
        throw new SystemException(ex.getMessage(), ex);
    }
}

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.//from  w  w w.ja  v  a  2  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.apache.axis2.transport.rabbitmq.RabbitMQConnectionFactory.java

/**
 * Initialize connection factory/*from   w  w w.  java2s .c  o m*/
 */
private void initConnectionFactory() {
    connectionFactory = new ConnectionFactory();
    String hostName = parameters.get(RabbitMQConstants.SERVER_HOST_NAME);
    String portValue = parameters.get(RabbitMQConstants.SERVER_PORT);
    String serverRetryIntervalS = parameters.get(RabbitMQConstants.SERVER_RETRY_INTERVAL);
    String retryIntervalS = parameters.get(RabbitMQConstants.RETRY_INTERVAL);
    String retryCountS = parameters.get(RabbitMQConstants.RETRY_COUNT);
    String heartbeat = parameters.get(RabbitMQConstants.HEARTBEAT);
    String connectionTimeout = parameters.get(RabbitMQConstants.CONNECTION_TIMEOUT);
    String sslEnabledS = parameters.get(RabbitMQConstants.SSL_ENABLED);
    String userName = parameters.get(RabbitMQConstants.SERVER_USER_NAME);
    String password = parameters.get(RabbitMQConstants.SERVER_PASSWORD);
    String virtualHost = parameters.get(RabbitMQConstants.SERVER_VIRTUAL_HOST);

    if (!StringUtils.isEmpty(heartbeat)) {
        try {
            int heartbeatValue = Integer.parseInt(heartbeat);
            connectionFactory.setRequestedHeartbeat(heartbeatValue);
        } catch (NumberFormatException e) {
            //proceeding with rabbitmq default value
            log.warn("Number format error in reading heartbeat value. Proceeding with default");
        }
    }
    if (!StringUtils.isEmpty(connectionTimeout)) {
        try {
            int connectionTimeoutValue = Integer.parseInt(connectionTimeout);
            connectionFactory.setConnectionTimeout(connectionTimeoutValue);
        } catch (NumberFormatException e) {
            //proceeding with rabbitmq default value
            log.warn("Number format error in reading connection timeout value. Proceeding with default");
        }
    }

    if (!StringUtils.isEmpty(sslEnabledS)) {
        try {
            boolean sslEnabled = Boolean.parseBoolean(sslEnabledS);
            if (sslEnabled) {
                String keyStoreLocation = parameters.get(RabbitMQConstants.SSL_KEYSTORE_LOCATION);
                String keyStoreType = parameters.get(RabbitMQConstants.SSL_KEYSTORE_TYPE);
                String keyStorePassword = parameters.get(RabbitMQConstants.SSL_KEYSTORE_PASSWORD);
                String trustStoreLocation = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_LOCATION);
                String trustStoreType = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_TYPE);
                String trustStorePassword = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_PASSWORD);
                String sslVersion = parameters.get(RabbitMQConstants.SSL_VERSION);

                if (StringUtils.isEmpty(keyStoreLocation) || StringUtils.isEmpty(keyStoreType)
                        || StringUtils.isEmpty(keyStorePassword) || StringUtils.isEmpty(trustStoreLocation)
                        || StringUtils.isEmpty(trustStoreType) || StringUtils.isEmpty(trustStorePassword)) {
                    log.warn(
                            "Trustore and keystore information is not provided correctly. Proceeding with default SSL configuration");
                    connectionFactory.useSslProtocol();
                } else {
                    char[] keyPassphrase = keyStorePassword.toCharArray();
                    KeyStore ks = KeyStore.getInstance(keyStoreType);
                    ks.load(new FileInputStream(keyStoreLocation), keyPassphrase);

                    KeyManagerFactory kmf = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    kmf.init(ks, keyPassphrase);

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

                    TrustManagerFactory tmf = TrustManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    tmf.init(tks);

                    SSLContext c = SSLContext.getInstance(sslVersion);
                    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

                    connectionFactory.useSslProtocol(c);
                }
            }
        } catch (Exception e) {
            log.warn("Format error in SSL enabled value. Proceeding without enabling SSL", e);
        }
    }

    if (!StringUtils.isEmpty(retryCountS)) {
        try {
            retryCount = Integer.parseInt(retryCountS);
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading retry count value. Proceeding with default value (3)", e);
        }
    }

    if (!StringUtils.isEmpty(hostName)) {
        connectionFactory.setHost(hostName);
    } else {
        handleException("Host name is not defined");
    }

    try {
        int port = Integer.parseInt(portValue);
        if (port > 0) {
            connectionFactory.setPort(port);
        }
    } catch (NumberFormatException e) {
        handleException("Number format error in port number", e);
    }

    if (!StringUtils.isEmpty(userName)) {
        connectionFactory.setUsername(userName);
    }

    if (!StringUtils.isEmpty(password)) {
        connectionFactory.setPassword(password);
    }

    if (!StringUtils.isEmpty(virtualHost)) {
        connectionFactory.setVirtualHost(virtualHost);
    }

    if (!StringUtils.isEmpty(retryIntervalS)) {
        try {
            retryInterval = Integer.parseInt(retryIntervalS);
        } catch (NumberFormatException e) {
            log.warn(
                    "Number format error in reading retry interval value. Proceeding with default value (30000ms)",
                    e);
        }
    }

    if (!StringUtils.isEmpty(serverRetryIntervalS)) {
        try {
            int serverRetryInterval = Integer.parseInt(serverRetryIntervalS);
            connectionFactory.setNetworkRecoveryInterval(serverRetryInterval);
        } catch (NumberFormatException e) {
            log.warn(
                    "Number format error in reading server retry interval value. Proceeding with default value",
                    e);
        }
    }

    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.setTopologyRecoveryEnabled(false);
}

From source file:edu.vt.middleware.ldap.LdapTLSSocketFactory.java

/**
 * This attempts to load the TrustManagers from the supplied <code>
 * InputStream</code> using the supplied password.
 *
 * @param  is  <code>InputStream</code> containing the truststore
 * @param  password  <code>String</code> to unlock the truststore
 * @param  storeType  <code>String</code> of truststore
 *
 * @return  <code>TrustManager[]</code>
 *
 * @throws  IOException  if the keystore cannot be loaded
 * @throws  GeneralSecurityException  if an errors occurs while loading the
 * TrustManagers/*from  w ww  .j a  va 2 s  .c om*/
 */
private TrustManager[] initTrustManager(final InputStream is, final String password, final String storeType)
        throws IOException, GeneralSecurityException {
    TrustManager[] tm = null;
    if (is != null) {
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(this.loadKeyStore(is, password, storeType));
        tm = tmf.getTrustManagers();
    }
    return tm;
}

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();
        }//from  w w  w  . ja  v  a 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:org.pentaho.di.trans.steps.rest.Rest.java

private void setConfig() throws KettleException {

    if (data.config == null) {
        // Use ApacheHttpClient for supporting proxy authentication.
        data.config = new DefaultApacheHttpClientConfig();

        if (!Const.isEmpty(data.realProxyHost)) {
            // PROXY CONFIGURATION
            data.config.getProperties().put(DefaultApacheHttpClientConfig.PROPERTY_PROXY_URI,
                    "http://" + data.realProxyHost + ":" + data.realProxyPort);
            if (!Const.isEmpty(data.realHttpLogin) && !Const.isEmpty(data.realHttpPassword)) {
                data.config.getState().setProxyCredentials(AuthScope.ANY_REALM, data.realProxyHost,
                        data.realProxyPort, data.realHttpLogin, data.realHttpPassword);
            }/*w  ww .  ja  v  a2  s  .  c o m*/
        } else {
            if (!Const.isEmpty(data.realHttpLogin)) {
                // Basic authentication
                data.basicAuthentication = new HTTPBasicAuthFilter(data.realHttpLogin, data.realHttpPassword);
            }
        }
        if (meta.isPreemptive()) {
            data.config.getProperties().put(ApacheHttpClientConfig.PROPERTY_PREEMPTIVE_AUTHENTICATION, true);
        }

        // SSL TRUST STORE CONFIGURATION
        if (!Const.isEmpty(data.trustStoreFile)) {

            try {
                KeyStore trustStore = KeyStore.getInstance("JKS");
                trustStore.load(new FileInputStream(data.trustStoreFile),
                        data.trustStorePassword.toCharArray());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(trustStore);

                SSLContext ctx = SSLContext.getInstance("SSL");
                ctx.init(null, tmf.getTrustManagers(), null);

                HostnameVerifier hv = new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        if (isDebug()) {
                            logDebug("Warning: URL Host: " + hostname + " vs. " + session.getPeerHost());
                        }
                        return true;
                    }
                };

                data.config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                        new HTTPSProperties(hv, ctx));

            } catch (NoSuchAlgorithmException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.NoSuchAlgorithm"), e);
            } catch (KeyStoreException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.KeyStoreException"), e);
            } catch (CertificateException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.CertificateException"), e);
            } catch (FileNotFoundException e) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "Rest.Error.FileNotFound", data.trustStoreFile), e);
            } catch (IOException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.IOException"), e);
            } catch (KeyManagementException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.KeyManagementException"), e);
            }
        }

    }
}

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

private void configureSSL(HttpClient client) throws IOException {
    final String keyStorePath = System.getProperty("javax.net.ssl.keyStore");
    final String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
    final boolean validateSSLCertificates = StringUtils.hasText(keyStorePath)
            && StringUtils.hasText(keyStorePassword);

    X509TrustManager customTrustManager = null;
    KeyManager[] keyManagers = null;

    try {//from w  ww  . ja va 2 s.c o m
        if (validateSSLCertificates) {
            // Use specified key store and perform SSL validation...
            KeyStore keystore = getKeyStore(keyStorePath, keyStorePassword);
            KeyManagerFactory keyManagerFactory = getKeyManagerFactory(keystore, keyStorePassword);
            TrustManagerFactory trustManagerFactory = getTrustManagerFactory(keystore);

            keyManagers = keyManagerFactory.getKeyManagers();
            customTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
        } else {
            // Revert to previous functionality and ignore SSL certs...
            customTrustManager = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) {
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) {
                }

                //required for jdk 1.3/jsse 1.0.3_01
                public boolean isClientTrusted(X509Certificate[] chain) {
                    return true;
                }

                //required for jdk 1.3/jsse 1.0.3_01
                public boolean isServerTrusted(X509Certificate[] chain) {
                    return true;
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
        }

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

        sslContext.init(keyManagers, new TrustManager[] { customTrustManager }, new SecureRandom());

        // XXX Should we use ALLOW_ALL_HOSTNAME_VERIFIER (least restrictive) or 
        //     BROWSER_COMPATIBLE_HOSTNAME_VERIFIER (moderate restrictive) or
        //     STRICT_HOSTNAME_VERIFIER (most restrictive)???
        // For now allow all, and make it configurable later...

        X509HostnameVerifier hostnameVerifier = null;

        if (validateSSLCertificates) {
            hostnameVerifier = new AllowAllHostnameVerifier();
        } else {
            hostnameVerifier = new X509HostnameVerifier() {
                private AllowAllHostnameVerifier internalVerifier = new AllowAllHostnameVerifier();

                public boolean verify(String host, SSLSession session) {
                    return internalVerifier.verify(host, session);
                }

                public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                    internalVerifier.verify(host, cns, subjectAlts);
                }

                public void verify(String host, X509Certificate cert) throws SSLException {
                    internalVerifier.verify(host, cert);
                }

                public void verify(String host, SSLSocket ssl) throws IOException {
                    try {
                        internalVerifier.verify(host, ssl);
                    } catch (SSLPeerUnverifiedException e) {
                        // ignore
                    }
                }
            };
        }

        client.getConnectionManager().getSchemeRegistry()
                .register(new Scheme("https", 443, new SSLSocketFactory(sslContext, hostnameVerifier)));
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.apache.nifi.controller.livy.LivySessionController.java

private void setSslSocketFactory(HttpsURLConnection httpsURLConnection, SSLContextService sslService,
        SSLContext sslContext) throws IOException, KeyStoreException, CertificateException,
        NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    final String keystoreLocation = sslService.getKeyStoreFile();
    final String keystorePass = sslService.getKeyStorePassword();
    final String keystoreType = sslService.getKeyStoreType();

    // prepare the keystore
    final KeyStore keyStore = KeyStore.getInstance(keystoreType);

    try (FileInputStream keyStoreStream = new FileInputStream(keystoreLocation)) {
        keyStore.load(keyStoreStream, keystorePass.toCharArray());
    }/*w  ww.  j  av  a2 s. c o m*/

    final KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePass.toCharArray());

    // load truststore
    final String truststoreLocation = sslService.getTrustStoreFile();
    final String truststorePass = sslService.getTrustStorePassword();
    final String truststoreType = sslService.getTrustStoreType();

    KeyStore truststore = KeyStore.getInstance(truststoreType);
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
    truststore.load(new FileInputStream(truststoreLocation), truststorePass.toCharArray());
    trustManagerFactory.init(truststore);

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

    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    httpsURLConnection.setSSLSocketFactory(sslSocketFactory);
}

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

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

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

        return sslContext;
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (UnrecoverableKeyException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (KeyStoreException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (KeyManagementException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    }
}