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:com.iiordanov.tigervnc.rfb.CSecurityTLS.java

private void initGlobal() {
    try {/*  w w w.  ja va 2s .  c  o  m*/
        SSLSocketFactory sslfactory;
        SSLContext ctx = SSLContext.getInstance("TLS");

        if (anon) {
            ctx.init(null, null, null);
        } else {
            TrustManager[] myTM = new TrustManager[] { new MyX509TrustManager() };
            ctx.init(null, myTM, null);
        }

        sslfactory = ctx.getSocketFactory();
        try {
            ssl = (SSLSocket) sslfactory.createSocket(CConnection.sock,
                    CConnection.sock.getInetAddress().getHostName(), CConnection.sock.getPort(), true);
            ssl.setTcpNoDelay(true);
        } catch (java.io.IOException e) {
            throw new Exception(e.toString());
        }

        if (anon) {
            String[] supported;
            ArrayList<String> enabled = new ArrayList<String>();

            supported = ssl.getSupportedCipherSuites();

            for (int i = 0; i < supported.length; i++) {
                //Log.e("SUPPORTED CIPHERS", supported[i]);
                if (supported[i].matches("TLS_DH_anon.*"))
                    enabled.add(supported[i]);
            }

            if (enabled.size() == 0)
                throw new Exception("Your device lacks support for ciphers necessary for this encryption mode "
                        + "(Anonymous Diffie-Hellman ciphers). "
                        + "This is a known issue with devices running Android 2.2.x and older. You can "
                        + "work around this by using VeNCrypt with x509 certificates instead.");

            ssl.setEnabledCipherSuites(enabled.toArray(new String[0]));
        } else {
            ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites());
        }

        ssl.setEnabledProtocols(ssl.getSupportedProtocols());
        ssl.addHandshakeCompletedListener(new MyHandshakeListener());
    } catch (java.security.GeneralSecurityException e) {
        vlog.error("TLS handshake failed " + e.toString());
        return;
    }
}

From source file:de.thingweb.client.security.Security4NicePlugfest.java

