Example usage for javax.net.ssl SSLContext createSSLEngine

List of usage examples for javax.net.ssl SSLContext createSSLEngine

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext createSSLEngine.

Prototype

public final SSLEngine createSSLEngine() 

Source Link

Document

Creates a new SSLEngine using this context.

Usage

From source file:com.intel.cosbench.client.http.HttpClientUtil.java

@SuppressWarnings({ "deprecation" })
private static SSLSocketFactory createSSLSocketFactory() {
    try {//  ww  w .j av a2 s.c o m
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new X509TrustManager[] { tm }, null);
        String[] enabled = { "SSL_RSA_WITH_NULL_MD5", "SSL_RSA_WITH_NULL_SHA" };
        ctx.createSSLEngine().setEnabledCipherSuites(enabled);

        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        return ssf;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService.java

/**
 * OVSDB Passive listening thread that uses Netty ServerBootstrap to open
 * passive connection with Ssl and handle channel callbacks.
 *//*  ww  w  .  j a  v  a2 s  .  c  om*/
private static void ovsdbManagerWithSsl(int port, final SSLContext sslContext) {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel channel) throws Exception {
                        logger.debug("New Passive channel created : {}", channel);
                        if (sslContext != null) {
                            /* Add SSL handler first if SSL context is provided */
                            SSLEngine engine = sslContext.createSSLEngine();
                            engine.setUseClientMode(false); // work in a server mode
                            engine.setNeedClientAuth(true); // need client authentication
                            channel.pipeline().addLast("ssl", new SslHandler(engine));
                        }

                        channel.pipeline().addLast(new JsonRpcDecoder(100000),
                                new StringEncoder(CharsetUtil.UTF_8), new ExceptionHandler());

                        handleNewPassiveConnection(channel);
                    }
                });
        serverBootstrap.option(ChannelOption.TCP_NODELAY, true);
        serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
        // Start the server.
        ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
        Channel serverListenChannel = channelFuture.channel();
        // Wait until the server socket is closed.
        serverListenChannel.closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error("Thread interrupted", e);
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.floragunn.searchguard.ssl.SSLTest.java

@Test
public void testAvailCiphers() throws Exception {
    final SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(null, null, null);
    final SSLEngine engine = serverContext.createSSLEngine();
    final List<String> jdkSupportedCiphers = new ArrayList<>(Arrays.asList(engine.getSupportedCipherSuites()));
    jdkSupportedCiphers.retainAll(SSLConfigConstants.getSecureSSLCiphers(Settings.EMPTY, false));
    engine.setEnabledCipherSuites(jdkSupportedCiphers.toArray(new String[0]));

    final List<String> jdkEnabledCiphers = Arrays.asList(engine.getEnabledCipherSuites());
    // example/*  ww  w .j  ava 2s  . c o  m*/
    // TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
    // TLS_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA
    System.out.println("JDK enabled ciphers: " + jdkEnabledCiphers);
    Assert.assertTrue(jdkEnabledCiphers.size() > 0);
}

From source file:mitm.BouncyCastleSslEngineSource.java

/**
 * Generates an 1024 bit RSA key pair using SHA1PRNG. Thoughts: 2048 takes
 * much longer time on older CPUs. And for almost every client, 1024 is
 * sufficient./*from   ww  w . j a  va  2  s  .  com*/
 *
 * Derived from Zed Attack Proxy (ZAP). ZAP is an HTTP/HTTPS proxy for
 * assessing web application security. Copyright 2011 mawoki@ymail.com
 * Licensed under the Apache License, Version 2.0
 *
 * @param commonName
 *            the common name to use in the server certificate
 *
 * @param subjectAlternativeNames
 *            a List of the subject alternative names to use in the server
 *            certificate, could be empty, but must not be null
 *
 */
public SSLEngine createCertForHost(final String commonName,
        final SubjectAlternativeNameHolder subjectAlternativeNames)
        throws GeneralSecurityException, OperatorCreationException, IOException, ExecutionException {
    if (commonName == null) {
        throw new IllegalArgumentException("Error, 'commonName' is not allowed to be null!");
    }
    if (subjectAlternativeNames == null) {
        throw new IllegalArgumentException("Error, 'subjectAlternativeNames' is not allowed to be null!");
    }

    SSLContext ctx;
    if (serverSSLContexts == null) {
        ctx = createServerContext(commonName, subjectAlternativeNames);
    } else {
        ctx = serverSSLContexts.get(commonName, new Callable<SSLContext>() {
            @Override
            public SSLContext call() throws Exception {
                return createServerContext(commonName, subjectAlternativeNames);
            }
        });
    }
    return ctx.createSSLEngine();
}

From source file:com.bt.pi.api.http.SimpleHttpsServerFactoryBean.java

protected HttpServer getInitializedServer(InetSocketAddress address) throws IOException {
    HttpsServer server = HttpsServer.create(address, getBacklog());
    try {/*from  www .  j  a v a2s  .c om*/
        SSLContext sslContext = SSLContext.getInstance(sslContextProtocol);

        KeyStore ks = KeyStore.getInstance(keyStoreType);
        InputStream is = keyStoreLocation.getInputStream();
        try {
            ks.load(is, password);
        } catch (EOFException e) {
            LOG.warn(String.format(
                    "Unable to load certificate store %s. This may be possible because https isn't enabled with a valid certificate",
                    keyStoreLocation));
            return null;
        }

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
        kmf.init(ks, password);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
        tmf.init(ks);

        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        final SSLEngine m_engine = sslContext.createSSLEngine();

        server.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
            public void configure(HttpsParameters params) {
                params.setSSLParameters(getSSLContext().getDefaultSSLParameters());
                params.setNeedClientAuth(false);
                params.setWantClientAuth(false);
                params.setCipherSuites(m_engine.getEnabledCipherSuites());
                params.setProtocols(m_engine.getEnabledProtocols());
            }
        });
    } catch (Throwable e) {
        throw new IOException("initializing HttpsServer failed due to exception", e);
    }
    return server;
}

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

