Example usage for javax.net.ssl SSLContext init

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

Introduction

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

Prototype

public final void init(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws KeyManagementException 

Source Link

Document

Initializes this context.

Usage

From source file:com.gargoylesoftware.htmlunit.httpclient.HtmlUnitSSLConnectionSocketFactory.java

/**
 * Factory method that builds a new SSLConnectionSocketFactory.
 * @param options the current WebClientOptions
 * @return the SSLConnectionSocketFactory
 *//*from w  w  w  .j ava2s.  com*/
public static SSLConnectionSocketFactory buildSSLSocketFactory(final WebClientOptions options) {
    try {
        final String[] sslClientProtocols = options.getSSLClientProtocols();
        final String[] sslClientCipherSuites = options.getSSLClientCipherSuites();

        final boolean useInsecureSSL = options.isUseInsecureSSL();

        if (!useInsecureSSL) {
            final KeyStore keyStore = options.getSSLClientCertificateStore();
            final KeyStore trustStore = options.getSSLTrustStore();

            return new HtmlUnitSSLConnectionSocketFactory(keyStore,
                    keyStore == null ? null : options.getSSLClientCertificatePassword(), trustStore,
                    useInsecureSSL, sslClientProtocols, sslClientCipherSuites);
        }

        // we need insecure SSL + SOCKS awareness
        String protocol = options.getSSLInsecureProtocol();
        if (protocol == null) {
            protocol = "SSL";
        }
        final SSLContext sslContext = SSLContext.getInstance(protocol);
        sslContext.init(getKeyManagers(options), new TrustManager[] { new InsecureTrustManager2() }, null);

        final SSLConnectionSocketFactory factory = new HtmlUnitSSLConnectionSocketFactory(sslContext,
                NoopHostnameVerifier.INSTANCE, useInsecureSSL, sslClientProtocols, sslClientCipherSuites);
        return factory;
    } catch (final GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.longtime.ajy.support.weixin.HttpsKit.java

/**
 * ??Post//from   ww  w.  j  a v  a2  s.  c om
 * 
 * @param url
 * @param params
 * @return
 * @throws IOException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static String post(String url, String params) {//throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {

    OutputStream out = null;
    InputStream in = null;
    HttpsURLConnection http = null;
    try {
        StringBuffer bufferRes = null;
        TrustManager[] tm = { new MyX509TrustManager() };
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // SSLContextSSLSocketFactory  
        SSLSocketFactory ssf = sslContext.getSocketFactory();

        URL urlGet = new URL(url);
        http = (HttpsURLConnection) urlGet.openConnection();
        // 
        http.setConnectTimeout(TIME_OUT_CONNECT);
        // ? --??
        http.setReadTimeout(TIME_OUT_READ);
        http.setRequestMethod("POST");
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        http.setSSLSocketFactory(ssf);
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();

        out = http.getOutputStream();
        out.write(params.getBytes("UTF-8"));
        out.flush();

        in = http.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
        String valueString = null;
        bufferRes = new StringBuffer();
        while ((valueString = read.readLine()) != null) {
            bufferRes.append(valueString);
        }

        return bufferRes.toString();

    } catch (Exception e) {
        logger.error(String.format("HTTP POST url=[%s] param=[%s] due to fail.", url, params), e);
    } finally {

        if (null != out) {
            try {
                out.close();
            } catch (IOException e) {
                logger.error(String.format("HTTP POST url=[%s] param=[%s]  close outputstream due to fail.",
                        url, params), e);
            }
        }
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error(String.format("HTTP POST url=[%s] param=[%s] close inputstream due to fail.", url,
                        params), e);
            }
        }

        if (http != null) {
            // 
            http.disconnect();

        }
    }
    return StringUtils.EMPTY;
}

From source file:com.unboundid.scim.sdk.examples.ClientExample.java

/**
 * Create an SSL-enabled Wink client config from the provided information.
 * The returned client config may be used to create a SCIM service object.
 * IMPORTANT: This should not be used in production because no validation
 * is performed on the server certificate returned by the SCIM service.
 *
 * @param userName    The HTTP Basic Auth user name.
 * @param password    The HTTP Basic Auth password.
 *
 * @return  An Apache Wink client config.
 */// w  w w. ja  v a2  s. c om
public static ClientConfig createHttpBasicClientConfig(final String userName, final String password) {
    SSLSocketFactory sslSocketFactory;
    try {
        final SSLContext sslContext = SSLContext.getInstance("TLS");

        // Do not use these settings in production.
        sslContext.init(null, new TrustManager[] { new BlindTrustManager() }, new SecureRandom());
        sslSocketFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (KeyManagementException e) {
        throw new RuntimeException(e.getLocalizedMessage());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getLocalizedMessage());
    }

    final HttpParams params = new BasicHttpParams();
    DefaultHttpClient.setDefaultHttpParams(params);
    params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, true);
    params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
    params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);

    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, sslSocketFactory));

    final PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(schemeRegistry);
    mgr.setMaxTotal(200);
    mgr.setDefaultMaxPerRoute(20);

    final DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params);

    final Credentials credentials = new UsernamePasswordCredentials(userName, password);
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);

    ClientConfig clientConfig = new ApacheHttpClientConfig(httpClient);
    clientConfig.setBypassHostnameVerification(true);

    return clientConfig;
}