public Security4NicePlugfest() {
    // Install the all-trusting trust manager
    // TODO setup trust-manager properly (not meant for production)
    try {/*  w ww .j a  v  a 2  s  . c  o  m*/
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = new TrustManager[] { new AllTrustingX509TrustManager() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (GeneralSecurityException e) {
        log.error(e.getMessage());
    }
}

From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java

@Override
public Socket createLayeredSocket(final Socket socket, final String target, final int port,
        final HttpContext context) throws IOException {

    final X509Credential credential = (X509Credential) context
            .getAttribute(HttpClientTransport.TRANSPORT_HTTP_CREDENTIALS);
    if (credential == null) {
        throw new IOException("Client credentials are missing from context.");
    }/*from w ww.ja  v  a  2s .c  o  m*/
    final SSLContext sslContext;
    try {
        sslContext = contextProvider.getContext(credential);
    } catch (GeneralSecurityException e) {
        throw new IOException("Failed to create SSLContext: " + e.getMessage(), e);
    }
    final SSLSocket sslsock = (SSLSocket) sslContext.getSocketFactory().createSocket(socket, target, port,
            true);
    if (supportedProtocols != null) {
        sslsock.setEnabledProtocols(supportedProtocols);
    } else {
        // If supported protocols are not explicitly set, remove all SSL protocol versions
        final String[] allProtocols = sslsock.getEnabledProtocols();
        final List<String> enabledProtocols = new ArrayList<String>(allProtocols.length);
        for (String protocol : allProtocols) {
            if (!protocol.startsWith("SSL")) {
                enabledProtocols.add(protocol);
            }
        }
        if (!enabledProtocols.isEmpty()) {
            sslsock.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
        }
    }
    if (supportedCipherSuites != null) {
        sslsock.setEnabledCipherSuites(supportedCipherSuites);
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Enabled protocols: {}", Arrays.asList(sslsock.getEnabledProtocols()));
        LOGGER.debug("Enabled cipher suites: {}", Arrays.asList(sslsock.getEnabledCipherSuites()));
    }

    prepareSocket(sslsock);
    LOGGER.debug("Starting handshake");
    sslsock.startHandshake();
    verifyHostname(sslsock, target);
    return sslsock;
}

From source file:org.apache.abdera.protocol.client.util.ClientAuthSSLProtocolSocketFactory.java

public Socket createSocket(String host, int port, InetAddress chost, int cport, HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {

    SSLContext context;
    SSLSocketFactory factory = null;
    SSLSocket socket = null;//from w ww  . j  av a 2 s  .  co  m
    try {
        KeyManagerFactory kmf;
        context = SSLContext.getInstance(protocol);
        kmf = KeyManagerFactory.getInstance(kmfFactory);
        TrustManager tm = (this.tm != null) ? this.tm : new NonOpTrustManager();
        kmf.init(ks, keyStorePass.toCharArray());
        context.init(kmf.getKeyManagers(), new TrustManager[] { tm }, null);
        factory = context.getSocketFactory();
        socket = (SSLSocket) factory.createSocket(host, port);
        return socket;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.nifi.processors.elasticsearch.AbstractElasticsearchHttpProcessor.java

@Override
protected void createElasticsearchClient(ProcessContext context) throws ProcessException {
    okHttpClientAtomicReference.set(null);

    OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();

    // Add a proxy if set
    final ProxyConfiguration proxyConfig = ProxyConfiguration.getConfiguration(context, () -> {
        final String proxyHost = context.getProperty(PROXY_HOST).evaluateAttributeExpressions().getValue();
        final Integer proxyPort = context.getProperty(PROXY_PORT).evaluateAttributeExpressions().asInteger();
        if (proxyHost != null && proxyPort != null) {
            final ProxyConfiguration componentProxyConfig = new ProxyConfiguration();
            componentProxyConfig.setProxyType(Proxy.Type.HTTP);
            componentProxyConfig.setProxyServerHost(proxyHost);
            componentProxyConfig.setProxyServerPort(proxyPort);
            componentProxyConfig.setProxyUserName(
                    context.getProperty(PROXY_USERNAME).evaluateAttributeExpressions().getValue());
            componentProxyConfig.setProxyUserPassword(
                    context.getProperty(PROXY_PASSWORD).evaluateAttributeExpressions().getValue());
            return componentProxyConfig;
        }/*from w  ww.j  a va2s. c  o m*/
        return ProxyConfiguration.DIRECT_CONFIGURATION;
    });

    if (!Proxy.Type.DIRECT.equals(proxyConfig.getProxyType())) {
        final Proxy proxy = proxyConfig.createProxy();
        okHttpClient.proxy(proxy);

        if (proxyConfig.hasCredential()) {
            okHttpClient.proxyAuthenticator(new Authenticator() {
                @Override
                public Request authenticate(Route route, Response response) throws IOException {
                    final String credential = Credentials.basic(proxyConfig.getProxyUserName(),
                            proxyConfig.getProxyUserPassword());
                    return response.request().newBuilder().header("Proxy-Authorization", credential).build();
                }
            });
        }
    }

    // Set timeouts
    okHttpClient.connectTimeout((context.getProperty(CONNECT_TIMEOUT).evaluateAttributeExpressions()
            .asTimePeriod(TimeUnit.MILLISECONDS).intValue()), TimeUnit.MILLISECONDS);
    okHttpClient.readTimeout(context.getProperty(RESPONSE_TIMEOUT).evaluateAttributeExpressions()
            .asTimePeriod(TimeUnit.MILLISECONDS).intValue(), TimeUnit.MILLISECONDS);

    final SSLContextService sslService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslService == null ? null
            : sslService.createSSLContext(SSLContextService.ClientAuth.NONE);

    // check if the ssl context is set and add the factory if so
    if (sslContext != null) {
        okHttpClient.sslSocketFactory(sslContext.getSocketFactory());
    }

    okHttpClientAtomicReference.set(okHttpClient.build());
}

From source file:edu.indiana.d2i.htrc.dataapi.DataAPIWrapper.java

private void initSSL(boolean isSelfSigned) throws NoSuchAlgorithmException, KeyManagementException {
    if (isSelfSigned) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }//from  w w  w  .  ja  v a 2s .co m

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

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

            @SuppressWarnings("unused")
            public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
                return true;
            }

            @SuppressWarnings("unused")
            public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
                return true;
            }
        } };

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

From source file:com.vuze.android.remote.AndroidUtils.java

private static boolean isURLAlive(String URLName, int conTimeout, int readTimeout) {
    try {//from  w  ww  .j  a  va 2s  . com
        HttpURLConnection.setFollowRedirects(false);

        URL url = new URL(URLName);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection conHttps = (HttpsURLConnection) con;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                SSLContext ctx = SSLContext.getInstance("TLS");
                ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() },
                        new SecureRandom());
                conHttps.setSSLSocketFactory(ctx.getSocketFactory());
            }

            conHttps.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }

        con.setConnectTimeout(conTimeout);
        con.setReadTimeout(readTimeout);
        con.setRequestMethod("HEAD");
        con.getResponseCode();
        if (DEBUG) {
            Log.d(TAG, "isLive? conn result=" + con.getResponseCode() + ";" + con.getResponseMessage());
        }
        return true;
    } catch (Exception e) {
        if (DEBUG) {
            Log.e(TAG, "isLive " + URLName, e);
        }
        return false;
    }
}

