Example usage for javax.net.ssl SSLContext getInstance

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

Introduction

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

Prototype

public static SSLContext getInstance(String protocol) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SSLContext object that implements the specified secure socket protocol.

Usage

From source file:org.couchpotato.CouchPotato.java

private CouchPotato(String scheme, String hostname, int port, String path, String api, String username,
        String password, boolean trustAll, String trustMe) {
    this.scheme = scheme;
    this.hostName = hostname;
    this.port = port;
    this.path = path;
    this.api = api;
    this.username = username;
    this.password = password;
    this.trustAll = trustAll;

    if (this.username == null)
        this.username = "";
    if (this.password == null)
        this.password = "";

    // Configure SSL behavior based on user preferences
    Authenticator.setDefault(new CouchAuthenticator(username, password, hostname));
    HostnameVerifier verifier;/*from   w w  w. j a v a2  s  .  co  m*/
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager(trustAll, trustMe) },
                new SecureRandom());
        if (trustAll) {
            verifier = new AllowAllHostnameVerifier();
        } else {
            verifier = new StrictHostnameVerifier();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(verifier);
    } catch (NoSuchAlgorithmException e) {

    } catch (KeyManagementException e) {

    } catch (KeyStoreException e) {

    }
}

From source file:io.hops.security.HopsUtil.java

/**
 * Set the default HTTPS trust policy to trust anything.
 *
 * NOTE: Use it only during development or use it wisely!
 *///w w  w .j ava2s.c om
public static void trustAllHTTPS() {
    try {
        final SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, trustAll, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    } catch (GeneralSecurityException ex) {
        throw new IllegalStateException("Could not initialize SSLContext for CRL fetcher", ex);
    }
}

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

private HttpUtils(Context context) {
    // private constructor to prevent instantiation
    this.context = context;
    try {//from w  w  w  .j a  va2 s.com
        // get version number to be set as part of user agent string
        version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
    }
    if (debug) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        try {
            TrustManager[] trustManagers = new X509TrustManager[1];
            trustManagers[0] = new TrustAllManager();

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustManagers, null);
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception ex) {
        }
    }
    // We don't enable response cache because this scenario requires fresh
    // data every time
    //enableHttpResponseCache();
}

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

void createMqttConnectOptions() {
    Optional<SSLContext> context = initTrustManagers().map(trustManagers -> {
        try {//from   w  ww .jav  a2s  .c  o m
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, trustManagers, new SecureRandom());
            return sslContext;
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "failed load", e);
            return null;
        }
    });

    options = new MqttConnectOptions();
    options.setUserName(userName);
    options.setPassword(password);
    context.ifPresent(sslContext -> options.setSocketFactory(sslContext.getSocketFactory()));
}

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//from w  w w.j a v a  2  s .com
    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:ee.ria.xroad.proxy.testsuite.DummyService.java

private ServerConnector createSslConnector() throws Exception {
    PKCS12 consumer = TestCertUtil.getConsumer();
    serverCert = consumer.cert;/*from  w  w w.  j  ava 2s .c o  m*/
    serverKey = consumer.key;

    SslContextFactory cf = new SslContextFactory(false);
    cf.setNeedClientAuth(true);

    cf.setIncludeCipherSuites(CryptoUtils.getINCLUDED_CIPHER_SUITES());
    cf.setSessionCachingEnabled(true);

    SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL);
    ctx.init(new KeyManager[] { new DummyServiceKeyManager() },
            new TrustManager[] { new DummyServiceTrustManager() }, new SecureRandom());

    cf.setSslContext(ctx);

    return new ServerConnector(this, cf);
}

From source file:oracle.custom.ui.utils.ServerUtils.java

public static SSLContext getContext() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager tms[] = new TrustManager[] { new X509TrustManager() {
        @Override//from  ww  w.  ja  v a2  s  .  c o m
        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tms, new SecureRandom());
    return context;
}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

/**
 * no-arg constructor for OkHttp client/*from  w w w  . j a  va2 s .  com*/
 */
public TankOkHttpClient() {
    try {

        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        } };

        // Setup SSL to accept all certs
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, null);
        sslSocketFactory = sslContext.getSocketFactory();

        // Setup Cookie manager
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(cookieManager);
        okHttpClient.setCookieHandler(cookieManager);

        okHttpClient.setConnectTimeout(30000, TimeUnit.MILLISECONDS);
        okHttpClient.setReadTimeout(30000, TimeUnit.MILLISECONDS); // Socket-timeout
        okHttpClient.setFollowRedirects(true);
        okHttpClient.setFollowSslRedirects(true);

        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

    } catch (Exception e) {
        LOG.error("Error setting accept all: " + e, e);
    }
}

From source file:com.screenslicer.common.LenientHttpsConfig.java

private LenientHttpsConfig() {
    AsyncHttpClientConfig configTmp = null;
    SSLContext sslContextTmp = null;
    try {/* w  w w  .ja  va 2s .  co  m*/
        AsyncHttpClient client = new AsyncHttpClient();
        configTmp = client.getConfig();
        IOUtils.closeQuietly(client);
        client = null;

        X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(CommonUtil.class.getResourceAsStream("screenslicer.internal.cert"));
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        keyStore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert);
        KeyManagerFactory keyManager = KeyManagerFactory.getInstance("SunX509");
        keyManager.init(keyStore, null);
        TrustManagerFactory trustManager = TrustManagerFactory.getInstance("X509");
        trustManager.init(keyStore);
        sslContextTmp = SSLContext.getInstance("TLS");
        sslContextTmp.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
    } catch (Throwable t) {
    }
    config = configTmp;
    sslContext = sslContextTmp;
}

From source file:com.aliyun.oss.common.comm.HttpClientFactory.java

private static SSLSocketFactory getSSLSocketFactory() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*from  w  w w.ja  va  2s.c  o m*/

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    try {
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(null, trustAllCerts, null);
        SSLSocketFactory ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return ssf;

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}