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:net.sf.taverna.t2.security.credentialmanager.impl.HTTPSConnectionAndTrustConfirmationIT.java

@After
// Clean up the credentialManagerDirectory we created for testing
public void cleanUp() throws NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException,
        KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {
    //      assertTrue(credentialManagerDirectory.exists());
    //      assertFalse(credentialManagerDirectory.listFiles().length == 0); // something was created there

    if (credentialManagerDirectory.exists()) {
        try {/*from ww  w . j a  va2 s.  c  o  m*/
            FileUtils.deleteDirectory(credentialManagerDirectory);
            System.out.println(
                    "Deleting Credential Manager's directory: " + credentialManagerDirectory.getAbsolutePath());
        } catch (IOException e) {
            System.out.println(e.getStackTrace());
        }
    }

    // Reset the SSLSocketFactory in JVM so we always have a clean start
    SSLContext sc = null;
    sc = SSLContext.getInstance("SSLv3");

    // Create a "default" JSSE X509KeyManager.
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    kmf.init(ks, "blah".toCharArray());

    // Create a "default" JSSE X509TrustManager.
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
    KeyStore ts = KeyStore.getInstance("JKS");
    ts.load(null, null);
    tmf.init(ts);

    sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    SSLContext.setDefault(sc);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}

From source file:com.axibase.tsd.driver.jdbc.protocol.SdkProtocolImpl.java

private void doTrustToCertificates(final HttpsURLConnection sslConnection) {
    final SSLContext sslContext;
    try {/*ww  w .  ja v  a  2 s.c  o  m*/
        sslContext = SSLContext.getInstance(CONTEXT_INSTANCE_TYPE);
    } catch (NoSuchAlgorithmException e) {
        if (logger.isErrorEnabled()) {
            logger.error(e.getMessage());
        }
        return;
    }
    final boolean trusted = contentDescription.isTrusted();
    if (logger.isDebugEnabled()) {
        logger.debug("[doTrustToCertificates] " + trusted);
    }
    try {
        sslContext.init(null, trusted ? DUMMY_TRUST_MANAGER : null, new SecureRandom());
    } catch (KeyManagementException e) {
        if (logger.isErrorEnabled()) {
            logger.error(e.getMessage());
        }
        return;
    }
    sslConnection.setSSLSocketFactory(sslContext.getSocketFactory());

    if (trusted) {
        sslConnection.setHostnameVerifier(DUMMY_HOSTNAME_VERIFIER);
    }
}

From source file:org.whispersystems.textsecure.push.PushServiceSocket.java

private HttpURLConnection getConnection(String urlFragment, String method, String body)
        throws PushNetworkException {
    try {/*from w  w w.j  av a  2s.  co m*/
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, trustManagers, null);

        URL url = new URL(String.format("%s%s", serviceUrl, urlFragment));
        Log.w("PushServiceSocket", "Push service URL: " + serviceUrl);
        Log.w("PushServiceSocket", "Opening URL: " + url);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        if (ENFORCE_SSL) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(context.getSocketFactory());
            ((HttpsURLConnection) connection).setHostnameVerifier(new StrictHostnameVerifier());
        }

        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", "application/json");

        if (password != null) {
            connection.setRequestProperty("Authorization", getAuthorizationHeader());
        }

        if (body != null) {
            connection.setDoOutput(true);
        }

        connection.connect();

        if (body != null) {
            Log.w("PushServiceSocket", method + "  --  " + body);
            OutputStream out = connection.getOutputStream();
            out.write(body.getBytes());
            out.close();
        }

        return connection;
    } catch (IOException e) {
        throw new PushNetworkException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    } catch (KeyManagementException e) {
        throw new AssertionError(e);
    }
}

From source file:com.almarsoft.GroundhogReader.lib.ServerManager.java

