Example usage for javax.net.ssl TrustManagerFactory init

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

Introduction

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

Prototype

public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes this factory with a source of provider-specific trust material.

Usage

From source file:io.fabric8.utils.cxf.WebClients.java

public static void configureCaCert(WebClient webClient, String caCertData, File caCertFile) {
    try {/*from  w w w  .  j a  va  2  s  .com*/
        KeyStore trustStore = createTrustStore(caCertData, caCertFile);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

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

        TLSClientParameters params = conduit.getTlsClientParameters();

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

        TrustManager[] existingTrustManagers = params.getTrustManagers();

        if (!ArrayUtils.isEmpty(existingTrustManagers)) {
            trustManagers = (TrustManager[]) ArrayUtils.addAll(existingTrustManagers, trustManagers);
        }

        params.setTrustManagers(trustManagers);
    } catch (Exception e) {
        LOG.error("Could not create trust manager for " + caCertFile, e);
    }
}

From source file:io.wcm.caravan.commons.httpclient.impl.helpers.CertificateLoader.java

/**
 * Build TrustManagerFactory.//from   w ww  . j  a  v  a2 s .  c  o m
 * @param trustStoreStream Truststore input stream
 * @param storeProperties store properties
 * @return TrustManagerFactory
 * @throws IOException
 * @throws GeneralSecurityException
 */
private static TrustManagerFactory getTrustManagerFactory(InputStream trustStoreStream,
        StoreProperties storeProperties) throws IOException, GeneralSecurityException {
    KeyStore jks = KeyStore.getInstance(storeProperties.getType());
    jks.load(trustStoreStream, storeProperties.getPassword().toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(storeProperties.getManagerType());
    tmf.init(jks);
    return tmf;
}

From source file:org.apache.activemq.ActiveMQSslConnectionFactoryTest.java

public static TrustManager[] getTrustManager() throws Exception {
    TrustManager[] trustStoreManagers = null;
    KeyStore trustedCertStore = KeyStore.getInstance(ActiveMQSslConnectionFactoryTest.KEYSTORE_TYPE);

    trustedCertStore.load(new FileInputStream(ActiveMQSslConnectionFactoryTest.TRUST_KEYSTORE), null);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    tmf.init(trustedCertStore);
    trustStoreManagers = tmf.getTrustManagers();
    return trustStoreManagers;
}

From source file:android.apn.androidpn.server.xmpp.ssl.SSLTrustManagerFactory.java

public static TrustManager[] getTrustManagers(KeyStore truststore, String trustpass) {
    TrustManager[] trustManagers;
    try {//from   ww w. ja  v  a 2s  .c om
        if (truststore == null) {
            trustManagers = null;
        } else {
            TrustManagerFactory trustFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            if (trustpass == null) {
                trustpass = SSLConfig.getc2sTrustPassword();
            }

            trustFactory.init(truststore);

            trustManagers = trustFactory.getTrustManagers();
        }
    } catch (KeyStoreException e) {
        trustManagers = null;
        log.error("SSLTrustManagerFactory startup problem.", e);
    } catch (NoSuchAlgorithmException e) {
        trustManagers = null;
        log.error("SSLTrustManagerFactory startup problem.", e);
    }
    return trustManagers;
}

From source file:org.wso2.carbon.esb.rabbitmq.message.store.jira.ESBJAVA4569RabbiMQSSLStoreWithClientCertValidationTest.java

/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result/*from  www.j  av a 2 s.  c o  m*/
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";

    String basePath = TestConfigurationProvider.getResourceLocation()
            + "/artifacts/ESB/messageStore/rabbitMQ/SSL/";

    String truststoreLocation = basePath + "rabbitMQ/certs/client/rabbitstore";
    String keystoreLocation = basePath + "rabbitMQ/certs/client/keycert.p12";

    char[] keyPassphrase = "MySecretPassword".toCharArray();
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(keystoreLocation), keyPassphrase);

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

    char[] trustPassphrase = "rabbitstore".toCharArray();
    KeyStore tks = KeyStore.getInstance("JKS");
    tks.load(new FileInputStream(truststoreLocation), trustPassphrase);

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

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

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol(c);

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    GetResponse chResponse = channel.basicGet("WithClientCertQueue", true);
    if (chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}

From source file:org.jasig.cas.authentication.FileTrustStoreSslSocketFactory.java

