Example usage for javax.net.ssl SSLContext getSocketFactory

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

Introduction

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

Prototype

public final SSLSocketFactory getSocketFactory() 

Source Link

Document

Returns a SocketFactory object for this context.

Usage

From source file:org.apache.jmeter.util.HttpSSLProtocolSocketFactory.java

private SSLSocketFactory getSSLSocketFactory() throws IOException {
    try {//from   w  w w . ja  v a 2s  .co  m
        SSLContext sslContext = this.sslManager.getContext();
        return sslContext.getSocketFactory();
    } catch (GeneralSecurityException ex) {
        throw new IOException("Rethrown as IOE", ex);
    }
}

From source file:org.apache.ftpserver.ssl.Ssl.java

/**
 * Returns a socket layered over an existing socket.
 *///from w  w w. ja v a2s .  c  o m
public Socket createSocket(String protocol, Socket soc, boolean clientMode) throws Exception {

    // already wrapped - no need to do anything
    if (soc instanceof SSLSocket) {
        return soc;
    }

    // get socket factory
    SSLContext ctx = getSSLContext(protocol);
    SSLSocketFactory socFactory = ctx.getSocketFactory();

    // create socket
    String host = soc.getInetAddress().getHostAddress();
    int port = soc.getLocalPort();
    SSLSocket ssoc = (SSLSocket) socFactory.createSocket(soc, host, port, true);
    ssoc.setUseClientMode(clientMode);

    // initialize socket
    String cipherSuites[] = ssoc.getSupportedCipherSuites();
    ssoc.setEnabledCipherSuites(cipherSuites);
    ssoc.setNeedClientAuth(m_clientAuthReqd);

    return ssoc;
}

From source file:org.openhab.binding.neato.internal.VendorVorwerk.java

/**
 * Trust the self signed certificate./*from ww  w  .  j a  va  2  s .c  o m*/
 *
 * @param connection
 */
public void applyNucleoSslConfiguration(HttpsURLConnection connection) {
    KeyStore keyStore;
    try {
        keyStore = KeyStore.getInstance("JKS");
        keyStore.load(this.getClass().getClassLoader().getResourceAsStream("keystore.jks"),
                "geheim".toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        SSLContext sslctx = SSLContext.getInstance("SSL");
        sslctx.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
        connection.setSSLSocketFactory(sslctx.getSocketFactory());
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:riddimon.android.asianetautologin.HttpManager.java

private HttpManager(Boolean debug, String version) {
    // Set basic data
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, true);
    HttpProtocolParams.setUserAgent(params, HttpUtils.userAgent);

    // Make pool// w  w w  .j  a  va  2s  .  c o m
    ConnPerRoute connPerRoute = new ConnPerRouteBean(12);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
    ConnManagerParams.setMaxTotalConnections(params, 20);

    // Set timeout
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Some client params
    HttpClientParams.setRedirecting(params, false);

    // Register http/s schemas!
    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    if (debug) {
        // Install the all-trusting trust manager
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustManagers = new X509TrustManager[1];
        trustManagers[0] = new TrustAllManager();

        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustManagers, null);
            schReg.register(new Scheme("https", (SocketFactory) sc.getSocketFactory(), 443));
        } catch (Exception e) {
            ;
        }
    } else {
        schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    }
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
    client = new DefaultHttpClient(conMgr, params);

}

From source file:com.jms.notify.utils.httpclient.SimpleHttpUtils.java

/**
 *
 * @param urlConn//from   w w w  . j a v  a2  s . c  o  m
 * @param sslVerify
 * @param hostnameVerify
 * @param trustCertFactory
 * @param clientKeyFactory
 */
