Example usage for javax.net.ssl SSLSocket setEnabledCipherSuites

List of usage examples for javax.net.ssl SSLSocket setEnabledCipherSuites

Introduction

In this page you can find the example usage for javax.net.ssl SSLSocket setEnabledCipherSuites.

Prototype

public abstract void setEnabledCipherSuites(String suites[]);

Source Link

Document

Sets the cipher suites enabled for use on this connection.

Usage

From source file:github.popeen.dsub.service.ssl.SSLSocketFactory.java

@SuppressWarnings("cast")
public Socket createSocket() throws IOException {
    // the cast makes sure that the factory is working as expected
    SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket();
    sslSocket.setEnabledProtocols(getProtocols(sslSocket));
    sslSocket.setEnabledCipherSuites(getCiphers(sslSocket));
    return sslSocket;
}

From source file:github.popeen.dsub.service.ssl.SSLSocketFactory.java

/**
 * @param params Optional parameters. Parameters passed to this method will have no effect.
 *               This method will create a unconnected instance of {@link Socket} class
 *               using {@link javax.net.ssl.SSLSocketFactory#createSocket()} method.
 * @since 4.1// www .  j  av  a  2  s.  c o m
 */
@SuppressWarnings("cast")
public Socket createSocket(final HttpParams params) throws IOException {
    // the cast makes sure that the factory is working as expected
    SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket();
    sslSocket.setEnabledProtocols(getProtocols(sslSocket));
    sslSocket.setEnabledCipherSuites(getCiphers(sslSocket));
    return sslSocket;
}

From source file:org.opcfoundation.ua.transport.https.HttpsClient.java

/**
 * Initialize HttpsClient. //www .ja  va  2s . c om
 * 
 * @param connectUrl
 * @param tcs
 */
public void initialize(String connectUrl, TransportChannelSettings tcs, EncoderContext ctx)
        throws ServiceResultException {

    this.connectUrl = connectUrl;
    this.securityPolicyUri = tcs.getDescription().getSecurityPolicyUri();
    this.transportChannelSettings = tcs;
    HttpsSettings httpsSettings = tcs.getHttpsSettings();
    HttpsSecurityPolicy[] policies = httpsSettings.getHttpsSecurityPolicies();
    if (policies != null && policies.length > 0)
        securityPolicy = policies[policies.length - 1];
    else
        securityPolicy = HttpsSecurityPolicy.TLS_1_1;
    // securityPolicy = SecurityPolicy.getSecurityPolicy( this.securityPolicyUri );
    if (securityPolicy != HttpsSecurityPolicy.TLS_1_0 && securityPolicy != HttpsSecurityPolicy.TLS_1_1
            && securityPolicy != HttpsSecurityPolicy.TLS_1_2)
        throw new ServiceResultException(StatusCodes.Bad_SecurityChecksFailed,
                "Https Client doesn't support securityPolicy " + securityPolicy);
    if (logger.isDebugEnabled()) {
        logger.debug("initialize: url={}; settings={}", tcs.getDescription().getEndpointUrl(),
                ObjectUtils.printFields(tcs));
    }

    // Setup Encoder
    EndpointConfiguration endpointConfiguration = tcs.getConfiguration();
    encoderCtx = ctx;
    encoderCtx.setMaxArrayLength(
            endpointConfiguration.getMaxArrayLength() != null ? endpointConfiguration.getMaxArrayLength() : 0);
    encoderCtx.setMaxStringLength(
            endpointConfiguration.getMaxStringLength() != null ? endpointConfiguration.getMaxStringLength()
                    : 0);
    encoderCtx.setMaxByteStringLength(endpointConfiguration.getMaxByteStringLength() != null
            ? endpointConfiguration.getMaxByteStringLength()
            : 0);
    encoderCtx.setMaxMessageSize(
            endpointConfiguration.getMaxMessageSize() != null ? endpointConfiguration.getMaxMessageSize() : 0);

    timer = TimerUtil.getTimer();
    try {
        SchemeRegistry sr = new SchemeRegistry();
        if (protocol.equals(UriUtil.SCHEME_HTTPS)) {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(httpsSettings.getKeyManagers(), httpsSettings.getTrustManagers(), null);
            X509HostnameVerifier hostnameVerifier = httpsSettings.getHostnameVerifier() != null
                    ? httpsSettings.getHostnameVerifier()
                    : SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, hostnameVerifier) {
                protected void prepareSocket(javax.net.ssl.SSLSocket socket) throws IOException {
                    socket.setEnabledCipherSuites(cipherSuites);
                };
            };

            SSLEngine sslEngine = sslcontext.createSSLEngine();
            String[] enabledCipherSuites = sslEngine.getEnabledCipherSuites();
            cipherSuites = CryptoUtil.filterCipherSuiteList(enabledCipherSuites,
                    securityPolicy.getCipherSuites());

            logger.info("Enabled protocols in SSL Engine are {}",
                    Arrays.toString(sslEngine.getEnabledProtocols()));
            logger.info("Enabled CipherSuites in SSL Engine are {}", Arrays.toString(enabledCipherSuites));
            logger.info("Client CipherSuite selection for {} is {}", securityPolicy.getPolicyUri(),
                    Arrays.toString(cipherSuites));

            Scheme https = new Scheme("https", 443, sf);
            sr.register(https);
        }

        if (protocol.equals(UriUtil.SCHEME_HTTP)) {
            Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
            sr.register(http);
        }

        if (ccm == null) {
            PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(sr);
            ccm = pccm;
            pccm.setMaxTotal(maxConnections);
            pccm.setDefaultMaxPerRoute(maxConnections);
        }
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams,
                transportChannelSettings.getConfiguration().getOperationTimeout());
        HttpConnectionParams.setSoTimeout(httpParams, 0);
        httpclient = new DefaultHttpClient(ccm, httpParams);

        // Set username and password authentication
        if (httpsSettings.getUsername() != null && httpsSettings.getPassword() != null) {
            BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(httpsSettings.getUsername(), httpsSettings.getPassword()));
            httpclient.setCredentialsProvider(credsProvider);
        }

    } catch (NoSuchAlgorithmException e) {
        new ServiceResultException(e);
    } catch (KeyManagementException e) {
        new ServiceResultException(e);
    }

}

