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.bt.pi.api.http.SimpleHttpsServerFactoryBean.java

protected HttpServer getInitializedServer(InetSocketAddress address) throws IOException {
    HttpsServer server = HttpsServer.create(address, getBacklog());
    try {//  ww  w  .j  a  va  2  s.co m
        SSLContext sslContext = SSLContext.getInstance(sslContextProtocol);

        KeyStore ks = KeyStore.getInstance(keyStoreType);
        InputStream is = keyStoreLocation.getInputStream();
        try {
            ks.load(is, password);
        } catch (EOFException e) {
            LOG.warn(String.format(
                    "Unable to load certificate store %s. This may be possible because https isn't enabled with a valid certificate",
                    keyStoreLocation));
            return null;
        }

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
        kmf.init(ks, password);

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

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

        final SSLEngine m_engine = sslContext.createSSLEngine();

        server.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
            public void configure(HttpsParameters params) {
                params.setSSLParameters(getSSLContext().getDefaultSSLParameters());
                params.setNeedClientAuth(false);
                params.setWantClientAuth(false);
                params.setCipherSuites(m_engine.getEnabledCipherSuites());
                params.setProtocols(m_engine.getEnabledProtocols());
            }
        });
    } catch (Throwable e) {
        throw new IOException("initializing HttpsServer failed due to exception", e);
    }
    return server;
}

From source file:io.hops.hopsworks.api.util.CustomSSLProtocolSocketFactory.java

private TrustManager[] createTrustManagers(final KeyStore trustStore)
        throws NoSuchAlgorithmException, KeyStoreException {
    if (trustStore == null) {
        LOG.log(Level.SEVERE, "Creating SSL socket but trust store is null");
        throw new IllegalArgumentException("TrustStore cannot be null");
    }//from w  w  w .  j a  v  a2  s.  c  o m
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    return tmf.getTrustManagers();
}

From source file:com.lyndir.lhunath.opal.network.SSLFactory.java

private SSLFactory(final File keyStore, final String password) {

    try (InputStream keyStoreStream = new FileInputStream(keyStore)) {
        KeyStore store = KeyStore.getInstance("JKS");
        store.load(keyStoreStream, password.toCharArray());

        TrustManagerFactory tFactory = TrustManagerFactory.getInstance("SunX509");
        tFactory.init(store);/*www.j  a v  a2  s. c o m*/

        context = SSLContext.getInstance("TLS");
        context.init(null, tFactory.getTrustManagers(), null);
    } catch (final KeyStoreException e) {
        throw new IllegalArgumentException(
                "Keystore type not supported or keystore could not be used to initialize trust.", e);
    } catch (final NoSuchAlgorithmException e) {
        throw new IllegalStateException("Key algorithm not supported.", e);
    } catch (final CertificateException e) {
        throw new IllegalArgumentException("Keystore could not be loaded.", e);
    } catch (final FileNotFoundException e) {
        throw new IllegalArgumentException("Keystore not found.", e);
    } catch (final IOException e) {
        throw new RuntimeException("Could not read the keys from the keystore.", e);
    } catch (final KeyManagementException e) {
        throw new RuntimeException("Could not use the keys for trust.", e);
    }
}

From source file:io.fabric8.elasticsearch.RequestRunner.java

protected final OkHttpClient getHttpClient() throws Exception {
    File ksFile = new File(keyStore);
    KeyStore trusted = KeyStore.getInstance("JKS");
    FileInputStream in = new FileInputStream(ksFile);
    trusted.load(in, password.toCharArray());
    in.close();//from  ww  w .  ja v  a2s .c om
    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManagerFactory trustManagerFactory = InsecureTrustManagerFactory.INSTANCE;
    X509TrustManager trustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    OkHttpClient client = new okhttp3.OkHttpClient.Builder()
            .sslSocketFactory(sslContext.getSocketFactory(), trustManager).readTimeout(1, TimeUnit.MINUTES)
            .writeTimeout(1, TimeUnit.MINUTES).build();
    return client;
}

