Java 类io.netty.handler.ssl.SslContextBuilder 实例源码

项目:incubator-pulsar    文件:ServiceChannelInitializer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    if (enableTLS) {
        File tlsCert = new File(serviceConfig.getTlsCertificateFilePath());
        File tlsKey = new File(serviceConfig.getTlsKeyFilePath());
        SslContextBuilder builder = SslContextBuilder.forServer(tlsCert, tlsKey);
        if (serviceConfig.isTlsAllowInsecureConnection()) {
            builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
        } else {
            if (serviceConfig.getTlsTrustCertsFilePath().isEmpty()) {
                // Use system default
                builder.trustManager((File) null);
            } else {
                File trustCertCollection = new File(serviceConfig.getTlsTrustCertsFilePath());
                builder.trustManager(trustCertCollection);
            }
        }
        SslContext sslCtx = builder.clientAuth(ClientAuth.OPTIONAL).build();
        ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc()));
    }
    ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(PulsarDecoder.MaxFrameSize, 0, 4, 0, 4));
    ch.pipeline().addLast("handler", new ServerConnection(discoveryService));
}
项目:monica    文件:SocketClient.java   
public void start(String ip, int port) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new FileClientInitializer(sslCtx));
        Channel ch = b.connect(ip, port).sync().channel();
        ConfigurationContext.propMap.putIfAbsent(SOCKET_CHANNEL, ch);           
    }catch(Exception e){
        e.printStackTrace();
    }
}
项目:Ashbringer-load    文件:NettyShooter.java   
public void shoot(ShootComplete shootComplete) {

        Bootstrap b = new Bootstrap();

        SslContext sslContext = null;
        if (ssl) {
            try {
                sslContext = SslContextBuilder.forClient()
                        .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
            } catch (SSLException e) {
                e.printStackTrace();
            }
        }

        b.group(group)
                .channel(NioSocketChannel.class)
                .handler(new HttpClientInitializer(sslContext));

        // Make the connection attempt.
        b.connect(host, port).addListener(
                (ChannelFutureListener) channelFuture -> {
                    sendHttpRequest(channelFuture, shootComplete);
                });
    }
