Example usage for javax.net.ssl SSLSocketFactory getSupportedCipherSuites

List of usage examples for javax.net.ssl SSLSocketFactory getSupportedCipherSuites

Introduction

In this page you can find the example usage for javax.net.ssl SSLSocketFactory getSupportedCipherSuites.

Prototype

public abstract String[] getSupportedCipherSuites();

Source Link

Document

Returns the names of the cipher suites which could be enabled for use on an SSL connection.

Usage

From source file:com.sat.vcse.automation.utils.http.HttpClient.java

/**
 * Get list of supported Cipher Suites/*from  w  w w .  j ava2  s .  co m*/
 * @return Supported Cipher Suites
 */
public static List<String> getSupportedCipherSuites() {
    final String METHOD_NAME = "getSupportedCipherSuites(): ";

    try {
        final SSLContext sslContext = SSLContext.getDefault();
        final SSLSocketFactory sslsf = sslContext.getSocketFactory();
        return Arrays.asList(sslsf.getSupportedCipherSuites());

    } catch (NoSuchAlgorithmException exp) {
        LogHandler.error(CLASS_NAME + METHOD_NAME + "Exception: " + exp.getMessage());
        throw new CoreRuntimeException(exp, CLASS_NAME + METHOD_NAME + exp.getMessage());
    }

}

From source file:com.github.kpavlov.ssl.DynamicSSLSocketFactory.java

public DynamicSSLSocketFactory(KeyStoreProvider keyStoreProvider, KeyPasswordProvider keyPasswordProvider) {
    Objects.requireNonNull(keyStoreProvider, "KeyStoreProvider is required");
    Objects.requireNonNull(keyPasswordProvider, "KeyPasswordProvider is required");
    this.keyPasswordProvider = keyPasswordProvider;
    this.keyStoreProvider = keyStoreProvider;

    SSLSocketFactory systemDefaultFactory = SSLContexts.createSystemDefault().getSocketFactory();
    defaultCipherSuites = systemDefaultFactory.getDefaultCipherSuites();
    supportedCipherSuites = systemDefaultFactory.getSupportedCipherSuites();
}

From source file:org.elasticsearch.xpack.core.ssl.SSLServiceTests.java

public void testThatSSLSocketFactoryHasProperCiphersAndProtocols() throws Exception {
    MockSecureSettings secureSettings = new MockSecureSettings();
    secureSettings.setString("xpack.ssl.keystore.secure_password", "testnode");
    Settings settings = Settings.builder().put("xpack.ssl.keystore.path", testnodeStore)
            .put("xpack.ssl.keystore.type", testnodeStoreType).setSecureSettings(secureSettings).build();
    SSLService sslService = new SSLService(settings, env);
    SSLSocketFactory factory = sslService.sslSocketFactory(Settings.EMPTY);
    SSLConfiguration config = sslService.sslConfiguration(Settings.EMPTY);
    final String[] ciphers = sslService.supportedCiphers(factory.getSupportedCipherSuites(),
            config.cipherSuites(), false);
    assertThat(factory.getDefaultCipherSuites(), is(ciphers));

    final String[] supportedProtocols = config.supportedProtocols().toArray(Strings.EMPTY_ARRAY);
    try (SSLSocket socket = (SSLSocket) factory.createSocket()) {
        assertThat(socket.getEnabledCipherSuites(), is(ciphers));
        // the order we set the protocols in is not going to be what is returned as internally the JDK may sort the versions
        assertThat(socket.getEnabledProtocols(), arrayContainingInAnyOrder(supportedProtocols));
        assertArrayEquals(ciphers, socket.getSSLParameters().getCipherSuites());
        assertThat(socket.getSSLParameters().getProtocols(), arrayContainingInAnyOrder(supportedProtocols));
        assertTrue(socket.getSSLParameters().getUseCipherSuitesOrder());
    }//from  ww  w .j a  v a 2  s  .c om
}

From source file:org.elasticsearch.xpack.core.ssl.SSLService.java