/**
 * Initialize HttpsClient. //from   w w  w. j  av a 2s. c o  m
 * 
 * @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:org.opcfoundation.ua.transport.https.HttpsServer.java

protected void initReactor() throws ServiceResultException {
    boolean https = false, http = false;
    for (SocketHandle sh : socketHandles.values()) {
        https |= sh.scheme.equals(UriUtil.SCHEME_HTTPS);
        http |= sh.scheme.equals(UriUtil.SCHEME_HTTP);
    }/*  w  w w.j a v  a 2 s  .  c  om*/

    try {
        if (https && sslSetupHandler == null) {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(application.getHttpsSettings().getKeyManagers(),
                    application.getHttpsSettings().getTrustManagers(), null);

            // SSL Setup Handler
            sslSetupHandler = new SSLSetupHandler() {
                public void verify(IOSession iosession, SSLSession sslsession) throws SSLException {
                }

                public void initalize(SSLEngine sslengine) throws SSLException {
                    //sslengine.setEnabledCipherSuites( calcCipherSuites() );
                }
            };

            // Create HTTP connection factory
            sslConnFactory = new SSLNHttpServerConnectionFactory(sslcontext, sslSetupHandler, getHttpParams());

            // Create server-side I/O event dispatch
            sslIoEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, sslConnFactory);

            // Create ssl engine
            sslEngine = sslcontext.createSSLEngine();
            log.info("Enabled protocols in SSL Engine are {}",
                    Arrays.toString(sslEngine.getEnabledProtocols()));
            enabledCipherSuites = sslEngine.getEnabledCipherSuites();
            log.info("Enabled CipherSuites in SSL Engine are {}", Arrays.toString(enabledCipherSuites));
        }

        if (https) {
            // Create list of cipher suites
            String[] oldCipherSuiteSelection = cipherSuites;
            cipherSuitePatterns = calcCipherSuitePatterns();
            //securityPolicies = calcSecurityPolicies().toArray( new SecurityPolicy[0] );
            cipherSuites = CryptoUtil.filterCipherSuiteList(enabledCipherSuites, cipherSuitePatterns);
            sslEngine.setEnabledCipherSuites(cipherSuites);

            if (oldCipherSuiteSelection == null || !Arrays.equals(oldCipherSuiteSelection, cipherSuites)) {
                log.info("CipherSuites for policies ({}) are {}", Arrays.toString(securityPolicies),
                        Arrays.toString(cipherSuites));
            }
        }

        if (http && plainConnFactory == null) {
            plainConnFactory = new DefaultNHttpServerConnectionFactory(getHttpParams());

            // Create server-side I/O event dispatch
            plainIoEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, plainConnFactory);
        }

        if (ioReactor == null) {
            // Create server-side I/O reactor
            ioReactor = new DefaultListeningIOReactor(ioConfig, null);
        }
    } catch (KeyManagementException e1) {
        throw new ServiceResultException(e1);
    } catch (NoSuchAlgorithmException e1) {
        throw new ServiceResultException(e1);
    } catch (IOReactorException e1) {
        throw new ServiceResultException(e1);
    }
}

From source file:org.parosproxy.paros.network.SSLConnector.java

private static synchronized void readSupportedProtocols(SSLSocket sslSocket) {
    if (supportedProtocols == null) {
        logger.info("Reading supported SSL/TLS protocols...");
        String[] tempSupportedProtocols;
        if (sslSocket != null) {
            logger.info("Using an existing SSLSocket...");
            tempSupportedProtocols = sslSocket.getSupportedProtocols();
        } else {//from   w  w w  .ja v a2s .  co m
            logger.info("Using a SSLEngine...");
            try {
                SSLContext ctx = SSLContext.getInstance(SSL);
                ctx.init(null, null, null);
                try {
                    tempSupportedProtocols = ctx.createSSLEngine().getSupportedProtocols();
                } catch (UnsupportedOperationException e) {
                    logger.warn("Failed to use SSLEngine. Trying with unconnected socket...", e);
                    try (SSLSocket socket = (SSLSocket) ctx.getSocketFactory().createSocket()) {
                        tempSupportedProtocols = socket.getSupportedProtocols();
                    }
                }
            } catch (NoSuchAlgorithmException | KeyManagementException | IOException e) {
                logger.error(
                        "Failed to read the SSL/TLS supported protocols." + " Using default protocol versions: "
                                + Arrays.toString(FAIL_SAFE_DEFAULT_ENABLED_PROTOCOLS),
                        e);
                tempSupportedProtocols = FAIL_SAFE_DEFAULT_ENABLED_PROTOCOLS;
            }
        }
        Arrays.sort(tempSupportedProtocols);
        supportedProtocols = tempSupportedProtocols;
        logger.info("Done reading supported SSL/TLS protocols: " + Arrays.toString(supportedProtocols));
    }
}