Example usage for javax.net.ssl TrustManagerFactory getInstance

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

Introduction

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

Prototype

public static final TrustManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a TrustManagerFactory object that acts as a factory for trust managers.

Usage

From source file:de.metas.procurement.webui.ActiveMQBrokerConfiguration.java

/**
 * @return embedded ActiveMQ broker or <code>null</code>
 */// ww  w.  j av  a 2  s.  c  om
@Bean
public BrokerService brokerService() throws Exception {
    if (!runEmbeddedBroker) {
        logger.info("Skip creating an ActiveMQ broker service");
        return null;
    }

    final BrokerService brokerService = new BrokerService();

    if (useSSL) {
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        {
            final KeyStore keystore = KeyStore.getInstance("JKS");
            final Resource keyStoreResource = Application.getContext().getResource(keyStoreFileResourceURL);
            final InputStream keyStoreStream = keyStoreResource.getInputStream();
            keystore.load(keyStoreStream, keyStorePassword.toCharArray());

            kmf.init(keystore, keyStorePassword.toCharArray());
        }

        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        {
            final KeyStore trustStore = KeyStore.getInstance("JKS");
            final Resource trustStoreResource = Application.getContext().getResource(trustStoreFileResourceURL);
            final InputStream trustStoreStream = trustStoreResource.getInputStream();
            trustStore.load(trustStoreStream, trustStorePassword.toCharArray());

            tmf.init(trustStore);
        }

        final SslContext sslContext = new SslContext(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        brokerService.setSslContext(sslContext);
    }

    //
    // "client" Connector
    {
        final TransportConnector connector = new TransportConnector();
        connector.setUri(new URI(brokerUrl.trim()));
        brokerService.addConnector(connector);
    }

    //
    // "Network of brokers" connector
    if (isSet(networkConnector_discoveryAddress)) {
        final DiscoveryNetworkConnector discoveryNetworkConnector = new DiscoveryNetworkConnector(
                new URI(networkConnector_discoveryAddress.trim()));
        discoveryNetworkConnector.setDuplex(true); // without this, we can send to the other broker, but won't get reposnses

        if (isSet(networkConnector_userName)) {
            discoveryNetworkConnector.setUserName(networkConnector_userName.trim());
        }
        if (isSet(networkConnector_password)) {
            discoveryNetworkConnector.setPassword(networkConnector_password.trim());
        }

        // we need to set ConduitSubscriptions to false,
        // see section "Conduit subscriptions and consumer selectors" on http://activemq.apache.org/networks-of-brokers.html
        discoveryNetworkConnector.setConduitSubscriptions(false);

        logger.info("Adding network connector: {}", networkConnector_discoveryAddress);
        brokerService.addNetworkConnector(discoveryNetworkConnector);
    }

    brokerService.setBrokerName(embeddedBrokerName);
    brokerService.start();
    logger.info("Embedded JMS broker started on URL " + brokerUrl);
    return brokerService;
}

From source file:org.xdi.net.SslDefaultHttpClient.java

private TrustManager[] getTrustManagers() throws Exception {
    KeyStore keyStore = getKeyStore(this.trustStoreType, this.trustStorePath, this.trustStorePassword);

    TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmFactory.init(keyStore);//from   www  .  j av a 2  s .com

    return tmFactory.getTrustManagers();
}

From source file:com.youTransactor.uCube.mdm.MDMManager.java

public void initialize(Context context) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

    onSharedPreferenceChanged(settings, null);

    settings.registerOnSharedPreferenceChangeListener(this);

    try {/*from www.  j  a va2 s.  c o  m*/
        KeyStore keystoreCA = KeyStore.getInstance(KEYSTORE_TYPE);
        keystoreCA.load(context.getResources().openRawResource(R.raw.keystore), PWD);

        KeyStore keystoreClient = null;

        File file = context.getFileStreamPath(KEYSTORE_CLIENT_FILENAME);

        if (file.exists()) {
            keystoreClient = KeyStore.getInstance(KEYSTORE_TYPE);
            InputStream in = new FileInputStream(file);
            keystoreClient.load(in, PWD);
        }

        ready = keystoreClient != null && keystoreClient.getKey(MDM_CLIENT_CERT_ALIAS, PWD) != null;

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystoreCA);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
        kmf.init(keystoreClient, PWD);

        sslContext = SSLContext.getInstance("TLS");

        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    } catch (Exception e) {
        LogManager.debug(MDMManager.class.getSimpleName(), "load keystore error", e);
    }
}

From source file:com.archivas.clienttools.arcutils.utils.net.GetCertsX509TrustManager.java

public void initStandardTrustManager(KeyStore keystore)
        throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException {
    TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    factory.init(keystore);//from  www  . ja va2s  . com
    TrustManager[] trustmanagers = factory.getTrustManagers();

    // Iterate over the returned trustmanagers, look for an instance of X509TrustManager.
    // If found, use that as our "default" trust manager.
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            if (standardTrustManager == null) {
                standardTrustManager = (X509TrustManager) trustmanagers[i];
            }
            // break;
            LOG.log(Level.FINER, "standardTrustManager=" + trustmanagers[i]);
        }
    }
}

From source file:org.ovirt.engine.core.uutils.net.HttpClientBuilder.java