项目:conscrypt    文件:OpenJdkEngineFactory.java   
private static SslContext newNettyClientContext(
        io.netty.handler.ssl.SslProvider sslProvider, boolean useAlpn) {
    try {
        TestKeyStore server = TestKeyStore.getServer();
        SslContextBuilder ctx =
                SslContextBuilder.forClient()
                        .sslProvider(sslProvider)
                        .trustManager((X509Certificate[]) server.getPrivateKey("RSA", "RSA")
                                              .getCertificateChain());
        if (useAlpn) {
            ctx.applicationProtocolConfig(OpenJdkEngineFactoryConfig.NETTY_ALPN_CONFIG);
        }
        return ctx.build();
    } catch (SSLException e) {
        throw new RuntimeException(e);
    }
}
项目:conscrypt    文件:OpenJdkEngineFactory.java   
private static SslContext newNettyServerContext(
        io.netty.handler.ssl.SslProvider sslProvider, boolean useAlpn) {
    try {
        PrivateKeyEntry server = TestKeyStore.getServer().getPrivateKey("RSA", "RSA");
        SslContextBuilder ctx =
                SslContextBuilder
                        .forServer(server.getPrivateKey(),
                                (X509Certificate[]) server.getCertificateChain())
                        .sslProvider(sslProvider);
        if (useAlpn) {
            ctx.applicationProtocolConfig(OpenJdkEngineFactoryConfig.NETTY_ALPN_CONFIG);
        }
        return ctx.build();
    } catch (SSLException e) {
        throw new RuntimeException(e);
    }
}
项目:spring-vault    文件:ClientHttpConnectorFactory.java   
private static void configureSsl(SslConfiguration sslConfiguration,
        SslContextBuilder sslContextBuilder) {

    try {

        if (sslConfiguration.getTrustStoreConfiguration().isPresent()) {
            sslContextBuilder.trustManager(createTrustManagerFactory(sslConfiguration
                    .getTrustStoreConfiguration()));
        }

        if (sslConfiguration.getKeyStoreConfiguration().isPresent()) {
            sslContextBuilder.keyManager(createKeyManagerFactory(sslConfiguration
                    .getKeyStoreConfiguration()));
        }
    }
    catch (GeneralSecurityException | IOException e) {
        throw new IllegalStateException(e);
    }
}
项目:opentsdb-plugins    文件:RelayClient.java   
private static SslContext getSSLContext() throws IOException, GeneralSecurityException {
    try {
        final String privateKeyFile = "keys/server.pkcs8.key";
        final String certificateFile = "keys/server.crt";
        final String rootCAFile = "keys/rootCA.pem";

        final PrivateKey privateKey = loadPrivateKey(privateKeyFile);
        final X509Certificate certificate = loadX509Cert(certificateFile);
        final X509Certificate rootCA = loadX509Cert(rootCAFile);

        return SslContextBuilder.forClient()
                .sslProvider(SslProvider.JDK)
                .trustManager(rootCA)
                .keyManager(privateKey, certificate)
                .build();

    } catch (IOException | GeneralSecurityException e) {
        LOGGER.warn("Failed to establish SSL Context");
        LOGGER.debug("Failed to establish SSL Context", e);
        throw e;
    }
}
项目:incubator-pulsar    文件:PulsarChannelInitializer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    if (enableTLS) {
        File tlsCert = new File(serviceConfig.getTlsCertificateFilePath());
        File tlsKey = new File(serviceConfig.getTlsKeyFilePath());
        SslContextBuilder builder = SslContextBuilder.forServer(tlsCert, tlsKey);
        if (serviceConfig.isTlsAllowInsecureConnection()) {
            builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
        } else {
            if (serviceConfig.getTlsTrustCertsFilePath().isEmpty()) {
                // Use system default
                builder.trustManager((File) null);
            } else {
                File trustCertCollection = new File(serviceConfig.getTlsTrustCertsFilePath());
                builder.trustManager(trustCertCollection);
            }
        }
        SslContext sslCtx = builder.clientAuth(ClientAuth.OPTIONAL).build();
        ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc()));
    }
    ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(PulsarDecoder.MaxFrameSize, 0, 4, 0, 4));
    ch.pipeline().addLast("handler", new ServerCnx(brokerService));
}
项目:LiteGraph    文件:GremlinServerIntegrateTest.java   
@Test
public void shouldEnableSslWithSslContextProgrammaticallySpecified() throws Exception {
    // just for testing - this is not good for production use
    final SslContextBuilder builder = SslContextBuilder.forClient();
    builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    builder.sslProvider(SslProvider.JDK);

    final Cluster cluster = Cluster.build().enableSsl(true).sslContext(builder.build()).create();
    final Client client = cluster.connect();

    try {
        // this should return "nothing" - there should be no exception
        assertEquals("test", client.submit("'test'").one().getString());
    } finally {
        cluster.close();
    }
}
项目:Dream-Catcher    文件:SslUtil.java   
/**
 * Creates a netty SslContext for use when connecting to upstream servers. Retrieves the list of trusted root CAs
 * from the trustSource. When trustSource is true, no upstream certificate verification will be performed.
 * <b>This will make it possible for attackers to MITM communications with the upstream server</b>, so always
 * supply an appropriate trustSource except in extraordinary circumstances (e.g. testing with dynamically-generated
 * certificates).
 *
 * @param cipherSuites    cipher suites to allow when connecting to the upstream server
 * @param trustSource     the trust store that will be used to validate upstream servers' certificates, or null to accept all upstream server certificates
 * @return an SSLContext to connect to upstream servers with
 */