/**
 * Create a new {@link SSLSocketFactory} based on the provided settings. The settings are used to identify the ssl configuration that
 * should be used to create the socket factory. The socket factory will also properly configure the ciphers and protocols on each
 * socket that is created/* ww  w  .jav  a  2  s  .c  o  m*/
 * @param settings the settings used to identify the ssl configuration, typically under a *.ssl. prefix. An empty settings will return
 *                 a factory created from the default configuration
 * @return Never {@code null}.
 */
public SSLSocketFactory sslSocketFactory(Settings settings) {
    SSLConfiguration sslConfiguration = sslConfiguration(settings);
    SSLSocketFactory socketFactory = sslContext(sslConfiguration).getSocketFactory();
    return new SecuritySSLSocketFactory(socketFactory,
            sslConfiguration.supportedProtocols().toArray(Strings.EMPTY_ARRAY),
            supportedCiphers(socketFactory.getSupportedCipherSuites(), sslConfiguration.cipherSuites(), false));
}

From source file:com.ibm.og.client.ApacheClient.java

private ConnectionSocketFactory createSslConnectionSocketFactory() {
    final SSLSocketFactory sslSocketFactory = createSSLSocketFactory();
    String[] configuredProtocols = null;
    String[] configuredCipherSuites = null;
    if (this.protocols != null) {
        configuredProtocols = Iterables.toArray(this.protocols, String.class);
    }/*from  w  w w.j a v a  2 s .  c o m*/
    if (this.cipherSuites != null) {
        final List<String> supportedCipherSuites = ImmutableList
                .copyOf(sslSocketFactory.getSupportedCipherSuites());
        for (final String cipherSuite : this.cipherSuites) {
            checkArgument(supportedCipherSuites.contains(cipherSuite), "Unsupported cipher suite [%s]",
                    cipherSuite);
        }

        configuredCipherSuites = Iterables.toArray(this.cipherSuites, String.class);
    }
    final PublicSuffixMatcher suffixMatcher = PublicSuffixMatcherLoader.getDefault();
    final HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

    return new SSLConnectionSocketFactory(sslSocketFactory, configuredProtocols, configuredCipherSuites,
            hostnameVerifier);

}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Setup SSL connection.//  w  w  w.  j ava 2  s  .  c  o  m
 */
private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException {
    if (DEBUG) {
        Log.d(TAG, "Load custom SSL certificates");
    }

    final SSLContext sslContext;
    try {
        // Load SSL certificates:
        // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html
        // Earlier Android versions do not have updated root CA
        // certificates, resulting in connection errors.
        final KeyStore keyStore = loadCertificates(context);

        final CustomTrustManager customTrustManager = new CustomTrustManager(keyStore);
        final TrustManager[] tms = new TrustManager[] { customTrustManager };

        // Init SSL connection with custom certificates.
        // The same SecureRandom instance is used for every connection to
        // speed up initialization.
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tms, SECURE_RANDOM);
    } catch (GeneralSecurityException e) {
        final IOException ioe = new IOException("Failed to initialize SSL engine");
        ioe.initCause(e);
        throw ioe;
    }

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // Fix slow read:
        // http://code.google.com/p/android/issues/detail?id=13117
        // Prior to ICS, the host name is still resolved even if we already
        // know its IP address, for each connection.
        final SSLSocketFactory delegate = sslContext.getSocketFactory();
        final SSLSocketFactory socketFactory = new SSLSocketFactory() {
            @Override
            public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
                InetAddress addr = InetAddress.getByName(host);
                injectHostname(addr, host);
                return delegate.createSocket(addr, port);
            }

            @Override
            public Socket createSocket(InetAddress host, int port) throws IOException {
                return delegate.createSocket(host, port);
            }

            @Override
            public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
                    throws IOException, UnknownHostException {
                return delegate.createSocket(host, port, localHost, localPort);
            }

            @Override
            public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
                    throws IOException {
                return delegate.createSocket(address, port, localAddress, localPort);
            }

            private void injectHostname(InetAddress address, String host) {
                try {
                    Field field = InetAddress.class.getDeclaredField("hostName");
                    field.setAccessible(true);
                    field.set(address, host);
                } catch (Exception ignored) {
                }
            }

            @Override
            public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
                injectHostname(s.getInetAddress(), host);
                return delegate.createSocket(s, host, port, autoClose);
            }

            @Override
            public String[] getDefaultCipherSuites() {
                return delegate.getDefaultCipherSuites();
            }

            @Override
            public String[] getSupportedCipherSuites() {
                return delegate.getSupportedCipherSuites();
            }
        };
        conn.setSSLSocketFactory(socketFactory);
    } else {
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    }

    conn.setHostnameVerifier(new BrowserCompatHostnameVerifier());
}

