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:org.keycloak.truststore.JSSETruststoreConfigurator.java

public TrustManager[] getTrustManagers() {
    if (provider == null) {
        return null;
    }/*w w w. j av a  2  s.  c  om*/

    if (tm == null) {
        synchronized (this) {
            if (tm == null) {
                TrustManagerFactory tmf = null;
                try {
                    tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    tmf.init(provider.getTruststore());
                    tm = tmf.getTrustManagers();
                } catch (Exception e) {
                    throw new RuntimeException("Failed to initialize TrustManager: ", e);
                }
            }
        }
    }
    return tm;
}

From source file:com.wso2telco.identity.application.authentication.endpoint.util.MutualSSLClient.java

/**
 * create basic SSL connection factory//from  w w  w  . ja  v  a2 s  . c om
 *
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.KeyStoreException
 * @throws java.security.KeyManagementException
 * @throws java.io.IOException
 * @throws java.security.UnrecoverableKeyException
 */
public static void initMutualSSLConnection() throws NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, IOException, UnrecoverableKeyException {

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
    trustManagerFactory.init(trustStore);
    SSLContext sslContext = SSLContext.getInstance(PROTOCOL);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    sslSocketFactory = sslContext.getSocketFactory();
}

From source file:se.kth.infosys.lumberjack.protocol.LumberjackClient.java