public static SslContext getUpstreamServerSslContext(Collection<String> cipherSuites, TrustSource trustSource) {
    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

    if (trustSource == null) {
        log.warn("Disabling upstream server certificate verification. This will allow attackers to intercept communications with upstream servers.");

        sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslContextBuilder.trustManager(trustSource.getTrustedCAs());
    }

    sslContextBuilder.ciphers(cipherSuites, SupportedCipherSuiteFilter.INSTANCE);

    try {
        return sslContextBuilder.build();
    } catch (SSLException e) {
        throw new SslContextInitializationException("Error creating new SSL context for connection to upstream server", e);
    }
}
项目:reactor-netty    文件:HttpClientTest.java   
@Test
public void sshExchangeAbsoluteGet() throws CertificateException, SSLException {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    SslContext sslClient = SslContextBuilder.forClient()
                                            .trustManager(ssc.cert()).build();

    NettyContext context =
            HttpServer.create(opt -> opt.sslContext(sslServer))
                      .newHandler((req, resp) -> resp.sendString(Flux.just("hello ", req.uri())))
                      .block();

    HttpClientResponse response = HttpClient.create(
            opt -> applyHostAndPortFromContext(opt, context)
                    .sslContext(sslClient))
            .get("/foo").block();
    context.dispose();
    context.onClose().block();

    String responseString = response.receive().aggregate().asString(CharsetUtil.UTF_8).block();
    assertThat(responseString).isEqualTo("hello /foo");
}
项目:byproxy    文件:ServerSSLContextManager.java   
private SslContext getNettySslContextInner(String host, boolean useH2) throws Exception {
        long start = System.currentTimeMillis();
        PrivateKeyAndCertChain keyAndCertChain = keyStoreGenerator.generateCertChain(host, Settings.certValidityDays);
        logger.debug("Create certificate for {}, cost {} ms", host, System.currentTimeMillis() - start);
        SslContextBuilder builder = SslContextBuilder
                .forServer(keyAndCertChain.getPrivateKey(), keyAndCertChain.getCertificateChain());
        if (useH2) {
//                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            builder.applicationProtocolConfig(new ApplicationProtocolConfig(
                    ApplicationProtocolConfig.Protocol.ALPN,
                    SelectorFailureBehavior.NO_ADVERTISE,
                    SelectedListenerFailureBehavior.ACCEPT,
                    ApplicationProtocolNames.HTTP_2,
                    ApplicationProtocolNames.HTTP_1_1));
        }
        return builder.build();
    }
项目:xockets.io    文件:SSLFactory.java   
/**
 * Creates a new SslContext object.
 *
 * @param cfg the cfg
 * @return the ssl context
 */