From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java

/**
 * Setup SSL connection.//from w  w  w .ja v  a2s. c  om
 */
private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException {
    final SSLContext sslContext;
    try {
        // SSL certificates are provided by the Guardian Project:
        // https://github.com/guardianproject/cacert
        if (trustManagers == null) {
            // Load SSL certificates:
            // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html
            // Earlier Android versions do not have updated root CA
            // certificates, resulting in connection errors.
            final KeyStore keyStore = loadCertificates(context);

            final CustomTrustManager customTrustManager = new CustomTrustManager(keyStore);
            trustManagers = new TrustManager[] { customTrustManager };
        }

        // Init SSL connection with custom certificates.
        // The same SecureRandom instance is used for every connection to
        // speed up initialization.
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, SECURE_RANDOM);
    } catch (GeneralSecurityException e) {
        final IOException ioe = new IOException("Failed to initialize SSL engine");
        ioe.initCause(e);
        throw ioe;
    }

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // Fix slow read:
        // http://code.google.com/p/android/issues/detail?id=13117
        // Prior to ICS, the host name is still resolved even if we already
        // know its IP address, for each connection.
        final SSLSocketFactory delegate = sslContext.getSocketFactory();
        final SSLSocketFactory socketFactory = new SSLSocketFactory() {
            @Override
            public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
                InetAddress addr = InetAddress.getByName(host);
                injectHostname(addr, host);
                return delegate.createSocket(addr, port);
            }

            @Override
            public Socket createSocket(InetAddress host, int port) throws IOException {
                return delegate.createSocket(host, port);
            }

            @Override
            public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
                    throws IOException, UnknownHostException {
                return delegate.createSocket(host, port, localHost, localPort);
            }

            @Override
            public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
                    throws IOException {
                return delegate.createSocket(address, port, localAddress, localPort);
            }

            private void injectHostname(InetAddress address, String host) {
                try {
                    Field field = InetAddress.class.getDeclaredField("hostName");
                    field.setAccessible(true);
                    field.set(address, host);
                } catch (Exception ignored) {
                }
            }

            @Override
            public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
                injectHostname(s.getInetAddress(), host);
                return delegate.createSocket(s, host, port, autoClose);
            }

            @Override
            public String[] getDefaultCipherSuites() {
                return delegate.getDefaultCipherSuites();
            }

            @Override
            public String[] getSupportedCipherSuites() {
                return delegate.getSupportedCipherSuites();
            }
        };
        conn.setSSLSocketFactory(socketFactory);
    } else {
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    }

    conn.setHostnameVerifier(new BrowserCompatHostnameVerifier());
}

From source file:org.apache.jmeter.util.HttpSSLProtocolSocketFactory.java

@Override
public String[] getSupportedCipherSuites() {
    try {//from www .  j  a  v  a 2  s.  c om
        SSLSocketFactory sslfac = getSSLSocketFactory();
        return sslfac.getSupportedCipherSuites();
    } catch (IOException ex) {
        return new String[] {};
    }
}

From source file:org.ops4j.pax.web.service.jetty.internal.JettyFactoryImpl.java

/**
 * {@inheritDoc}/*from w  w  w  .j  a va2s .  c  o m*/
 */