From source file:github.popeen.dsub.service.ssl.SSLSocketFactory.java

/**
 * @deprecated Use {@link #createLayeredSocket(Socket, String, int, boolean)}
 *//*from   w w w  .j a v a  2 s. c  o  m*/
@Deprecated
public Socket createSocket(final Socket socket, final String host, int port, boolean autoClose)
        throws IOException, UnknownHostException {
    SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(socket, host, port, autoClose);
    sslSocket.setEnabledProtocols(getProtocols(sslSocket));
    sslSocket.setEnabledCipherSuites(getCiphers(sslSocket));
    setHostName(sslSocket, host);
    return sslSocket;
}

From source file:github.popeen.dsub.service.ssl.SSLSocketFactory.java

/**
 * @since 4.1//w  w  w.  j av  a2s .c om
 */
public Socket createLayeredSocket(final Socket socket, final String host, final int port,
        final boolean autoClose) throws IOException, UnknownHostException {
    SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(socket, host, port, autoClose);
    sslSocket.setEnabledProtocols(getProtocols(sslSocket));
    sslSocket.setEnabledCipherSuites(getCiphers(sslSocket));
    if (this.hostnameVerifier != null) {
        this.hostnameVerifier.verify(host, sslSocket);
    }
    // verifyHostName() didn't blowup - good!
    return sslSocket;
}

From source file:org.lightcouch.CouchDbClientBase.java

/**
 * @return {@link DefaultHttpClient} instance.
 *//*from ww w .  j  ava  2s.c  om*/
private HttpClient createHttpClient(CouchDbProperties props) {
    DefaultHttpClient httpclient = null;
    try {
        SchemeSocketFactory ssf = null;
        if (props.getProtocol().equals("https")) {
            TrustManager trustManager = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

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

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] { trustManager }, null);
            ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            SSLSocket socket = (SSLSocket) ssf.createSocket(null);
            socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" });
        } else {
            ssf = PlainSocketFactory.getSocketFactory();
        }
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme(props.getProtocol(), props.getPort(), ssf));
        PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);
        httpclient = new DefaultHttpClient(ccm);
        host = new HttpHost(props.getHost(), props.getPort(), props.getProtocol());
        context = new BasicHttpContext();
        // Http params
        httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout());
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                props.getConnectionTimeout());
        int maxConnections = props.getMaxConnections();
        if (maxConnections != 0) {
            ccm.setMaxTotal(maxConnections);
            ccm.setDefaultMaxPerRoute(maxConnections);
        }
        if (props.getProxyHost() != null) {
            HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort());
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        // basic authentication
        if (props.getUsername() != null && props.getPassword() != null) {
            httpclient.getCredentialsProvider().setCredentials(new AuthScope(props.getHost(), props.getPort()),
                    new UsernamePasswordCredentials(props.getUsername(), props.getPassword()));
            props.clearPassword();
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(host, basicAuth);
            context.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }
        // request interceptor
        httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context) throws IOException {
                if (log.isInfoEnabled())
                    log.info(">> " + request.getRequestLine());
            }
        });
        // response interceptor
        httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
            public void process(final HttpResponse response, final HttpContext context) throws IOException {
                validate(response);
                if (log.isInfoEnabled())
                    log.info("<< Status: " + response.getStatusLine().getStatusCode());
            }
        });
    } catch (Exception e) {
        log.error("Error Creating HTTP client. " + e.getMessage());
        throw new IllegalStateException(e);
    }
    return httpclient;
}