private synchronized SslContext createServerSslContext(IConfig cfg){
    SslContext ctx = null;
    try{
            SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;

            if(provider.equals(SslProvider.OPENSSL)){
                cfg.print("Using OpenSSL for network encryption.");
            }

            ctx = SslContextBuilder
                    .forServer(new File(cfg.getCertFile()), new File(cfg.getKeyFile()), cfg.getKeyPassword())
                    .sslProvider(provider)
                    .build();

    }catch(Exception e){
        LOG.log(Level.SEVERE, null, e);
    }

    return ctx;
}
项目:JavaAyo    文件:FactorialServer.java   
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new FactorialServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
项目:JavaAyo    文件:SecureChatServer.java   
public static void main(String[] args) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
        .build();

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new SecureChatServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
项目:JavaAyo    文件:HttpCorsServer.java   
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new HttpCorsServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
项目:JavaAyo    文件:WorldClockServer.java   
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new WorldClockServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
项目:JavaAyo    文件:TelnetServer.java   
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new TelnetServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
项目:jlogstash-input-plugin    文件:SslSimpleBuilder.java   
public SslHandler build(ByteBufAllocator bufferAllocator) throws SSLException {
    SslContextBuilder builder = SslContextBuilder.forServer(sslCertificateFile, sslKeyFile, passPhrase);

    builder.ciphers(Arrays.asList(ciphers));

    if(requireClientAuth()) {
        logger.debug("Certificate Authorities: " + certificateAuthorities);
        builder.trustManager(new File(certificateAuthorities));
    }

    SslContext context = builder.build();
    SslHandler sslHandler = context.newHandler(bufferAllocator);

    SSLEngine engine = sslHandler.engine();
    engine.setEnabledProtocols(protocols);


    if(requireClientAuth()) {
        engine.setUseClientMode(false);
        engine.setNeedClientAuth(true);
    }

    return sslHandler;
}
项目:samebug-idea-plugin    文件:WebSocketClient.java   
public WebSocketClient(WebSocketConfig config) throws URISyntaxException, SSLException, InterruptedException {
    final int port = config.serverUri.getPort();
    final String scheme = config.serverUri.getScheme().endsWith("s") ? "wss" : "ws";
    final boolean isWss = "wss".equalsIgnoreCase(scheme);

    this.headers = new DefaultHttpHeaders();
    if (config.apiKey != null) headers.add("X-Samebug-ApiKey", config.apiKey);
    if (config.workspaceId != null) headers.add("X-Samebug-WorkspaceId", config.workspaceId);

    this.port = port == -1 ? (isWss ? 443 : 80) : port;
    this.host = config.serverUri.getHost();
    this.wsEndpoint = new URI(scheme, null, host, port, "/sockets/websocket", null, null);
    this.eventHandler = config.eventHandler;
    this.group = config.group;
    this.sslContext = isWss ? SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build() : null;
    // IMPROVE the constructor blocks the thread with networking!
    this.channel = connect();
}
项目:nomulus    文件:SslClientInitializer.java   
@Override
protected void initChannel(C channel) throws Exception {
  BackendProtocol protocol = (BackendProtocol) channel.attr(PROTOCOL_KEY).get();
  checkNotNull(protocol, "Protocol is not set for channel: %s", channel);
  SslHandler sslHandler =
      SslContextBuilder.forClient()
          .sslProvider(sslProvider)
          .trustManager(trustedCertificates)
          .build()
          .newHandler(channel.alloc(), protocol.host(), protocol.port());

  // Enable hostname verification.
  SSLEngine sslEngine = sslHandler.engine();
  SSLParameters sslParameters = sslEngine.getSSLParameters();
  sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
  sslEngine.setSSLParameters(sslParameters);

  channel.pipeline().addLast(sslHandler);
}
项目:nomulus    文件:SslClientInitializerTest.java   
private ChannelInitializer<LocalChannel> getServerInitializer(
    PrivateKey privateKey,
    X509Certificate certificate,
    Lock serverLock,
    Exception serverException)
    throws Exception {
  SslContext sslContext = SslContextBuilder.forServer(privateKey, certificate).build();
  return new ChannelInitializer<LocalChannel>() {
    @Override
    protected void initChannel(LocalChannel ch) throws Exception {
      ch.pipeline()
          .addLast(
              sslContext.newHandler(ch.alloc()), new EchoHandler(serverLock, serverException));
    }
  };
}
项目:jiguang-java-client-common    文件:NettyHttpClient.java   
public NettyHttpClient(String authCode, HttpProxy proxy, ClientConfig config) {
    _maxRetryTimes = config.getMaxRetryTimes();
    _readTimeout = config.getReadTimeout();
    String message = MessageFormat.format("Created instance with "
                    + "connectionTimeout {0}, readTimeout {1}, maxRetryTimes {2}, SSL Version {3}",
            config.getConnectionTimeout(), _readTimeout, _maxRetryTimes, config.getSSLVersion());
    LOG.debug(message);
    _authCode = authCode;

    try {
        _sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        _workerGroup = new NioEventLoopGroup();
        b = new Bootstrap(); // (1)
        b.group(_workerGroup); // (2)
        b.channel(NioSocketChannel.class); // (3)
        b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
    } catch (SSLException e) {
        e.printStackTrace();
    }
}
项目:spike.x    文件:KeyStoreHelper.java   
public SslContext buildOpenSslClientContext(final boolean clientAuth) throws IOException {

        SslContext ctx;

        if (clientAuth) {
            ctx = SslContextBuilder.forClient()
                    .sslProvider(SslProvider.OPENSSL)
                    .trustManager(getTrustCertChainPath().toAbsolutePath().normalize().toFile())
                    .keyManager(getClientCertPath().toAbsolutePath().normalize().toFile(),
                            getClientKeyPath().toAbsolutePath().normalize().toFile())
                    .build();
        } else {
            ctx = SslContextBuilder.forClient()
                    .sslProvider(SslProvider.OPENSSL)
                    .trustManager(getTrustCertChainPath().toAbsolutePath().normalize().toFile())
                    .build();
        }

        return ctx;
    }
项目:jmeter-http2-plugin    文件:NettyHttp2Client.java   
private SslContext getSslContext() {
    SslContext sslCtx = null;

    final SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;

    try {
        sslCtx = SslContextBuilder.forClient()
            .sslProvider(provider)
            .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(
                Protocol.ALPN,
                SelectorFailureBehavior.NO_ADVERTISE,
                SelectedListenerFailureBehavior.ACCEPT,
                ApplicationProtocolNames.HTTP_2))
            .build();
    } catch(SSLException exception) {
        return null;
    }

    return sslCtx;
}
项目:search-guard-ssl    文件:DefaultSearchGuardKeyStore.java   
private SslContext buildSSLServerContext(final PrivateKey _key, final X509Certificate[] _cert, final X509Certificate[] _trustedCerts, final Iterable<String> ciphers, final SslProvider sslProvider, final ClientAuth authMode) throws SSLException {

        final SslContextBuilder _sslContextBuilder = 
                SslContextBuilder
                .forServer(_key, _cert)
                .ciphers(ciphers)
                .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED)
                .clientAuth(Objects.requireNonNull(authMode)) // https://github.com/netty/netty/issues/4722
                .sessionCacheSize(0)
                .sessionTimeout(0)
                .sslProvider(sslProvider);

        if(_trustedCerts != null && _trustedCerts.length > 0) {
            _sslContextBuilder.trustManager(_trustedCerts);
        }

        return buildSSLContext0(_sslContextBuilder);
    }