From source file:jp.pigumer.mqtt.Client.java

Optional<TrustManager[]> initTrustManagers() {
    return loadKeyStore().map(keyStore -> {
        try {/*from  w w  w.  ja  v  a  2 s .co m*/
            Security.addProvider(new BouncyCastleProvider());
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);
            return tmf.getTrustManagers();
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "failed load", e);
            return null;
        }
    });
}

From source file:com.qpark.eip.core.spring.security.https.EipX509TrustManager.java

/**
 * Initialize./*  ww  w.ja  va 2s .co  m*/
 * 
 * @throws Exception
 */
@PostConstruct
public void init() throws Exception {
    // create a "default" JSSE X509TrustManager.
    this.ks = KeyStore.getInstance("JKS");
    if (this.keystore != null) {
        this.ks.load(this.keystore.getInputStream(), this.keystorePassword);
    }

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
    tmf.init(this.ks);

    TrustManager tms[] = tmf.getTrustManagers();

    /*
     * Iterate over the returned trust managers, look for an instance of
     * X509TrustManager. If found, use that as our "default" trust manager.
     */
    for (TrustManager tm : tms) {
        if (tm instanceof X509TrustManager) {
            this.sunJSSEX509TrustManager = (X509TrustManager) tm;
            return;
        }
    }

    /*
     * Find some other way to initialize, or else we have to fail the
     * constructor.
     */
    throw new Exception("Couldn't initialize");
}

From source file:com.linkedin.pinot.common.utils.ClientSSLContextGenerator.java

private TrustManager[] setupTrustManagers()
        throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
    // This is the cert authority that validates server's cert, so we need to put it in our
    // trustStore.
    if (_serverCACertFile != null) {
        LOGGER.info("Initializing trust store from {}", _serverCACertFile);
        FileInputStream is = new FileInputStream(new File(_serverCACertFile));
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null);/*from   w  w  w  . j  a  v a  2s  .c  o  m*/
        CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        int i = 0;
        while (is.available() > 0) {
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is);
            LOGGER.info("Read certificate serial number {} by issuer {} ", cert.getSerialNumber().toString(16),
                    cert.getIssuerDN().toString());

            String serverKey = "https-server-" + i;
            trustStore.setCertificateEntry(serverKey, cert);
            i++;
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(CERTIFICATE_TYPE);
        tmf.init(trustStore);
        LOGGER.info("Successfully initialized trust store");
        return tmf.getTrustManagers();
    }
    // Server verification disabled. Trust all servers
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } };
    return trustAllCerts;
}

From source file:ddf.security.settings.impl.SecuritySettingsServiceImpl.java

@Override
public TLSClientParameters getTLSParameters() {
    TLSClientParameters tlsParams = new TLSClientParameters();
    try {//from  w  w  w  . j  a  va  2  s.co m
        TrustManagerFactory trustFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(trustStore);
        TrustManager[] tm = trustFactory.getTrustManagers();
        tlsParams.setTrustManagers(tm);

        KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyFactory.init(keyStore, keystorePassword.toCharArray());
        KeyManager[] km = keyFactory.getKeyManagers();
        tlsParams.setKeyManagers(km);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
        LOGGER.warn(
                "Could not fully load keystore/truststore into TLSParameters. Parameters may not be fully functional.",
                e);
    }

    FiltersType filter = new FiltersType();
    filter.getInclude().addAll(SSL_ALLOWED_ALGORITHMS);
    filter.getExclude().addAll(SSL_DISALLOWED_ALGORITHMS);
    tlsParams.setCipherSuitesFilter(filter);

    return tlsParams;
}

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);//www.  j av a2s.  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:br.com.ararati.operacoes.SocketFactory.java

public TrustManager[] createTrustManagers()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    KeyStore trustStore = KeyStore.getInstance("JKS");

    trustStore.load(new FileInputStream(fileCacerts), "changeit".toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    return trustManagerFactory.getTrustManagers();
}