private void connect() throws SocketException, IOException, ServerAuthException {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);

    String tmpPort = prefs.getString("port", "119");

    if (tmpPort != null)
        tmpPort = tmpPort.trim();/*from  ww  w. j  a  v  a2s  .c  om*/

    if (tmpPort == null || tmpPort.length() == 0) {
        // Fix for migrating f*cked config files (from a bug in a previous version)
        tmpPort = "119";
        Editor edit = prefs.edit();
        edit.putString("port", tmpPort);
        edit.commit();
    }

    int port = new Integer(tmpPort);
    boolean needsAuth = prefs.getBoolean("needsAuth", false);

    String host = prefs.getString("host", null);
    if (host != null)
        host = host.trim();

    String clogin = prefs.getString("login", null);
    if (clogin != null)
        clogin = clogin.trim();

    String cpass = prefs.getString("pass", null);
    if (cpass != null)
        cpass = cpass.trim();

    boolean useSSL = prefs.getBoolean("useSSL", false);
    boolean trustAllCertificates = prefs.getBoolean("trustAllCertificates", false);

    mClient = new NNTPExtended();

    if (useSSL) {
        Log.i("CgroundhogReader.lib.ServerManager", "Using SSL...");
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(host, !trustAllCertificates) },
                    new SecureRandom());
            mClient.setSocketFactory(sslContext.getSocketFactory());
        } catch (KeyManagementException e) {
            Log.e("GroundhogReader.lib.ServerManager", "Caught KeyManagementException", e);
        } catch (NoSuchAlgorithmException e) {
            Log.e("GroundhogReader.lib.ServerManager", "Caught NoSuchAlgorihmException", e);
        }
    }

    // Get the configuration host, port, username and pass
    mClient.connect(host, port);

    if (needsAuth) {
        if (!mClient.authenticate(clogin, cpass)) {
            throw new ServerAuthException();
        }
    }
}

From source file:org.kurento.test.base.BrowserTest.java