项目:search-guard-ssl    文件:DefaultSearchGuardKeyStore.java   
private SslContext buildSSLServerContext(final File _key, final File _cert, final File _trustedCerts, final String pwd, final Iterable<String> ciphers, final SslProvider sslProvider, final ClientAuth authMode) throws SSLException {

        final SslContextBuilder _sslContextBuilder = 
                SslContextBuilder
                .forServer(_cert, _key, pwd)
                .ciphers(ciphers)
                .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED)
                .clientAuth(Objects.requireNonNull(authMode)) // https://github.com/netty/netty/issues/4722
                .sessionCacheSize(0)
                .sessionTimeout(0)
                .sslProvider(sslProvider);

        if(_trustedCerts != null) {
            _sslContextBuilder.trustManager(_trustedCerts);
        }

        return buildSSLContext0(_sslContextBuilder);
    }
项目:search-guard-ssl    文件:DefaultSearchGuardKeyStore.java   
private SslContext buildSSLClientContext(final PrivateKey _key, final X509Certificate[] _cert, final X509Certificate[] _trustedCerts, final Iterable<String> ciphers, final SslProvider sslProvider) throws SSLException {

        final SslContextBuilder _sslClientContextBuilder = 
                SslContextBuilder
                .forClient()
                .ciphers(ciphers)
                .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED)
                .sessionCacheSize(0)
                .sessionTimeout(0)
                .sslProvider(sslProvider)
                .trustManager(_trustedCerts)
                .keyManager(_key, _cert);

        return buildSSLContext0(_sslClientContextBuilder);

    }
项目:search-guard-ssl    文件:DefaultSearchGuardKeyStore.java   
private SslContext buildSSLClientContext(final File _key, final File _cert, final File _trustedCerts, final String pwd, final Iterable<String> ciphers, final SslProvider sslProvider) throws SSLException {

        final SslContextBuilder _sslClientContextBuilder = 
                SslContextBuilder
                .forClient()
                .ciphers(ciphers)
                .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED)
                .sessionCacheSize(0)
                .sessionTimeout(0)
                .sslProvider(sslProvider)
                .trustManager(_trustedCerts)
                .keyManager(_cert, _key, pwd);

        return buildSSLContext0(_sslClientContextBuilder);

    }
项目:search-guard-ssl    文件:DefaultSearchGuardKeyStore.java   
private SslContext buildSSLContext0(final SslContextBuilder sslContextBuilder) throws SSLException {

        final SecurityManager sm = System.getSecurityManager();

        if (sm != null) {
            sm.checkPermission(new SpecialPermission());
        }

        SslContext sslContext = null;
        try {
            sslContext = AccessController.doPrivileged(new PrivilegedExceptionAction<SslContext>() {
                @Override
                public SslContext run() throws Exception {
                    return sslContextBuilder.build();
                }
            });
        } catch (final PrivilegedActionException e) {
            throw (SSLException) e.getCause();
        }

        return sslContext;
    }
项目:GameServerFramework    文件:NettyCenter.java   
/**
 * 私有构造函数
 */
private NettyCenter() {
    int maybeThreadSize = Runtime.getRuntime().availableProcessors();
    if (maybeThreadSize == 1) maybeThreadSize += 2;
    else if (maybeThreadSize == 8) maybeThreadSize = 2;
    else if (maybeThreadSize > 8) maybeThreadSize /= 2;
    /**
     * 构造事件循环组
     */
    eventLoopGroup = new NioEventLoopGroup(maybeThreadSize, new DefaultThreadFactory("NettyNioLoopGroup"));
    /**
     * 构造定时器
     */
    hashedWheelTimer = new HashedWheelTimer(new DefaultThreadFactory("NettyHashedWheelTimer"));
    /**
     * 构造 SSL 环境
     */
    try {
        SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
        sslContextBuilder.clientAuth(ClientAuth.OPTIONAL);
        simpleClientSslContext = sslContextBuilder.build();
    } catch (Throwable e) {
        log.error("NettyCenter :: initialize client sslcontext error!", e);
    }
}
项目:armeria    文件:AbstractVirtualHostBuilder.java   
/**
 * Sets the {@link SslContext} of this {@link VirtualHost} from the specified {@link SessionProtocol},
 * {@code keyCertChainFile}, {@code keyFile} and {@code keyPassword}.
 */