From source file:hudson.remoting.Launcher.java

/**
 * Bypass HTTPS security check by using free-for-all trust manager.
 *
 * @param _/*from ww  w .  j ava 2 s .c  om*/
 *      This is ignored.
 */
@Option(name = "-noCertificateCheck")
public void setNoCertificateCheck(boolean _) throws NoSuchAlgorithmException, KeyManagementException {
    System.out.println("Skipping HTTPS certificate checks altoghether. Note that this is not secure at all.");
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    // bypass host name check, too.
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
}

From source file:io.fabric8.elasticsearch.RequestRunner.java

protected final OkHttpClient getHttpClient() throws Exception {
    File ksFile = new File(keyStore);
    KeyStore trusted = KeyStore.getInstance("JKS");
    FileInputStream in = new FileInputStream(ksFile);
    trusted.load(in, password.toCharArray());
    in.close();/*from  w w w.  j  a v  a2  s. c o  m*/
    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManagerFactory trustManagerFactory = InsecureTrustManagerFactory.INSTANCE;
    X509TrustManager trustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    OkHttpClient client = new okhttp3.OkHttpClient.Builder()
            .sslSocketFactory(sslContext.getSocketFactory(), trustManager).readTimeout(1, TimeUnit.MINUTES)
            .writeTimeout(1, TimeUnit.MINUTES).build();
    return client;
}

From source file:org.kuali.mobility.push.dao.PushDaoImpl.java

private SSLSocket openConnectionToAPNS(String host, int port, String key, String passphrase) {
    SSLSocket socket;//from  ww  w.j a v a  2s  .c  om
    try {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        //          keyStore.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray());
        //          keyStore.load(getClass().getResourceAsStream("/newcert.p12"), "strange word to use".toCharArray());
        //          keyStore.load(this.getClass().getClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray());

        // This works when built with Eclipse, but not when built from command line. 
        // Has to do with where the build system puts /resources/*.p12 file
        //          keyStore.load(this.getClass().getClassLoader().getResourceAsStream(key), "strange word to use".toCharArray());

        // Currently only works when read from the server's FS. Won't currently read from within eclipse project. 
        // Putting it in /opt/kme/push prevents naming conflicts. 
        keyStore.load(new FileInputStream("/opt/kme/push/newcert.p12"), "strange word to use".toCharArray());

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
        keyManagerFactory.init(keyStore, "strange word to use".toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
        trustManagerFactory.init(keyStore);
        SSLContext sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
        SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
        socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
        socket.startHandshake();

        //Diagnostic output
        Enumeration e = keyStore.aliases();
        LOG.info(e.toString());
        while (e.hasMoreElements()) {
            LOG.info("Alias: " + e.nextElement().toString());
        }

        String not = (socket.isConnected()) ? "" : "NOT ";
        LOG.info("SSLSocket is " + not + "Connected");

        LOG.info("Connected to: " + socket.getInetAddress().getCanonicalHostName());
        LOG.info("Connected to: " + socket.getInetAddress().getHostAddress());

        String cs[] = socket.getEnabledCipherSuites();
        LOG.info("CipherSuites: " + Arrays.toString(cs));

        String ep[] = socket.getEnabledProtocols();
        LOG.info("Enabled Protocols: " + Arrays.toString(ep));

        LOG.info("Timeout: " + socket.getSoTimeout());
        LOG.info("Send Buffer Size: " + socket.getSendBufferSize());

        return socket;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}