public void waitForHostIsReachable(URL url, int timeout) {
    long timeoutMillis = TimeUnit.MILLISECONDS.convert(timeout, TimeUnit.SECONDS);
    long endTimeMillis = System.currentTimeMillis() + timeoutMillis;

    log.debug("Waiting for {} to be reachable (timeout {} seconds)", url, timeout);

    try {/*  w  ww .  j av  a  2 s  .c  o m*/
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

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

        int responseCode = 0;
        while (true) {
            try {
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout((int) timeoutMillis);
                connection.setReadTimeout((int) timeoutMillis);
                connection.setRequestMethod("HEAD");
                responseCode = connection.getResponseCode();

                break;
            } catch (SSLHandshakeException | SocketException e) {
                log.warn("Error {} waiting URL {}, trying again in 1 second", e.getMessage(), url);
                // Polling to wait a consistent SSL state
                Thread.sleep(1000);
            }
            if (System.currentTimeMillis() > endTimeMillis) {
                break;
            }
        }

        if (responseCode != HttpURLConnection.HTTP_OK) {
            log.warn("URL " + url + " not reachable. Response code=" + responseCode);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("URL " + url + " not reachable in " + timeout + " seconds (" + e.getClass().getName() + ", "
                + e.getMessage() + ")");
    }

    log.debug("URL {} already reachable", url);
}

From source file:org.apache.jmeter.protocol.amf.proxy.AmfProxy.java

/**
 * Get SSL connection from hashmap, creating it if necessary.
 *
 * @param host//from  w w  w. j  a  v a 2  s . c om
 * @return a ssl socket factory
 * @throws IOException
 */
private SSLSocketFactory getSSLSocketFactory(String host) throws IOException {
    synchronized (hashHost) {
        if (hashHost.containsKey(host)) {
            log.debug("Good, already in map, host=" + host);
            return hashHost.get(host);
        }
        InputStream in = getCertificate();
        Exception except = null;
        if (in != null) {
            KeyStore ks = null;
            KeyManagerFactory kmf = null;
            SSLContext sslcontext = null;
            try {
                ks = KeyStore.getInstance(KEYSTORE_TYPE);
                ks.load(in, KEYSTORE_PASSWORD);
                kmf = KeyManagerFactory.getInstance(KEYMANAGERFACTORY);
                kmf.init(ks, KEY_PASSWORD);
                sslcontext = SSLContext.getInstance(SSLCONTEXT_PROTOCOL);
                sslcontext.init(kmf.getKeyManagers(), null, null);
                SSLSocketFactory sslFactory = sslcontext.getSocketFactory();
                hashHost.put(host, sslFactory);
                log.info("KeyStore for SSL loaded OK and put host in map (" + host + ")");
                return sslFactory;
            } catch (NoSuchAlgorithmException e) {
                except = e;
            } catch (KeyManagementException e) {
                except = e;
            } catch (KeyStoreException e) {
                except = e;
            } catch (UnrecoverableKeyException e) {
                except = e;
            } catch (CertificateException e) {
                except = e;
            } finally {
                if (except != null) {
                    log.error("Problem with SSL certificate", except);
                }
                IOUtils.closeQuietly(in);
            }
        } else {
            throw new IOException("Unable to read keystore");
        }
        return null;
    }
}

From source file:org.apache.camel.component.file.remote.FtpsEndpoint.java

/**
 * Create the FTPS client./*from   w  w w .  j a  va  2  s .  co  m*/
 */
protected FTPClient createFtpClient() throws Exception {
    FTPSClient client = null;

    if (sslContextParameters != null) {
        SSLContext context = sslContextParameters.createSSLContext();

        client = new FTPSClient(getFtpsConfiguration().isImplicit(), context);

        // The FTPSClient tries to manage the following SSLSocket related configuration options
        // on its own based on internal configuration options.  FTPSClient does not lend itself
        // to subclassing for the purpose of overriding this behavior (private methods, fields, etc.).
        // As such, we create a socket (preconfigured by SSLContextParameters) from the context
        // we gave to FTPSClient and then setup FTPSClient to reuse the already configured configuration
        // from the socket for all future sockets it creates.  Not sexy and a little brittle, but it works.
        SSLSocket socket = (SSLSocket) context.getSocketFactory().createSocket();
        client.setEnabledCipherSuites(socket.getEnabledCipherSuites());
        client.setEnabledProtocols(socket.getEnabledProtocols());
        client.setNeedClientAuth(socket.getNeedClientAuth());
        client.setWantClientAuth(socket.getWantClientAuth());
        client.setEnabledSessionCreation(socket.getEnableSessionCreation());
    } else {
        client = new FTPSClient(getFtpsConfiguration().getSecurityProtocol(),
                getFtpsConfiguration().isImplicit());

        if (ftpClientKeyStoreParameters != null) {
            String type = (ftpClientKeyStoreParameters.containsKey("type"))
                    ? (String) ftpClientKeyStoreParameters.get("type")
                    : KeyStore.getDefaultType();
            String file = (String) ftpClientKeyStoreParameters.get("file");
            String password = (String) ftpClientKeyStoreParameters.get("password");
            String algorithm = (ftpClientKeyStoreParameters.containsKey("algorithm"))
                    ? (String) ftpClientKeyStoreParameters.get("algorithm")
                    : KeyManagerFactory.getDefaultAlgorithm();
            String keyPassword = (String) ftpClientKeyStoreParameters.get("keyPassword");

            KeyStore keyStore = KeyStore.getInstance(type);
            FileInputStream keyStoreFileInputStream = new FileInputStream(new File(file));
            try {
                keyStore.load(keyStoreFileInputStream, password.toCharArray());
            } finally {
                IOHelper.close(keyStoreFileInputStream, "keyStore", log);
            }

            KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(algorithm);
            keyMgrFactory.init(keyStore, keyPassword.toCharArray());
            client.setNeedClientAuth(true);
            client.setKeyManager(keyMgrFactory.getKeyManagers()[0]);
        }

        if (ftpClientTrustStoreParameters != null) {
            String type = (ftpClientTrustStoreParameters.containsKey("type"))
                    ? (String) ftpClientTrustStoreParameters.get("type")
                    : KeyStore.getDefaultType();
            String file = (String) ftpClientTrustStoreParameters.get("file");
            String password = (String) ftpClientTrustStoreParameters.get("password");
            String algorithm = (ftpClientTrustStoreParameters.containsKey("algorithm"))
                    ? (String) ftpClientTrustStoreParameters.get("algorithm")
                    : TrustManagerFactory.getDefaultAlgorithm();

            KeyStore trustStore = KeyStore.getInstance(type);
            FileInputStream trustStoreFileInputStream = new FileInputStream(new File(file));
            try {
                trustStore.load(trustStoreFileInputStream, password.toCharArray());
            } finally {
                IOHelper.close(trustStoreFileInputStream, "trustStore", log);
            }

            TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(algorithm);
            trustMgrFactory.init(trustStore);

            client.setTrustManager(trustMgrFactory.getTrustManagers()[0]);
        }
    }

    return client;
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

private javax.net.ssl.SSLSocketFactory getProviderSSLSocketFactory() throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException {
    String provider_cert_string = preferences.getString(Provider.CA_CERT, "");

    java.security.cert.Certificate provider_certificate = ConfigHelper
            .parseX509CertificateFromString(provider_cert_string);

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);/*  ww  w .  j  av a 2  s.  c o  m*/
    keyStore.setCertificateEntry("provider_ca_certificate", provider_certificate);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);

    return context.getSocketFactory();
}

From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.i2b2.I2B2XMLResourceImplementation.java

private HttpClientBuilder ignoreCertificate() throws NoSuchAlgorithmException, KeyManagementException {
    System.setProperty("jsse.enableSNIExtension", "false");

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

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }//  www  .j a  v  a 2 s.c  om

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

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

    SSLContext sslContext;

    sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);

    Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslsf).build();

    HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);

    return HttpClients.custom().setConnectionManager(cm);
}