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:Main.java

public static void disableSSLCertificateChecking() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*from ww w. j  av a  2s  .co  m*/

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("TLS");

        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/**
 * Disables the SSL certificate checking for new instances of {@link HttpsURLConnection} This has been created to
 * aid testing on a local box, not for use on production.
 *//*from w w w  . j a v  a2s .c  o m*/
private static void disableSSLCertificateChecking() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("TLS");

        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/**
 * Trust every server - dont check for any certificate
 *///from w w w. j  av a2 s . co m
private static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub

        }
    } };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        HttpsURLConnection.setDefaultHostnameVerifier(DO_NOT_VERIFY);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.lolay.android.security.OpenX509TrustManager.java

public static void openTrust() {
    LolayLog.w(TAG, "openTrust", "THIS IS AN OPEN TRUST MANAGER FOR DEBUGGING ONLY!");
    try {//from  w w w.  java  2  s . c  om
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new OpenX509TrustManager() }, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        LolayLog.e(TAG, "openTrust", "Could not open the trust", e);
    }
}

From source file:Main.java

/**
 * Trust every server - dont check for any certificate
 *///from   w  ww .  j a  v  a2 s .c  o  m
static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

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

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

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws CertificateException {
            // TODO Auto-generated method stub

        }
    } };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.hashes.HttpsClient.java

private static SocketFactory buildSocketFactory() {
    SocketFactory socketFactory;//from ww  w  .  ja  v a2  s.  co m

    try {
        final SSLContext sslContext = SSLContext.getInstance(SSL_CONTEXT_PROTOCOL);
        sslContext.init(null, new TrustManager[] { new NaiveX509TrustManager() }, null);
        socketFactory = sslContext.getSocketFactory();
    } catch (final Exception e) {
        LOG.warn("Could not disable certificate validation", e);
        socketFactory = SSLSocketFactory.getDefault();
    }

    return socketFactory;
}

From source file:Main.java

public static void trustAllHosts(boolean trustAnyCert, boolean trustAnyHost) {
    try {//  www.j  a va 2 s.  c  om
        if (trustAnyCert) {
            X509TrustManager easyTrustManager = new X509TrustManager() {

                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Oh, I am easy!
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Oh, I am easy!
                }

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

            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { easyTrustManager };

            // Install the all-trusting trust manager

            SSLContext sc = SSLContext.getInstance("TLS");

            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        }

        if (trustAnyHost) {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.glite.slcs.SLCSBaseClient.java

static protected void registerSSLTrustStore(SLCSClientConfiguration configuration) throws SLCSException {
    String truststorePath = getDefaultHttpClientTrustStoreFile(configuration);
    try {// w ww.ja v a2s.c o  m
        ExtendedProtocolSocketFactory epsf = new ExtendedProtocolSocketFactory(truststorePath);
        Protocol https = new Protocol("https", (ProtocolSocketFactory) epsf, 443);
        Protocol.registerProtocol("https", https);
        // BUG FIX: register the truststore as default SSLSocketFactory
        // to download the metadata from https (QuoVadis CAs not in all default cacerts)
        LOG.info(
                "register ExtendedProtocolSocketFactory(" + truststorePath + ") as default SSL socket factory");
        SSLContext sc = epsf.getSSLContext();
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        LOG.error(e);
        throw new SLCSException("Failed to create ExtendedProtocolSocketFactory", e);
    }

}

From source file:proxy.ElementalHttpGet.java

private static void request(HttpProcessor httpproc, HttpRequestExecutor httpexecutor,
        HttpCoreContext coreContext, HttpHost host, InetAddress localinetAddress)
        throws NoSuchAlgorithmException, IOException, HttpException {
    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;
    try {/*from   w  ww.j ava2s.  c om*/

        String[] targets = { "/2/users/show.json?access_token=2.00SlDQsDdcZIJC94e5308f67sRL13D&uid=3550148352",
                "/account/rate_limit_status.json?access_token=2.00SlDQsDdcZIJC94e5308f67sRL13D" };

        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                SSLContext sslcontext = SSLContext.getInstance("Default");
                //               sslcontext.init(null, null, null);
                SocketFactory sf = sslcontext.getSocketFactory();
                SSLSocket socket = (SSLSocket) sf.createSocket(host.getHostName(), host.getPort(),
                        localinetAddress, 0);
                socket.setEnabledCipherSuites(new String[] { "TLS_RSA_WITH_AES_256_CBC_SHA",
                        "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" });
                conn.bind(socket);
                //               Socket socket = new Socket(host.getHostName(), host.getPort());
                //               conn.bind(socket);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:net.sf.jsignpdf.ssl.SSLInitializer.java

/**
 * @param options//from w  w  w .jav a 2 s . c o  m
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws CertificateException
 * @throws KeyStoreException
 * @throws KeyManagementException
 * @throws UnrecoverableKeyException
 */
public static void init(BasicSignerOptions options) throws NoSuchAlgorithmException, KeyManagementException,
        KeyStoreException, CertificateException, IOException, UnrecoverableKeyException {
    KeyManager[] km = null;
    if (options != null && options.getTsaServerAuthn() == ServerAuthentication.CERTIFICATE) {
        char[] pwd = null;
        if (StringUtils.isNotEmpty(options.getTsaCertFilePwd())) {
            pwd = options.getTsaCertFilePwd().toCharArray();
        }
        LOGGER.info(Constants.RES.get("ssl.keymanager.init", options.getTsaCertFile()));
        final String ksType = StringUtils.defaultIfBlank(options.getTsaCertFileType(), "PKCS12");
        KeyStore keyStore = KeyStoreUtils.loadKeyStore(ksType, options.getTsaCertFile(), pwd);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, pwd);
        km = keyManagerFactory.getKeyManagers();
    }
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(km, TRUST_MANAGERS, null);

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}