From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java

@SuppressWarnings("deprecation")
@Test//from  ww w  .  j a  va  2s. c o  m
public void testSSLConnection() throws Exception {
    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
    SSLSocketFactory ssf = new SSLSocketFactory(SSLContext.getInstance("TLS"));
    ssf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", ssf, 443);
    SchemeRegistry sr = new SchemeRegistry();
    sr.register(http);
    sr.register(https);

    TrustManager easyTrustManager = new X509TrustManager() {

        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) {
            System.out.println("checkClientTrusted");
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) {
            System.out.println("checkServerTrusted");
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            System.out.println("getAcceptedIssuers");
            return null;
        }
    };

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    SSLSocket socket = (SSLSocket) sf.createSocket();
    socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" });
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);
    sf.connectSocket(socket, "119.29.234.42", 443, null, -1, params);
}

From source file:com.irccloud.android.HTTPFetcher.java

private void http_thread() {
    try {/*from   w w  w  .j  a v a2s .co  m*/
        mThread.setName("http-stream-thread");
        int port = (mURI.getPort() != -1) ? mURI.getPort() : (mURI.getProtocol().equals("https") ? 443 : 80);

        String path = TextUtils.isEmpty(mURI.getPath()) ? "/" : mURI.getPath();
        if (!TextUtils.isEmpty(mURI.getQuery())) {
            path += "?" + mURI.getQuery();
        }

        PrintWriter out = new PrintWriter(mSocket.getOutputStream());

        if (mProxyHost != null && mProxyHost.length() > 0 && mProxyPort > 0) {
            out.print("CONNECT " + mURI.getHost() + ":" + port + " HTTP/1.0\r\n");
            out.print("\r\n");
            out.flush();
            HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(
                    mSocket.getInputStream());

            // Read HTTP response status line.
            StatusLine statusLine = parseStatusLine(readLine(stream));
            if (statusLine == null) {
                throw new HttpException("Received no reply from server.");
            } else if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }

            // Read HTTP response headers.
            while (!TextUtils.isEmpty(readLine(stream)))
                ;
            if (mURI.getProtocol().equals("https")) {
                mSocket = getSSLSocketFactory().createSocket(mSocket, mURI.getHost(), port, false);
                SSLSocket s = (SSLSocket) mSocket;
                try {
                    s.setEnabledProtocols(ENABLED_PROTOCOLS);
                } catch (IllegalArgumentException e) {
                    //Not supported on older Android versions
                }
                try {
                    s.setEnabledCipherSuites(ENABLED_CIPHERS);
                } catch (IllegalArgumentException e) {
                    //Not supported on older Android versions
                }
                out = new PrintWriter(mSocket.getOutputStream());
            }
        }

        if (mURI.getProtocol().equals("https")) {
            SSLSocket s = (SSLSocket) mSocket;
            StrictHostnameVerifier verifier = new StrictHostnameVerifier();
            if (!verifier.verify(mURI.getHost(), s.getSession()))
                throw new SSLException("Hostname mismatch");
        }

        Crashlytics.log(Log.DEBUG, TAG, "Sending HTTP request");

        out.print("GET " + path + " HTTP/1.0\r\n");
        out.print("Host: " + mURI.getHost() + "\r\n");
        if (mURI.getHost().equals(NetworkConnection.IRCCLOUD_HOST)
                && NetworkConnection.getInstance().session != null
                && NetworkConnection.getInstance().session.length() > 0)
            out.print("Cookie: session=" + NetworkConnection.getInstance().session + "\r\n");
        out.print("Connection: close\r\n");
        out.print("Accept-Encoding: gzip\r\n");
        out.print("User-Agent: " + NetworkConnection.getInstance().useragent + "\r\n");
        out.print("\r\n");
        out.flush();

        HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(mSocket.getInputStream());

        // Read HTTP response status line.
        StatusLine statusLine = parseStatusLine(readLine(stream));
        if (statusLine != null)
            Crashlytics.log(Log.DEBUG, TAG, "Got HTTP response: " + statusLine);

        if (statusLine == null) {
            throw new HttpException("Received no reply from server.");
        } else if (statusLine.getStatusCode() != HttpStatus.SC_OK
                && statusLine.getStatusCode() != HttpStatus.SC_MOVED_PERMANENTLY) {
            Crashlytics.log(Log.ERROR, TAG, "Failure: " + mURI + ": " + statusLine.getStatusCode() + " "
                    + statusLine.getReasonPhrase());
            throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }

        // Read HTTP response headers.
        String line;

        boolean gzipped = false;
        while (!TextUtils.isEmpty(line = readLine(stream))) {
            Header header = parseHeader(line);
            if (header.getName().equalsIgnoreCase("content-encoding")
                    && header.getValue().equalsIgnoreCase("gzip"))
                gzipped = true;
            if (statusLine.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                    && header.getName().equalsIgnoreCase("location")) {
                Crashlytics.log(Log.INFO, TAG, "Redirecting to: " + header.getValue());
                mURI = new URL(header.getValue());
                mSocket.close();
                mSocket = null;
                mThread = null;
                connect();
                return;
            }
        }

        if (gzipped)
            onStreamConnected(new GZIPInputStream(mSocket.getInputStream()));
        else
            onStreamConnected(mSocket.getInputStream());

        onFetchComplete();
    } catch (Exception ex) {
        NetworkConnection.printStackTraceToCrashlytics(ex);
        onFetchFailed();
    }
}