From source file:com.axibase.tsd.client.HttpClient.java

private static void ignoreSslCertificateErrorInit(SSLContext sslContext) {
    try {/*from w  ww .  java 2 s . c  o m*/
        sslContext.init(null, 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];
            }
        } }, new SecureRandom());
    } catch (KeyManagementException e) {
        log.warn("SSL context initialization error: ", e);
    }
}

From source file:it.haefelinger.flaka.util.InitSSL.java

static public void install(TrustManager tm) throws Exception {
    // There's a problem (bug?) in Java 1.4 causing sc.init() to take a
    // very long time. Disabling installation of new trustmanager if
    // not 1.5 or newer. That's just fine cause 1.4 trustmanger accepts
    // self signed certificates.
    if (isjava15()) {
        SSLContext sc;
        sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { tm }, null);
        /* register with standard HTTP implementation */
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        /* register with Jakarta HTTPClient */
        Protocol https = new Protocol("https", new SSLSocketFactory(sc), 443);
        Protocol.registerProtocol("https", https);
    }//from  w w w . ja  v  a2s  .c o  m
}

From source file:ee.ria.xroad.common.request.ManagementRequestClient.java

private static CloseableHttpClient createHttpClient(KeyManager km, TrustManager tm) throws Exception {
    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create();

    sfr.register("http", PlainConnectionSocketFactory.INSTANCE);

    SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL);
    ctx.init(km != null ? new KeyManager[] { km } : null, tm != null ? new TrustManager[] { tm } : null,
            new SecureRandom());

    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(ctx,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    sfr.register("https", sf);

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(sfr.build());
    cm.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS);
    cm.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE);

    int timeout = SystemProperties.getClientProxyTimeout();
    int socketTimeout = SystemProperties.getClientProxyHttpClientTimeout();

    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);//w  ww . j  a  va2s .c o m
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(socketTimeout);

    HttpClientBuilder cb = HttpClients.custom();
    cb.setConnectionManager(cm);
    cb.setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    return cb.build();
}

From source file:com.gravspace.core.HttpServer.java

public static void start(String[] args) throws Exception {

    int port = 8082;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }/*from w  w w  .  ja  va  2 s.c  om*/

    ActorSystem system = ActorSystem.create("Application-System");
    Properties config = new Properties();
    config.load(HttpServer.class.getResourceAsStream("/megapode.conf"));
    ActorRef master = system.actorOf(Props.create(CoordinatingActor.class, config), "Coordinator");

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpHandler(system, master));

    // Set up the HTTP service
    HttpService httpService = new HttpService(httpproc, reqistry);

    SSLServerSocketFactory sf = null;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = HttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            System.out.println("Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        sf = sslcontext.getServerSocketFactory();
    }

    RequestListenerThread t = new RequestListenerThread(port, httpService, sf);
    t.setDaemon(false);
    t.start();

    t.join();
}

From source file:io.personium.core.utils.HttpClientFactory.java

/**
 * SSLSocket?./* w w  w  .  ja  v  a  2s  .  c om*/
 * @return ???SSLSocket
 */
private static SSLSocketFactory createInsecureSSLSocketFactory() {
    // CHECKSTYLE:OFF
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e1) {
        throw new RuntimeException(e1);
    }

    try {
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                // System.out.println("getAcceptedIssuers =============");
                X509Certificate[] ret = new X509Certificate[0];
                return ret;
            }

            public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
    } catch (KeyManagementException e1) {
        throw new RuntimeException(e1);
    }
    // CHECKSTYLE:ON

    HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    // socketFactory.setHostnameVerifier((X509HostnameVerifier)
    // hostnameVerifier);

    return socketFactory;
}

From source file:com.fujitsu.dc.test.jersey.HttpClientFactory.java

/**
 * SSLSocket?./*from w ww. ja v a  2 s .  co m*/
 * @return ???SSLSocket
 */
private static SSLSocketFactory createInsecureSSLSocketFactory() {
    // CHECKSTYLE:OFF
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e1) {
        throw new RuntimeException(e1);
    }

    try {
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                // System.out.println("getAcceptedIssuers =============");
                X509Certificate[] ret = new X509Certificate[0];
                return ret;
            }

            public final void checkClientTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkClientTrusted =============");
            }

            public final void checkServerTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
    } catch (KeyManagementException e1) {
        throw new RuntimeException(e1);
    }
    // CHECKSTYLE:ON

    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    // socketFactory.setHostnameVerifier((X509HostnameVerifier)
    // hostnameVerifier);

    return socketFactory;
}

From source file:io.personium.test.jersey.HttpClientFactory.java

/**
 * SSLSocket?./* ww  w.ja v a  2 s.co  m*/
 * @return ???SSLSocket
 */
private static SSLSocketFactory createInsecureSSLSocketFactory() {
    // CHECKSTYLE:OFF
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e1) {
        throw new RuntimeException(e1);
    }

    try {
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                // System.out.println("getAcceptedIssuers =============");
                X509Certificate[] ret = new X509Certificate[0];
                return ret;
            }

            public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
    } catch (KeyManagementException e1) {
        throw new RuntimeException(e1);
    }
    // CHECKSTYLE:ON

    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    // socketFactory.setHostnameVerifier((X509HostnameVerifier)
    // hostnameVerifier);

    return socketFactory;
}