@Override
public ServerConnector createSecureConnector(Server server, String name, int port, String sslKeystore,
        String sslKeystorePassword, String sslKeyPassword, String host, String sslKeystoreType,
        String sslKeyAlias, String trustStore, String trustStorePassword, String trustStoreType,
        boolean isClientAuthNeeded, boolean isClientAuthWanted, List<String> cipherSuitesIncluded,
        List<String> cipherSuitesExcluded, List<String> protocolsIncluded, List<String> protocolsExcluded,
        Boolean sslRenegotiationAllowed, String crlPath, Boolean enableCRLDP, Boolean validateCerts,
        Boolean validatePeerCerts, Boolean enableOCSP, String ocspResponderURL) {

    // SSL Context Factory for HTTPS and SPDY
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(sslKeystore);
    sslContextFactory.setKeyStorePassword(sslKeystorePassword);
    sslContextFactory.setKeyManagerPassword(sslKeyPassword);
    sslContextFactory.setNeedClientAuth(isClientAuthNeeded);
    sslContextFactory.setWantClientAuth(isClientAuthWanted);
    sslContextFactory.setEnableCRLDP(enableCRLDP);
    sslContextFactory.setValidateCerts(validateCerts);
    sslContextFactory.setValidatePeerCerts(validatePeerCerts);
    sslContextFactory.setEnableOCSP(enableOCSP);
    if ((null != crlPath) && (!"".equals(crlPath))) {
        sslContextFactory.setCrlPath(crlPath);
    }
    if ((null != ocspResponderURL) && (!"".equals(ocspResponderURL))) {
        sslContextFactory.setOcspResponderURL(ocspResponderURL);
    }
    if (sslKeystoreType != null) {
        sslContextFactory.setKeyStoreType(sslKeystoreType);
    }
    // Java key stores may contain more than one private key entry.
    // Specifying the alias tells jetty which one to use.
    if ((null != sslKeyAlias) && (!"".equals(sslKeyAlias))) {
        sslContextFactory.setCertAlias(sslKeyAlias);
    }

    // Quite often it is useful to use a certificate trust store other than the JVM default.
    if ((null != trustStore) && (!"".equals(trustStore))) {
        sslContextFactory.setTrustStorePath(trustStore);
    }
    if ((null != trustStorePassword) && (!"".equals(trustStorePassword))) {
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    if ((null != trustStoreType) && (!"".equals(trustStoreType))) {
        sslContextFactory.setTrustStoreType(trustStoreType);
    }

    // In light of well-known attacks against weak encryption algorithms such as RC4,
    // it is usefull to be able to include or exclude certain ciphersuites.
    // Due to the overwhelming number of cipher suites using regex to specify inclusions
    // and exclusions greatly simplifies configuration.
    final String[] cipherSuites;
    try {
        SSLContext context = SSLContext.getDefault();
        SSLSocketFactory sf = context.getSocketFactory();
        cipherSuites = sf.getSupportedCipherSuites();
    } catch (NoSuchAlgorithmException e) {

        throw new RuntimeException("Failed to get supported cipher suites.", e);
    }

    if (cipherSuitesIncluded != null && !cipherSuitesIncluded.isEmpty()) {
        final List<String> cipherSuitesToInclude = new ArrayList<>();
        for (final String cipherSuite : cipherSuites) {
            for (final String includeRegex : cipherSuitesIncluded) {
                if (cipherSuite.matches(includeRegex)) {
                    cipherSuitesToInclude.add(cipherSuite);
                }
            }
        }
        sslContextFactory.setIncludeCipherSuites(
                cipherSuitesToInclude.toArray(new String[cipherSuitesToInclude.size()]));
    }

    if (cipherSuitesExcluded != null && !cipherSuitesExcluded.isEmpty()) {
        final List<String> cipherSuitesToExclude = new ArrayList<>();
        for (final String cipherSuite : cipherSuites) {
            for (final String excludeRegex : cipherSuitesExcluded) {
                if (cipherSuite.matches(excludeRegex)) {
                    cipherSuitesToExclude.add(cipherSuite);
                }
            }
        }
        sslContextFactory.setExcludeCipherSuites(
                cipherSuitesToExclude.toArray(new String[cipherSuitesToExclude.size()]));
    }

    // In light of attacks against SSL 3.0 as "POODLE" it is useful to include or exclude
    // SSL/TLS protocols as needed.
    if ((null != protocolsIncluded) && (!protocolsIncluded.isEmpty())) {
        sslContextFactory.setIncludeProtocols(protocolsIncluded.toArray(new String[protocolsIncluded.size()]));
    }
    if ((null != protocolsExcluded) && (!protocolsExcluded.isEmpty())) {
        sslContextFactory.setExcludeProtocols(protocolsExcluded.toArray(new String[protocolsExcluded.size()]));
    }
    if (sslRenegotiationAllowed != null) {
        sslContextFactory.setRenegotiationAllowed(sslRenegotiationAllowed);
    }

    // HTTP Configuration
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setSecureScheme(HttpScheme.HTTPS.asString());
    httpConfig.setSecurePort(port);
    httpConfig.setOutputBufferSize(32768);

    // HTTPS Configuration
    HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    List<AbstractConnectionFactory> connectionFactories = new ArrayList<>();

    HttpConnectionFactory httpConFactory = new HttpConnectionFactory(httpsConfig);

    SslConnectionFactory sslFactory = null;
    AbstractConnectionFactory http2Factory = null;

    NegotiatingServerConnectionFactory alpnFactory = null;

    if (alpnCLassesAvailable()) {
        log.info("HTTP/2 available, creating HttpSpdyServerConnector for Https");
        // SPDY connector
        try {
            Class<?> comparatorClass = bundle.loadClass("org.eclipse.jetty.http2.HTTP2Cipher");

            Comparator<String> cipherComparator = (Comparator<String>) FieldUtils
                    .readDeclaredStaticField(comparatorClass, "COMPARATOR");
            sslContextFactory.setCipherComparator(cipherComparator);

            sslFactory = new SslConnectionFactory(sslContextFactory, "h2");
            connectionFactories.add(sslFactory);

            //org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory
            Class<?> loadClass = bundle
                    .loadClass("org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory");
            //            
            //            //ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory("spdy/3", "http/1.1");
            //            alpnFactory = (NegotiatingServerConnectionFactory) ConstructorUtils.invokeConstructor(loadClass, (Object) new String[] {"ssl", "http/2", "http/1.1"});
            //            alpnFactory.setDefaultProtocol("http/1.1");
            //            connectionFactories.add(alpnFactory);

            //HTTPSPDYServerConnectionFactory spdy = new HTTPSPDYServerConnectionFactory(SPDY.V3, httpConfig);
            //            loadClass = bundle.loadClass("org.eclipse.jetty.spdy.server.http.HTTPSPDYServerConnectionFactory");
            //            loadClass = bundle.loadClass("org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory");

            http2Factory = (AbstractConnectionFactory) ConstructorUtils.invokeConstructor(loadClass,
                    httpsConfig);
            connectionFactories.add(http2Factory);

        } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException
                | IllegalArgumentException | IllegalAccessException | InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        log.info("SPDY not available, creating standard ServerConnector for Https");
        sslFactory = new SslConnectionFactory(sslContextFactory, "http/1.1");
    }

    //      HttpConnectionFactory httpFactory = new HttpConnectionFactory(httpConfig);
    //      
    //      ServerConnector https = new ServerConnector(server); 

    // HTTPS connector
    ServerConnector https = new ServerConnector(server, sslFactory, httpConFactory);
    for (AbstractConnectionFactory factory : connectionFactories) {
        https.addConnectionFactory(factory);
    }

    https.setPort(port);
    https.setName(name);
    https.setHost(host);
    https.setIdleTimeout(500000);

    /*
             
    SslContextFactory sslContextFactory = new SslContextFactory();
    HttpConfiguration httpConfig = new HttpConfiguration();
            
    SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, "alpn");
    ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory("spdy/3", "http/1.1");
    alpn.setDefaultProtocol("http/1.1");
    HTTPSPDYServerConnectionFactory spdy = new HTTPSPDYServerConnectionFactory(SPDY.V3, httpConfig);
    HttpConnectionFactory http = new HttpConnectionFactory(httpConfig);
            
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server, new ConnectionFactory[]{ssl, alpn, spdy, http});
             
     */

    return https;

}