private static void setSSLSocketFactory(HttpURLConnection urlConn, boolean sslVerify, boolean hostnameVerify,
        TrustKeyStore trustCertFactory, ClientKeyStore clientKeyFactory) {
    try {
        SSLSocketFactory socketFactory = null;
        if (trustCertFactory != null || clientKeyFactory != null || !sslVerify) {
            SSLContext sc = SSLContext.getInstance("SSL");
            TrustManager[] trustManagers = null;
            KeyManager[] keyManagers = null;
            if (trustCertFactory != null) {
                trustManagers = trustCertFactory.getTrustManagerFactory().getTrustManagers();
            }
            if (clientKeyFactory != null) {
                keyManagers = clientKeyFactory.getKeyManagerFactory().getKeyManagers();
            }
            if (!sslVerify) {
                trustManagers = trustAnyManagers;
                hostnameVerify = false;
            }
            sc.init(keyManagers, trustManagers, new java.security.SecureRandom());
            socketFactory = sc.getSocketFactory();
        }

        if (urlConn instanceof HttpsURLConnection) {
            HttpsURLConnection httpsUrlCon = (HttpsURLConnection) urlConn;
            if (socketFactory != null) {
                httpsUrlCon.setSSLSocketFactory(socketFactory);
            }
            //??hostname
            if (!hostnameVerify) {
                httpsUrlCon.setHostnameVerifier(new TrustAnyHostnameVerifier());
            }
        }
        if (urlConn instanceof com.sun.net.ssl.HttpsURLConnection) {
            com.sun.net.ssl.HttpsURLConnection httpsUrlCon = (com.sun.net.ssl.HttpsURLConnection) urlConn;
            if (socketFactory != null) {
                httpsUrlCon.setSSLSocketFactory(socketFactory);
            }
            //??hostname
            if (!hostnameVerify) {
                httpsUrlCon.setHostnameVerifier(new TrustAnyHostnameVerifierOld());
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.intuit.karate.ScriptContext.java

public void buildClient() {
    ClientBuilder clientBuilder = ClientBuilder.newBuilder().register(new LoggingFilter()) // must be first
            .register(MultiPartFeature.class).register(new RequestFilter());
    if (sslEnabled) {
        logger.info("ssl enabled, initializing generic trusted certificate / key-store with algorithm: {}",
                sslAlgorithm);/*w ww.  j ava  2  s.c  o  m*/
        SSLContext ssl = SslUtils.getSslContext(sslAlgorithm);
        HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
        clientBuilder.sslContext(ssl);
        clientBuilder.hostnameVerifier((host, session) -> true);
    }
    client = clientBuilder.build();
    if (connectTimeout != -1) {
        client.property(ClientProperties.CONNECT_TIMEOUT, connectTimeout);
    }
    if (readTimeout != -1) {
        client.property(ClientProperties.READ_TIMEOUT, readTimeout);
    }
    if (proxyUri != null) {
        client.property(ClientProperties.PROXY_URI, proxyUri);
    }
    if (proxyUsername != null) {
        client.property(ClientProperties.PROXY_USERNAME, proxyUsername);
    }
    if (proxyPassword != null) {
        client.property(ClientProperties.PROXY_PASSWORD, proxyPassword);
    }
}

From source file:ti.modules.titanium.network.NonValidatingSSLSocketFactory.java

public NonValidatingSSLSocketFactory() {
    try {// w w w.j av a2s .c  o m
        SSLContext context = SSLContext.getInstance("TLS");
        TrustManager managers[] = new TrustManager[] { new NonValidatingTrustManager() };
        context.init(null, managers, new SecureRandom());
        sslFactory = context.getSocketFactory();
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
    }

}

From source file:org.apache.hc.core5.http.benchmark.HttpBenchmark.java

public Results doExecute() throws Exception {

    final URL url = config.getUrl();
    final long endTime = System.currentTimeMillis() + config.getTimeLimit() * 1000;
    final HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    final ThreadPoolExecutor workerPool = new ThreadPoolExecutor(config.getThreads(), config.getThreads(), 5,
            TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {

                @Override/*w  w  w.j a v a  2  s . co m*/
                public Thread newThread(final Runnable r) {
                    return new Thread(r, "ClientPool");
                }

            });
    workerPool.prestartAllCoreThreads();

    SocketFactory socketFactory = null;
    if ("https".equals(host.getSchemeName())) {
        final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.setProtocol("SSL");
        if (config.isDisableSSLVerification()) {
            sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {

                @Override
                public boolean isTrusted(final X509Certificate[] chain, final String authType)
                        throws CertificateException {
                    return true;
                }

            });
        } else if (config.getTrustStorePath() != null) {
            sslContextBuilder.loadTrustMaterial(new File(config.getTrustStorePath()),
                    config.getTrustStorePassword() != null ? config.getTrustStorePassword().toCharArray()
                            : null);
        }
        if (config.getIdentityStorePath() != null) {
            sslContextBuilder.loadKeyMaterial(new File(config.getIdentityStorePath()),
                    config.getIdentityStorePassword() != null ? config.getIdentityStorePassword().toCharArray()
                            : null,
                    config.getIdentityStorePassword() != null ? config.getIdentityStorePassword().toCharArray()
                            : null);
        }
        final SSLContext sslContext = sslContextBuilder.build();
        socketFactory = sslContext.getSocketFactory();
    }

    final BenchmarkWorker[] workers = new BenchmarkWorker[config.getThreads()];
    for (int i = 0; i < workers.length; i++) {
        workers[i] = new BenchmarkWorker(host, createRequest(host), socketFactory, config);
        workerPool.execute(workers[i]);
    }

    while (workerPool.getCompletedTaskCount() < config.getThreads()) {
        Thread.yield();
        try {
            Thread.sleep(1000);
        } catch (final InterruptedException ignore) {
        }
        if (config.getTimeLimit() != -1 && System.currentTimeMillis() > endTime) {
            for (int i = 0; i < workers.length; i++) {
                workers[i].setShutdownSignal();
            }
        }
    }

    workerPool.shutdown();
    return ResultProcessor.collectResults(workers, host, config.getUrl().toString());
}

From source file:org.vsearchd.crawler.backend.BackendSessionHTTPS.java

private Scheme getHttpSslTheme(String url) throws Exception {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, getTrustManager(), null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    SSLSocketFactory socketFactory = new SSLSocketFactory(sc, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return new Scheme("https", Integer.valueOf(this.getBackendServer().getPort()), socketFactory);
}

From source file:com.ibm.iotf.client.AbstractClient.java

static SSLSocketFactory getSocketFactory(final String caCrtFile, final String crtFile, final String keyFile,
        final String password) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException {
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate caCert = null;

    if (caCrtFile != null) {
        // load CA certificate
        PEMReader reader = new PEMReader(
                new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
        caCert = (X509Certificate) reader.readObject();
        reader.close();/*  w w  w .ja  va  2s . c o  m*/
    } else {
        ClassLoader classLoader = AbstractClient.class.getClassLoader();
        PEMReader reader = new PEMReader(
                new InputStreamReader(classLoader.getResource(SERVER_MESSAGING_PEM).openStream()));
        caCert = (X509Certificate) reader.readObject();
        reader.close();
    }

    PEMReader reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
    X509Certificate cert = (X509Certificate) reader.readObject();
    reader.close();

    // load client private key
    reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))));
    KeyPair key = (KeyPair) reader.readObject();
    reader.close();

    TrustManagerFactory tmf = null;
    if (caCert != null) {
        // CA certificate is used to authenticate server
        KeyStore caKs = KeyStore.getInstance("JKS");
        //caKs.load(null, null);
        caKs.load(null, null);
        caKs.setCertificateEntry("ca-certificate", caCert);
        tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(caKs);
    }
    // client key and certificates are sent to server so it can authenticate us
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    ks.setCertificateEntry("certificate", cert);
    ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(),
            new java.security.cert.Certificate[] { cert });
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
    kmf.init(ks, password.toCharArray());

    // finally, create SSL socket factory
    SSLContext context = SSLContext.getInstance("TLSv1.2");
    if (tmf != null) {
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        context.init(kmf.getKeyManagers(), null, null);
    }

    return context.getSocketFactory();
}