public CloseableHttpClient build() throws IOException, GeneralSecurityException {
    // Prepare the default configuration for all requests:
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(connectTimeout != null ? connectTimeout : 0)
            .setSocketTimeout(readTimeout != null ? readTimeout : 0).build();

    // Configure the trust manager:
    TrustManager[] trustManager = null;
    if (verifyChain) {
        if (trustStore != null) {
            try (InputStream is = new FileInputStream(trustStore)) {
                KeyStore ks = KeyStore.getInstance(trustStoreType);
                ks.load(is, StringUtils.isEmpty(trustStorePassword) ? null : trustStorePassword.toCharArray());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
                tmf.init(ks);//from ww w.  j  a v  a  2s  .  c  o  m
                trustManager = tmf.getTrustManagers();
            }
        }
    } else {
        trustManager = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[] {};
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

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

    // Create the SSL context:
    SSLContext sslContext = SSLContext.getInstance(tlsProtocol);
    sslContext.init(null, trustManager, null);

    // Create the SSL host name verifier:
    HostnameVerifier sslHostnameVerifier = null;
    if (!verifyHost) {
        sslHostnameVerifier = (hostname, session) -> true;
    }

    // Create the socket factory for HTTP:
    ConnectionSocketFactory httpSocketFactory = new PlainConnectionSocketFactory();

    // Create the socket factory for HTTPS:
    ConnectionSocketFactory httpsSocketFactory = new SSLConnectionSocketFactory(sslContext,
            sslHostnameVerifier);

    // Create the socket factory registry:
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", httpSocketFactory).register("https", httpsSocketFactory).build();

    // Create the connection manager:
    HttpClientConnectionManager connectionManager;
    if (poolSize != null) {
        PoolingHttpClientConnectionManager poolManager = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);
        poolManager.setDefaultMaxPerRoute(poolSize);
        poolManager.setMaxTotal(poolSize);
        connectionManager = poolManager;
    } else {
        connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
    }

    // Create the client:
    return org.apache.http.impl.client.HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .setSSLHostnameVerifier(sslHostnameVerifier).setConnectionManager(connectionManager).build();
}

From source file:org.apache.hadoop.hdfsproxy.ProxyUtil.java

private static void setupSslProps(Configuration conf) throws IOException {
    FileInputStream fis = null;/* w ww.  ja  v a2s. c o  m*/
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        KeyManager[] kms = null;
        TrustManager[] tms = null;
        if (conf.get("ssl.client.keystore.location") != null) {
            // initialize default key manager with keystore file and pass
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            KeyStore ks = KeyStore.getInstance(conf.get("ssl.client.keystore.type", "JKS"));
            char[] ksPass = conf.get("ssl.client.keystore.password", "changeit").toCharArray();
            fis = new FileInputStream(conf.get("ssl.client.keystore.location", "keystore.jks"));
            ks.load(fis, ksPass);
            kmf.init(ks, conf.get("ssl.client.keystore.keypassword", "changeit").toCharArray());
            kms = kmf.getKeyManagers();
            fis.close();
            fis = null;
        }
        // initialize default trust manager with keystore file and pass
        if (conf.getBoolean("ssl.client.do.not.authenticate.server", false)) {
            // by pass trustmanager validation
            tms = new DummyTrustManager[] { new DummyTrustManager() };
        } else {
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
            KeyStore ts = KeyStore.getInstance(conf.get("ssl.client.truststore.type", "JKS"));
            char[] tsPass = conf.get("ssl.client.truststore.password", "changeit").toCharArray();
            fis = new FileInputStream(conf.get("ssl.client.truststore.location", "truststore.jks"));
            ts.load(fis, tsPass);
            tmf.init(ts);
            tms = tmf.getTrustManagers();
        }
        sc.init(kms, tms, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        throw new IOException("Could not initialize SSLContext", e);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
}

From source file:ninja.standalone.StandaloneHelper.java

static public SSLContext createSSLContext(URI keystoreUri, char[] keystorePassword, URI truststoreUri,
        char[] truststorePassword) throws Exception {

    // load keystore
    KeyStore keystore = loadKeyStore(keystoreUri, keystorePassword);
    KeyManager[] keyManagers;//from  w ww.  j a  v a  2s .  c o  m
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keystore, keystorePassword);
    keyManagers = keyManagerFactory.getKeyManagers();

    // load truststore
    KeyStore truststore = loadKeyStore(truststoreUri, truststorePassword);
    TrustManager[] trustManagers;
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(truststore);
    trustManagers = trustManagerFactory.getTrustManagers();

    SSLContext sslContext;
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, null);

    return sslContext;
}

From source file:com.openmeap.util.SSLUtils.java

/**
 * @param keyStore is passed into TrustManagerFactory.init(), and may be null for default behavior.
 * @return an array of the default trust managers
 * @throws NoSuchAlgorithmException//from  w w  w  .j av  a  2  s  .  co  m
 * @throws KeyStoreException
 */
public static TrustManager[] getDefaultTrustManagers(KeyStore keyStore)
        throws NoSuchAlgorithmException, KeyStoreException {

    String defaultFactoryManagerAlg = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory managerFactory = TrustManagerFactory.getInstance(defaultFactoryManagerAlg);
    managerFactory.init((KeyStore) keyStore);
    return managerFactory.getTrustManagers();
}

From source file:com.t2auth.AuthUtils.java

public static SSLContext getSslContext(Context ctx) {
    InputStream in = null;/*from   ww w. j  a va 2  s  . c  om*/

    if (sSslContext == null) {
        try {
            sSslContext = SSLContext.getInstance("TLS");
            try {
                if (sKey == null) {
                    sKey = KeyStore.getInstance("BKS");
                    in = ctx.getResources().openRawResource(R.raw.keystore);
                    sKey.load(in, "itsatrap".toCharArray());
                }

                TrustManagerFactory tmf = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(sKey);
                KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
                kmf.init(sKey, "itsatrap".toCharArray());

                sSslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
                return sSslContext;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    } else {
        return sSslContext;
    }

    return null;
}