Example usage for io.netty.handler.ssl SslProvider JDK

List of usage examples for io.netty.handler.ssl SslProvider JDK

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslProvider JDK.

Prototype

SslProvider JDK

To view the source code for io.netty.handler.ssl SslProvider JDK.

Click Source Link

Document

JDK's default implementation.

Usage

From source file:io.gatling.http.client.impl.DefaultHttpClient.java

License:Apache License

public DefaultHttpClient(HttpClientConfig config) {
    this.config = config;
    try {/*from   w w  w .j a  va  2  s  .  co  m*/
        SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

        if (config.getSslSessionCacheSize() > 0) {
            sslContextBuilder.sessionCacheSize(config.getSslSessionCacheSize());
        }

        if (config.getSslSessionTimeout() > 0) {
            sslContextBuilder.sessionTimeout(config.getSslSessionTimeout());
        }

        if (isNonEmpty(config.getEnabledSslProtocols())) {
            sslContextBuilder.protocols(config.getEnabledSslProtocols());
        }

        if (isNonEmpty(config.getEnabledSslCipherSuites())) {
            sslContextBuilder.ciphers(Arrays.asList(config.getEnabledSslCipherSuites()));
        } else if (!config.isFilterInsecureCipherSuites()) {
            sslContextBuilder.ciphers(null, IdentityCipherSuiteFilter.INSTANCE_DEFAULTING_TO_SUPPORTED_CIPHERS);
        }

        sslContextBuilder.sslProvider(config.isUseOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK)
                .keyManager(config.getKeyManagerFactory()).trustManager(config.getTrustManagerFactory());

        this.sslContext = sslContextBuilder.build();

        this.alpnSslContext = sslContextBuilder.applicationProtocolConfig(
                new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                        ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))
                .build();

    } catch (SSLException e) {
        throw new IllegalArgumentException("Impossible to create SslContext", e);
    }

    DefaultThreadFactory threadFactory = new DefaultThreadFactory(config.getThreadPoolName());
    eventLoopGroup = config.isUseNativeTransport() ? new EpollEventLoopGroup(0, threadFactory)
            : new NioEventLoopGroup(0, threadFactory);
    eventLoopPicker = new AffinityEventLoopPicker(eventLoopGroup);
    channelGroup = new DefaultChannelGroup(eventLoopGroup.next());
}

From source file:io.grpc.netty.GrpcSslContexts.java

License:Apache License

/**
 * Set ciphers and APN appropriate for gRPC. Precisely what is set is permitted to change, so if
 * an application requires particular settings it should override the options set here.
 *//*  www  .j  a va 2  s . co  m*/
@CanIgnoreReturnValue
public static SslContextBuilder configure(SslContextBuilder builder, Provider jdkProvider) {
    ApplicationProtocolConfig apc;
    if (SUN_PROVIDER_NAME.equals(jdkProvider.getName())) {
        // Jetty ALPN/NPN only supports one of NPN or ALPN
        if (JettyTlsUtil.isJettyAlpnConfigured()) {
            apc = ALPN;
        } else if (JettyTlsUtil.isJettyNpnConfigured()) {
            apc = NPN;
        } else if (JettyTlsUtil.isJava9AlpnAvailable()) {
            apc = ALPN;
        } else {
            throw new IllegalArgumentException(SUN_PROVIDER_NAME + " selected, but Jetty NPN/ALPN unavailable");
        }
    } else if (isConscrypt(jdkProvider)) {
        apc = ALPN;
    } else {
        throw new IllegalArgumentException("Unknown provider; can't configure: " + jdkProvider);
    }
    return builder.sslProvider(SslProvider.JDK)
            .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            .applicationProtocolConfig(apc).sslContextProvider(jdkProvider);
}

From source file:io.grpc.netty.GrpcSslContexts.java

License:Apache License

/**
 * Returns OpenSSL if available, otherwise returns the JDK provider.
 *//*from w ww  .  j  a va  2 s  .c  o  m*/
private static SslProvider defaultSslProvider() {
    if (OpenSsl.isAvailable()) {
        logger.log(Level.FINE, "Selecting OPENSSL");
        return SslProvider.OPENSSL;
    }
    Provider provider = findJdkProvider();
    if (provider != null) {
        logger.log(Level.FINE, "Selecting JDK with provider {0}", provider);
        return SslProvider.JDK;
    }
    logger.log(Level.INFO, "netty-tcnative unavailable (this may be normal)", OpenSsl.unavailabilityCause());
    logger.log(Level.INFO, "Conscrypt not found (this may be normal)");
    logger.log(Level.INFO, "Jetty ALPN unavailable (this may be normal)",
            JettyTlsUtil.getJettyAlpnUnavailabilityCause());
    throw new IllegalStateException("Could not find TLS ALPN provider; "
            + "no working netty-tcnative, Conscrypt, or Jetty NPN/ALPN available");
}