public B sslContext(
        SessionProtocol protocol,
        File keyCertChainFile, File keyFile, String keyPassword) throws SSLException {

    if (requireNonNull(protocol, "protocol") != SessionProtocol.HTTPS) {
        throw new IllegalArgumentException("unsupported protocol: " + protocol);
    }

    final SslContextBuilder builder = SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword);

    builder.sslProvider(Flags.useOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK);
    builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE);
    builder.applicationProtocolConfig(HTTPS_ALPN_CFG);

    sslContext(builder.build());
    return self();
}
项目:carbon-transports    文件:SSLHandlerFactory.java   
/**
 * This method will provide netty ssl context which supports HTTP2 over TLS using
 * Application Layer Protocol Negotiation (ALPN)
 *
 * @return instance of {@link SslContext}
 * @throws SSLException if any error occurred during building SSL context.
 */
public SslContext createHttp2TLSContext() throws SSLException {

    // If listener configuration does not include cipher suites , default ciphers required by the HTTP/2
    // specification will be added.
    List<String> ciphers = sslConfig.getCipherSuites() != null && sslConfig.getCipherSuites().length > 0 ? Arrays
            .asList(sslConfig.getCipherSuites()) : Http2SecurityUtil.CIPHERS;
    SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
    return SslContextBuilder.forServer(this.getKeyManagerFactory())
            .trustManager(this.getTrustStoreFactory())
            .sslProvider(provider)
            .ciphers(ciphers,
                    SupportedCipherSuiteFilter.INSTANCE)
            .clientAuth(needClientAuth ? ClientAuth.REQUIRE : ClientAuth.NONE)
            .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();
}
项目:blynk-server    文件:WebSocketClient.java   
public WebSocketClient(String host, int port, String path, boolean isSSL) throws Exception {
    super(host, port, new Random());

    String scheme = isSSL ? "wss://" : "ws://";
    URI uri = new URI(scheme + host + ":" + port + path);

    if (isSSL) {
        sslCtx = SslContextBuilder.forClient().sslProvider(SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    this.handler = new WebSocketClientHandler(
                    WebSocketClientHandshakerFactory.newHandshaker(
                            uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));
}
项目:blynk-server    文件:SslContextHolder.java   
public static SslContext build(File serverCert, File serverKey, String serverPass,
                               SslProvider sslProvider, File clientCert) throws SSLException {
    log.info("Creating SSL context for cert '{}', key '{}', key pass '{}'",
            serverCert.getAbsolutePath(), serverKey.getAbsoluteFile(), serverPass);
    if (serverPass == null || serverPass.isEmpty()) {
        return SslContextBuilder.forServer(serverCert, serverKey)
                .sslProvider(sslProvider)
                .trustManager(clientCert)
                .build();
    } else {
        return SslContextBuilder.forServer(serverCert, serverKey, serverPass)
                .sslProvider(sslProvider)
                .trustManager(clientCert)
                .build();
    }
}
项目:tinkerpop    文件:GremlinServerIntegrateTest.java   
@Test
public void shouldEnableSslWithSslContextProgrammaticallySpecified() throws Exception {
    // just for testing - this is not good for production use
    final SslContextBuilder builder = SslContextBuilder.forClient();
    builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    builder.sslProvider(SslProvider.JDK);

    final Cluster cluster = TestClientFactory.build().enableSsl(true).sslContext(builder.build()).create();
    final Client client = cluster.connect();

    try {
        // this should return "nothing" - there should be no exception
        assertEquals("test", client.submit("'test'").one().getString());
    } finally {
        cluster.close();
    }
}
项目:etcd4j    文件:SecurityContextBuilder.java   
/**
 * Builds SslContext using protected keystore file overriding default key manger algorithm. Adequate for non-mutual TLS connections.
 *
 * @param keystore Keystore inputstream (file, binaries, etc)
 * @param keystorePassword Password for protected keystore file
 * @param keyManagerAlgorithm Algorithm for keyManager used to process keystorefile
 * @return SslContext ready to use
 * @throws SecurityContextException for any troubles building the SslContext
 */
public static SslContext forKeystore(InputStream keystore, String keystorePassword, String keyManagerAlgorithm)
        throws SecurityContextException {

    try {
        final KeyStore ks = KeyStore.getInstance(KEYSTORE_JKS);
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);

        ks.load(keystore, keystorePassword.toCharArray());
        kmf.init(ks, keystorePassword.toCharArray());

        SslContextBuilder ctxBuilder = SslContextBuilder.forClient().keyManager(kmf);
        return ctxBuilder.build();
    } catch (Exception e) {
        throw new SecurityContextException(e);
    }
}
项目:etcd4j    文件:SecurityContextBuilder.java   
/**
 * Builds SslContext using protected keystore and truststores, overriding default key manger algorithm. Adequate for mutual TLS connections.
 * @param keystore Keystore inputstream (file, binaries, etc)
 * @param keystorePassword Password for protected keystore file
 * @param truststore Truststore inputstream (file, binaries, etc)
 * @param truststorePassword Password for protected truststore file
 * @param keyManagerAlgorithm Algorithm for keyManager used to process keystorefile
 * @return SslContext ready to use
 * @throws SecurityContextException
 */
public static SslContext forKeystoreAndTruststore(InputStream keystore, String keystorePassword, InputStream truststore, String truststorePassword, String keyManagerAlgorithm)
        throws SecurityContextException {
    try {
        final KeyStore ks = KeyStore.getInstance(KEYSTORE_JKS);
        final KeyStore ts = KeyStore.getInstance(KEYSTORE_JKS);

        final KeyManagerFactory keystoreKmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
        final TrustManagerFactory truststoreKmf = TrustManagerFactory.getInstance(keyManagerAlgorithm);

        ks.load(keystore, keystorePassword.toCharArray());
        ts.load(truststore, truststorePassword.toCharArray());

        keystoreKmf.init(ks, keystorePassword.toCharArray());
        truststoreKmf.init(ts);

        SslContextBuilder ctxBuilder = SslContextBuilder.forClient().keyManager(keystoreKmf);
        ctxBuilder.trustManager(truststoreKmf);

        return ctxBuilder.build();
    } catch (Exception e) {
        throw new SecurityContextException(e);
    }
}
项目:postgres-async-driver    文件:NettyPgProtocolStream.java   
ChannelHandler newSslInitiator() {
    return new ByteToMessageDecoder() {
        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            if(in.readableBytes() < 1) {
                return;
            }
            if('S' != in.readByte()) {
                ctx.fireExceptionCaught(new IllegalStateException("SSL required but not supported by backend server"));
                return;
            }
            ctx.pipeline().remove(this);
            ctx.pipeline().addFirst(
                    SslContextBuilder
                            .forClient()
                            .trustManager(InsecureTrustManagerFactory.INSTANCE)
                            .build()
                            .newHandler(ctx.alloc()));
        }
    };
}
项目:jooby    文件:NettySslContext.java   
static SslContext build(final Config conf) throws IOException, CertificateException {
  String tmpdir = conf.getString("application.tmpdir");
  boolean http2 = conf.getBoolean("server.http2.enabled");
  File keyStoreCert = toFile(conf.getString("ssl.keystore.cert"), tmpdir);
  File keyStoreKey = toFile(conf.getString("ssl.keystore.key"), tmpdir);
  String keyStorePass = conf.hasPath("ssl.keystore.password")
      ? conf.getString("ssl.keystore.password") : null;
  SslContextBuilder scb = SslContextBuilder.forServer(keyStoreCert, keyStoreKey, keyStorePass);
  if (conf.hasPath("ssl.trust.cert")) {
    scb.trustManager(toFile(conf.getString("ssl.trust.cert"), tmpdir))
       .clientAuth(ClientAuth.REQUIRE);
  }
  if (http2) {
    SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
    return scb.sslProvider(provider)
        .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
        .applicationProtocolConfig(new ApplicationProtocolConfig(
            Protocol.ALPN,
            SelectorFailureBehavior.NO_ADVERTISE,
            SelectedListenerFailureBehavior.ACCEPT,
            Arrays.asList(ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)))
        .build();
  }
  return scb.build();
}