From source file:com.joyent.manta.http.MantaSSLConnectionSocketFactory.java

@Override
protected void prepareSocket(final SSLSocket socket) throws IOException {
    final Set<String> enabledProtocols = new LinkedHashSet<>(Arrays.asList(socket.getEnabledProtocols()));
    final Set<String> enabledCipherSuites = new LinkedHashSet<>(Arrays.asList(socket.getEnabledCipherSuites()));

    if (LOG.isDebugEnabled()) {
        LOG.debug("Enabled TLS protocols: {}", MantaUtils.asString(enabledProtocols));
        LOG.debug("Enabled cipher suites: {}", MantaUtils.asString(enabledCipherSuites));
    }/*from   ww w  .j av  a 2 s  . co  m*/

    supportedCipherSuites.retainAll(enabledCipherSuites);

    if (!supportedCipherSuites.isEmpty()) {
        try {
            String[] supportedCiphers = new String[supportedCipherSuites.size()];
            supportedCipherSuites.toArray(supportedCiphers);
            socket.setEnabledCipherSuites(supportedCiphers);
        } catch (IllegalArgumentException e) {
            String msg = String.format("Unsupported encryption provider. Supported providers: %s",
                    MantaUtils.asString(socket.getEnabledCipherSuites()));
            throw new ConfigurationException(msg, e);
        }
    }

    supportedProtocols.retainAll(enabledProtocols);

    if (!supportedProtocols.isEmpty()) {
        String[] supportedProtos = new String[supportedProtocols.size()];
        supportedProtocols.toArray(supportedProtos);
        socket.setEnabledProtocols(supportedProtos);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Supported TLS protocols: {}", MantaUtils.asString(supportedProtocols));
        LOG.debug("Supported cipher suites: {}", MantaUtils.asString(supportedCipherSuites));
    }
}

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java

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

    SSLSocketFactory sslSocketFactory = insecure ? insecoreSSLSocketfactory : defaultSSLSocketFactory;

    final SSLSocket sslsock = (SSLSocket) sslSocketFactory.createSocket(socket, target, port, true);

    if (supportedProtocols != null) {
        sslsock.setEnabledProtocols(supportedProtocols);
    } else {//  w  ww.  jav  a2s  . c o m
        // 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 (this.log.isDebugEnabled()) {
        this.log.debug("Enabled protocols: " + Arrays.asList(sslsock.getEnabledProtocols()));
        this.log.debug("Enabled cipher suites:" + Arrays.asList(sslsock.getEnabledCipherSuites()));
    }

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