From source file:io.grpc.netty.TlsTest.java

License:Apache License

@Before
public void setUp() throws NoSuchAlgorithmException {
    executor = Executors.newSingleThreadScheduledExecutor();
    switch (tlsImpl) {
    case TCNATIVE:
        Assume.assumeTrue(OpenSsl.isAvailable());
        sslProvider = SslProvider.OPENSSL;
        break;/*from  w w  w . j  a  v a 2 s . c  om*/
    case JDK:
        Assume.assumeTrue(Arrays.asList(SSLContext.getDefault().getSupportedSSLParameters().getCipherSuites())
                .contains("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"));
        sslProvider = SslProvider.JDK;
        jdkProvider = Security.getProvider("SunJSSE");
        Assume.assumeNotNull(jdkProvider);
        try {
            // Check for presence of an (ironic) class added in Java 9
            Class.forName("java.lang.Runtime$Version");
            // Java 9+
        } catch (ClassNotFoundException ignored) {
            // Before Java 9
            try {
                GrpcSslContexts.configure(SslContextBuilder.forClient(), jdkProvider);
            } catch (IllegalArgumentException ex) {
                Assume.assumeNoException("Not Java 9+ and Jetty ALPN does not seem available", ex);
            }
        }
        break;
    case CONSCRYPT:
        sslProvider = SslProvider.JDK;
        jdkProvider = Security.getProvider("Conscrypt");
        Assume.assumeNotNull(jdkProvider);
        break;
    default:
        throw new AssertionError();
    }
    clientContextBuilder = SslContextBuilder.forClient();
    if (sslProvider == SslProvider.JDK) {
        GrpcSslContexts.configure(clientContextBuilder, jdkProvider);
    } else {
        GrpcSslContexts.configure(clientContextBuilder, sslProvider);
    }
}

From source file:io.grpc.netty.TlsTest.java

License:Apache License

private ServerBuilder<?> serverBuilder(int port, File serverCertChainFile, File serverPrivateKeyFile,
        X509Certificate[] serverTrustedCaCerts) throws IOException {
    SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(serverCertChainFile,
            serverPrivateKeyFile);/*  ww  w . ja v  a 2 s  .  c  o  m*/
    if (sslProvider == SslProvider.JDK) {
        GrpcSslContexts.configure(sslContextBuilder, jdkProvider);
    } else {
        GrpcSslContexts.configure(sslContextBuilder, sslProvider);
    }
    sslContextBuilder.trustManager(serverTrustedCaCerts).clientAuth(ClientAuth.REQUIRE);

    return NettyServerBuilder.forPort(port).sslContext(sslContextBuilder.build());
}

From source file:io.hekate.network.internal.NettySslUtils.java

License:Apache License

private static SslProvider provider(NetworkSslConfig cfg) {
    switch (cfg.getProvider()) {
    case AUTO: {//from w ww .jav a2 s  .co m
        return OpenSsl.isAvailable() ? SslProvider.OPENSSL : SslProvider.JDK;
    }
    case JDK: {
        return SslProvider.JDK;
    }
    case OPEN_SSL: {
        return SslProvider.OPENSSL;
    }
    default: {
        throw new IllegalArgumentException("Unexpected SSL provider: " + cfg.getProvider());
    }
    }
}

From source file:io.netty.example.http2.helloworld.client.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from   ww  w. j  av  a2  s  .  c  om
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);

    try {
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');

        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");
        if (URL != null) {
            // Create a simple GET request.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL, Unpooled.EMPTY_BUFFER);
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.write(request), channel.newPromise());
            streamId += 2;
        }
        if (URL2 != null) {
            // Create a simple POST request with a body.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
                    wrappedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.write(request), channel.newPromise());
        }
        channel.flush();
        responseHandler.awaitResponses(5, TimeUnit.SECONDS);
        System.out.println("Finished HTTP/2 request(s)");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:io.opendevice.sonoff.SonOffServerConnection.java

License:Open Source License