public LumberjackClient(String keyStoreFile, String server, int port, int timeout) throws IOException {
    this.server = server;
    this.port = port;

    try {/*w w  w .j a  v  a  2s. c o  m*/
        if (keyStoreFile == null) {
            throw new IOException("Key store not configured");
        }
        if (server == null) {
            throw new IOException("Server address not configured");
        }

        keyStore = KeyStore.getInstance("JKS");
        InputStream keystoreStream = this.getClass().getClassLoader().getResourceAsStream(keyStoreFile);
        keyStore.load(keystoreStream, null);
        keystoreStream.close();

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(keyStore);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        SSLSocketFactory socketFactory = context.getSocketFactory();
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(server), port), timeout);
        sslSocket = (SSLSocket) socketFactory.createSocket(socket, server, port, true);
        sslSocket.setUseClientMode(true);
        sslSocket.startHandshake();

        output = new DataOutputStream(new BufferedOutputStream(sslSocket.getOutputStream()));
        input = new DataInputStream(sslSocket.getInputStream());

        logger.info("Connected to {}:{}", server, port);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.thesocialcoin.networking.SSL.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {//from w w w  .j a va2 s.  co  m

        // Client should authenticate itself with the valid certificate to Server.
        InputStream clientStream = App.getAppContext().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

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

        // Client should also add the CA certificate obtained from server and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = App.getAppContext().getResources().openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return context;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

From source file:com.ring.ytjojo.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {//w  ww . j av  a  2  s.c o m

        // Client should authenticate itself with the valid certificate to Server.
        InputStream clientStream = AppContext_.getInstance().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

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

        // Client should also add the CA certificate obtained from server and create TrustManager from it for the client to validate the 
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = AppContext_.getInstance().getResources().openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return context;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

From source file:org.apache.streams.cassandra.CassandraClient.java

public void start() throws Exception {

    Objects.nonNull(config);//w ww  .  j  a  v a2 s.  c  om

    LOGGER.info("CassandraClient.start {}", config);

    Cluster.Builder builder = Cluster.builder().withPort(config.getPort().intValue()).withoutJMXReporting()
            .withoutMetrics()
            .withSocketOptions(new SocketOptions().setConnectTimeoutMillis(DEFAULT_CONNECT_TIMEOUT_MILLIS * 10)
                    .setReadTimeoutMillis(DEFAULT_READ_TIMEOUT_MILLIS * 10));

    if (config.getSsl() != null && config.getSsl().getEnabled() == true) {

        Ssl ssl = config.getSsl();

        KeyStore ks = KeyStore.getInstance("JKS");

        InputStream trustStore = new FileInputStream(ssl.getTrustStore());
        ks.load(trustStore, ssl.getTrustStorePassword().toCharArray());
        InputStream keyStore = new FileInputStream(ssl.getKeyStore());
        ks.load(keyStore, ssl.getKeyStorePassword().toCharArray());

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

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, ssl.getKeyStorePassword().toCharArray());

        SSLContext sslContext = SSLContext.getInstance("SSLv3");
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        SSLOptions sslOptions = JdkSSLOptions.builder().withSSLContext(sslContext).build();

        builder = builder.withSSL(sslOptions);
    }

    Collection<InetSocketAddress> addresses = new ArrayList<>();
    for (String h : config.getHosts()) {
        LOGGER.info("Adding Host: {}", h);
        InetSocketAddress socketAddress = new InetSocketAddress(h, config.getPort().intValue());
        addresses.add(socketAddress);
    }
    builder.addContactPointsWithPorts(addresses);

    if (StringUtils.isNotBlank(config.getUser()) && StringUtils.isNotBlank(config.getPassword())) {
        builder.withCredentials(config.getUser(), config.getPassword());
    }
    cluster = builder.build();

    Objects.nonNull(cluster);

    try {
        Metadata metadata = cluster.getMetadata();
        LOGGER.info("Connected to cluster: {}\n", metadata.getClusterName());
        for (Host host : metadata.getAllHosts()) {
            LOGGER.info("Datacenter: {}; Host: {}; Rack: {}\n", host.getDatacenter(), host.getAddress(),
                    host.getRack());
        }
    } catch (Exception e) {
        LOGGER.error("Exception: {}", e);
        throw e;
    }

    try {
        session = cluster.connect();
    } catch (Exception e) {
        LOGGER.error("Exception: {}", e);
        throw e;
    }

    Objects.nonNull(session);

}

From source file:cn.dacas.emmclient.security.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {/*ww  w.j  a  va  2 s .c  o  m*/

        // Client should authenticate itself with the valid certificate to Server.
        InputStream clientStream = EmmClientApplication.getContext().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

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

        // Client should also add the CA certificate obtained from server and create TrustManager from it for the client to validate the 
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = EmmClientApplication.getContext().getResources().openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return context;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

From source file:com.alliander.osgp.shared.usermanagement.OrganisationManagementClient.java

/**
 * Construct a UserManagementClient instance.
 *
 * @param keystoreLocation/*w  w w  .j  a  v  a 2s. co  m*/
 *            The location of the key store.
 * @param keystorePassword
 *            The password for the key store.
 * @param keystoreType
 *            The type of the key store.
 * @param baseAddress
 *            The base address or URL for the UserManagementClient.
 *
 * @throws OrganisationManagementClientException
 *             In case the construction fails, a
 *             OrganisationManagementClientException will be thrown.
 */
public OrganisationManagementClient(final String keystoreLocation, final String keystorePassword,
        final String keystoreType, final String baseAddress) throws OrganisationManagementClientException {

    InputStream stream = null;
    boolean isClosed = false;
    Exception exception = null;

    try {
        // Create the KeyStore.
        final KeyStore keystore = KeyStore.getInstance(keystoreType.toUpperCase());

        stream = new FileInputStream(keystoreLocation);
        keystore.load(stream, keystorePassword.toCharArray());

        // Create TrustManagerFactory and initialize it using the KeyStore.
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystore);

        // Create Apache CXF WebClient with JSON provider.
        final List<Object> providers = new ArrayList<Object>();
        providers.add(new JacksonJaxbJsonProvider());

        this.webClient = WebClient.create(baseAddress, providers);
        if (this.webClient == null) {
            throw new UserManagementClientException("webclient is null");
        }

        // Set up the HTTP Conduit to use the TrustManagers.
        final ClientConfiguration config = WebClient.getConfig(this.webClient);
        final HTTPConduit conduit = config.getHttpConduit();

        conduit.setTlsClientParameters(new TLSClientParameters());
        conduit.getTlsClientParameters().setTrustManagers(tmf.getTrustManagers());
    } catch (final Exception e) {
        LOGGER.error(CONSTRUCTION_FAILED, e);
        throw new OrganisationManagementClientException(CONSTRUCTION_FAILED, e);
    } finally {
        try {
            stream.close();
            isClosed = true;
        } catch (final Exception streamCloseException) {
            LOGGER.error(CONSTRUCTION_FAILED, streamCloseException);
            exception = streamCloseException;
        }
    }

    if (!isClosed) {
        throw new OrganisationManagementClientException(CONSTRUCTION_FAILED, exception);
    }
}

From source file:com.ldroid.kwei.common.lib.volley.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {/*  w ww .  java  2  s  .c o  m*/

        // Client should authenticate itself with the valid certificate to
        // Server.
        InputStream clientStream = MainApp.getContext().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

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

        // Client should also add the CA certificate obtained from server
        // and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = MainApp.getContext().getResources().openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return context;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

From source file:org.elasticsearch.client.RestClientBuilderIntegTests.java

private static SSLContext getSslContext() throws Exception {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    try (InputStream in = RestClientBuilderIntegTests.class.getResourceAsStream("/testks.jks")) {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(in, "password".toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keyStore, "password".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(keyStore);//from   w  w  w  . j  a v  a 2  s.  c  o  m
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    }
    return sslContext;
}