/**
 * Gets trust manager./* ww  w . j av a  2  s  .  c o  m*/
 *
 * @param algorithm the algorithm
 * @param keystore the keystore
 * @return the trust manager
 * @throws Exception the exception
 */
private static X509TrustManager getTrustManager(final String algorithm, final KeyStore keystore)
        throws Exception {
    final TrustManagerFactory factory = TrustManagerFactory.getInstance(algorithm);
    factory.init(keystore);
    return (X509TrustManager) factory.getTrustManagers()[0];
}

From source file:org.apache.nifi.minifi.c2.integration.test.AbstractTestSecure.java

public static SSLContext initCertificates(Path certificatesDirectory, List<String> serverHostnames)
        throws Exception {
    List<String> toolkitCommandLine = new ArrayList<>(Arrays.asList("-O", "-o",
            certificatesDirectory.toFile().getAbsolutePath(), "-C", "CN=user1", "-C", "CN=user2", "-C",
            "CN=user3", "-C", "CN=user4", "-S", "badKeystorePass", "-K", "badKeyPass", "-P", "badTrustPass"));
    for (String serverHostname : serverHostnames) {
        toolkitCommandLine.add("-n");
        toolkitCommandLine.add(serverHostname);
    }//w w  w  .j a  va  2 s .  c o m
    Files.createDirectories(certificatesDirectory);
    TlsToolkitStandaloneCommandLine tlsToolkitStandaloneCommandLine = new TlsToolkitStandaloneCommandLine();
    tlsToolkitStandaloneCommandLine.parse(toolkitCommandLine.toArray(new String[toolkitCommandLine.size()]));
    new TlsToolkitStandalone()
            .createNifiKeystoresAndTrustStores(tlsToolkitStandaloneCommandLine.createConfig());

    tlsToolkitStandaloneCommandLine = new TlsToolkitStandaloneCommandLine();
    tlsToolkitStandaloneCommandLine.parse(new String[] { "-O", "-o",
            certificatesDirectory.getParent().resolve("badCert").toFile().getAbsolutePath(), "-C",
            "CN=user3" });
    new TlsToolkitStandalone()
            .createNifiKeystoresAndTrustStores(tlsToolkitStandaloneCommandLine.createConfig());

    final KeyStore trustStore = KeyStoreUtils.getTrustStore("jks");
    try (final InputStream trustStoreStream = new FileInputStream(
            certificatesDirectory.resolve("c2").resolve("truststore.jks").toFile().getAbsolutePath())) {
        trustStore.load(trustStoreStream, "badTrustPass".toCharArray());
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    return SslContextFactory.createTrustSslContext(
            certificatesDirectory.resolve("c2").resolve("truststore.jks").toFile().getAbsolutePath(),
            "badTrustPass".toCharArray(), "jks", "TLS");
}

From source file:com.utest.webservice.client.rest.AuthSSLProtocolSocketFactory.java

private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }/*from  ww  w. j a v  a  2  s.c  o m*/
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new AuthSSLX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    return trustmanagers;
}

From source file:keywhiz.cli.ClientUtils.java

/**
 * Creates a {@link OkHttpClient} to start a TLS connection.
 *
 * @param cookies list of cookies to include in the client.
 * @return new http client.// w  ww .ja va2  s.  com
 */
public static OkHttpClient sslOkHttpClient(List<HttpCookie> cookies) {
    checkNotNull(cookies);

    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLSv1.2");

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);

        sslContext.init(new KeyManager[0], trustManagerFactory.getTrustManagers(), new SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw Throwables.propagate(e);
    }

    SSLSocketFactory socketFactory = sslContext.getSocketFactory();

    OkHttpClient client = new OkHttpClient().setSslSocketFactory(socketFactory)
            .setConnectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS)).setFollowSslRedirects(false);

    client.setRetryOnConnectionFailure(false);
    client.networkInterceptors().add(new XsrfTokenInterceptor("XSRF-TOKEN", "X-XSRF-TOKEN"));
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    cookies.forEach(c -> cookieManager.getCookieStore().add(null, c));
    client.setCookieHandler(cookieManager);
    return client;
}

From source file:AuthSSLProtocolSocketFactory.java

private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }/*from   w w  w. j av  a 2s . c om*/
    System.out.println("Initializing trust manager");
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new AuthSSLX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    return trustmanagers;
}