private SslContext generateSSLContext() {

    //        File certFile = config.getFile("sonoff.ssl.certificateFile");
    //        if(cert == null) throw new IllegalArgumentException("Certificate not found (check sonoff.ssl.certificateFile) !");
    //        File key = config.getFile("sonoff.ssl.certificateKey");
    //        if(key == null) throw new IllegalArgumentException("Certificate key must be provided (check sonoff.ssl.certificateKey) !");

    OpenDeviceConfig config = ODev.getConfig();

    InputStream cert = null;/*  ww  w.  j a  v a  2  s . c om*/
    InputStream key = null;

    try {
        File certFile = config.getFile("sonoff.ssl.certificateFile");
        if (certFile != null) {
            cert = new FileInputStream(certFile);
        } else {
            log.info("Using self-signed embedded certificate ...");
            cert = getClass().getClassLoader().getResourceAsStream("ssl/cert.pem");
        }

        File keyFile = config.getFile("sonoff.ssl.certificateKey");
        if (keyFile != null) {
            key = new FileInputStream(keyFile);
        } else {
            key = getClass().getClassLoader().getResourceAsStream("ssl/key.pem");
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    try {
        SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(cert, key);
        sslContextBuilder.sslProvider(SslProvider.JDK);
        SslContext sslContext = sslContextBuilder.build();
        return sslContext;
    } catch (SSLException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:io.spikex.core.util.connection.KeyStoreHelper.java

License:Apache License

public SslContext buildJdkClientContext(final boolean clientAuth) throws KeyStoreException {

    SslContext ctx = null;/*from  ww w  . j  a v  a 2s  .c  o  m*/

    try {
        TrustManagerFactory trustMgrFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        {
            String password = geTrustStorePassword();
            KeyStore trustStore = loadKeyStore(getTrustStorePath(), password);
            trustMgrFactory.init(trustStore);
        }

        if (clientAuth) {

            KeyManagerFactory keyMgrFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            String password = geKeyStorePassword();
            KeyStore keyStore = loadKeyStore(getKeyStorePath(), password);
            keyMgrFactory.init(keyStore, password != null ? password.toCharArray() : null);

            ctx = SslContextBuilder.forClient().sslProvider(SslProvider.JDK).trustManager(trustMgrFactory)
                    .keyManager(keyMgrFactory).build();
        } else {
            ctx = SslContextBuilder.forClient().sslProvider(SslProvider.JDK).trustManager(trustMgrFactory)
                    .build();
        }
    } catch (IOException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
        throw new KeyStoreException("Failed to build SSL context", e);
    }

    return ctx;
}

From source file:io.vertx.core.net.impl.SSLHelper.java

License:Open Source License

private SslContext createContext(VertxInternal vertx) {
    try {/*from   w  w  w. j  a  v  a 2  s  . c om*/
        KeyManagerFactory keyMgrFactory = getKeyMgrFactory(vertx);
        TrustManagerFactory trustMgrFactory = getTrustMgrFactory(vertx);
        SslContextBuilder builder;
        if (client) {
            builder = SslContextBuilder.forClient();
            if (keyMgrFactory != null) {
                builder.keyManager(keyMgrFactory);
            }
        } else {
            if (keyMgrFactory == null) {
                throw new VertxException("Key/certificate is mandatory for SSL");
            }
            builder = SslContextBuilder.forServer(keyMgrFactory);
        }
        Collection<String> cipherSuites = enabledCipherSuites;
        if (openSsl) {
            builder.sslProvider(SslProvider.OPENSSL);
            if (cipherSuites == null || cipherSuites.isEmpty()) {
                cipherSuites = OpenSsl.availableOpenSslCipherSuites();
            }
        } else {
            builder.sslProvider(SslProvider.JDK);
            if (cipherSuites == null || cipherSuites.isEmpty()) {
                cipherSuites = DEFAULT_JDK_CIPHER_SUITE;
            }
        }
        if (trustMgrFactory != null) {
            builder.trustManager(trustMgrFactory);
        }
        if (cipherSuites != null && cipherSuites.size() > 0) {
            builder.ciphers(cipherSuites);
        }
        if (useAlpn && applicationProtocols != null && applicationProtocols.size() > 0) {
            builder.applicationProtocolConfig(new ApplicationProtocolConfig(
                    ApplicationProtocolConfig.Protocol.ALPN,
                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, applicationProtocols
                            .stream().map(PROTOCOL_NAME_MAPPING::get).collect(Collectors.toList())));
        }
        return builder.build();
    } catch (Exception e) {
        throw new VertxException(e);
    }
}