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

项目: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();
    }
}
项目:drift    文件:ConnectionFactory.java   
ConnectionFactory(
        EventLoopGroup group,
        MessageFraming messageFraming,
        MessageEncoding messageEncoding,
        Optional<Supplier<SslContext>> sslContextSupplier,
        DriftNettyClientConfig clientConfig)
{
    this.group = requireNonNull(group, "group is null");
    this.messageFraming = requireNonNull(messageFraming, "messageFraming is null");
    this.messageEncoding = requireNonNull(messageEncoding, "messageEncoding is null");
    this.sslContextSupplier = requireNonNull(sslContextSupplier, "sslContextSupplier is null");

    requireNonNull(clientConfig, "clientConfig is null");
    this.connectTimeout = clientConfig.getConnectTimeout();
    this.requestTimeout = clientConfig.getRequestTimeout();
    this.socksProxy = Optional.ofNullable(clientConfig.getSocksProxy());
}
项目:indeed-grpc-java    文件:SslContextReloader.java   
@Override
public boolean load() {
    final SslContext previous = reference.get();
    try {
        final SslContext context = loader.get();
        if (context == null) {
            return finishLoadWithReloadState(ReloadState.FAILED, null);
        }

        if (Objects.equals(previous, context)) {
            return finishLoadWithReloadState(ReloadState.NO_CHANGE, null);
        }

        reference.set(context);
        return finishLoadWithReloadState(ReloadState.RELOADED, null);
    } catch (final Exception e) {
        LOGGER.error("Failed to load SslContext.", e);
    }

    return finishLoadWithReloadState(ReloadState.FAILED, null);
}
项目:indeed-grpc-java    文件:SslContextReloaderTest.java   
@Test
public void get() throws Exception {
    final SslContextReloader reloader = new SslContextReloader(() -> null);

    assertFalse(reloader.load());
    assertEquals(ReloadState.FAILED, reloader.getReloadState());
    assertNull(reloader.getDataVersion());

    final SslContext context = reloader.get();
    assertNotNull(context);

    expectNullPointerException(context::isClient);
    expectNullPointerException(context::cipherSuites);
    expectNullPointerException(context::sessionCacheSize);
    expectNullPointerException(context::sessionTimeout);
    expectNullPointerException(context::applicationProtocolNegotiator);
    expectNullPointerException(context::sessionContext);
    expectNullPointerException(() -> context.newEngine(ByteBufAllocator.DEFAULT));
    expectNullPointerException(() -> context.newEngine(ByteBufAllocator.DEFAULT, "localhost", 1234));
}
项目:qonduit    文件:Server.java   
protected ChannelHandler setupWSChannel(SslContext sslCtx, Configuration conf, DataStore datastore) {
    return new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", sslCtx.newHandler(ch.alloc()));
            ch.pipeline().addLast("httpServer", new HttpServerCodec());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
            ch.pipeline().addLast("sessionExtractor", new WebSocketHttpCookieHandler(config));
            ch.pipeline().addLast("idle-handler", new IdleStateHandler(conf.getWebsocket().getTimeout(), 0, 0));
            ch.pipeline().addLast("ws-protocol", new WebSocketServerProtocolHandler(WS_PATH, null, true));
            ch.pipeline().addLast("wsDecoder", new WebSocketRequestDecoder(datastore, config));
            ch.pipeline().addLast("error", new WSExceptionHandler());
        }
    };

}
项目:NioImapClient    文件:ImapClient.java   
public ImapClient(ImapClientConfiguration configuration,
                  Channel channel,
                  SslContext sslContext,
                  EventExecutorGroup promiseExecutor,
                  String clientName) {
  this.logger = LogUtils.loggerWithName(ImapClient.class, clientName);
  this.configuration = configuration;
  this.channel = channel;
  this.sslContext = sslContext;
  this.promiseExecutor = promiseExecutor;
  this.clientState = new ImapClientState(clientName, promiseExecutor);
  this.codec = new ImapCodec(clientState);
  this.pendingWriteQueue = new ConcurrentLinkedQueue<>();
  this.connectionShutdown = new AtomicBoolean(false);
  this.connectionClosed = new AtomicBoolean(false);
  this.capabilities = new AtomicReference<>(null);

  configureChannel();
}
项目:spring-credhub    文件:ClientHttpRequestFactoryFactory.java   
static ClientHttpRequestFactory usingNetty(ClientOptions options)
        throws IOException, GeneralSecurityException {

    SslContext sslContext = new JdkSslContext(SSLContext.getDefault(), true, ClientAuth.REQUIRE);

    final Netty4ClientHttpRequestFactory requestFactory = new Netty4ClientHttpRequestFactory();
    requestFactory.setSslContext(sslContext);

    if (options.getConnectionTimeout() != null) {
        requestFactory.setConnectTimeout(options.getConnectionTimeout());
    }
    if (options.getReadTimeout() != null) {
        requestFactory.setReadTimeout(options.getReadTimeout());
    }

    return requestFactory;
}
项目:byproxy    文件:ServerSSLContextManager.java   
/**
 * Create ssl context for the host
 */
public SslContext createSSlContext(String host, boolean useH2) {
    String finalHost = Networks.wildcardHost(host);
    lock.readLock().lock();
    try {
        return sslContextCache.computeIfAbsent(host + ":" + useH2, key -> {
            try {
                return getNettySslContextInner(finalHost, useH2);
            } catch (Exception e) {
                throw new SSLContextException(e);
            }
        });
    } finally {
        lock.readLock().unlock();
    }
}
项目: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);
    }
}
项目: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));
    }
  };
}
项目: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();
    }
项目:riposte    文件:HttpChannelInitializerTest.java   
@Test
public void initChannel_adds_sslCtx_handler_first_if_available_and_no_utility_handlers() throws SSLException {
    // given
    SslContext sslCtx = new JdkSslClientContext();
    HttpChannelInitializer hci = basicHttpChannelInitializer(sslCtx, 0, 100, false, mock(RequestValidator.class),
                                                             createRequestAndResponseFilterMock());

    // when
    hci.initChannel(socketChannelMock);

    // then
    ArgumentCaptor<ChannelHandler> channelHandlerArgumentCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
    verify(channelPipelineMock, atLeastOnce()).addLast(anyString(), channelHandlerArgumentCaptor.capture());
    List<ChannelHandler> handlers = channelHandlerArgumentCaptor.getAllValues();
    assertThat(handlers.get(0), instanceOf(SslHandler.class));
}
项目: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;
    }
}
项目: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();
    }
}
项目:LiteGraph    文件:Channelizer.java   
@Override
protected void initChannel(final SocketChannel socketChannel) throws Exception {
    final ChannelPipeline pipeline = socketChannel.pipeline();
    final Optional<SslContext> sslCtx;
    if (supportsSsl()) {
        try {
            sslCtx = Optional.of(cluster.createSSLContext());
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    } else {
        sslCtx = Optional.empty();
    }

    if (sslCtx.isPresent()) {
        pipeline.addLast(sslCtx.get().newHandler(socketChannel.alloc(), connection.getUri().getHost(), connection.getUri().getPort()));
    }

    configure(pipeline);
    pipeline.addLast(PIPELINE_GREMLIN_SASL_HANDLER, new Handler.GremlinSaslAuthenticationHandler(cluster.authProperties()));
    pipeline.addLast(PIPELINE_GREMLIN_HANDLER, new Handler.GremlinResponseHandler(pending, connection.getClient().getSettings()));
}
项目: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    文件: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();
    }
}
项目: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");
}
项目:zbus    文件:TcpServer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {  
    ChannelPipeline p = ch.pipeline(); 
    int timeout = loop.getIdleTimeInSeconds();
    p.addLast(new IdleStateHandler(0, 0, timeout));
    SslContext sslCtx = loop.getSslContext();
    if(sslCtx != null){
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }
    CodecInitializer initializer = getCodecInitializer();
    if(initializer != null){
        List<ChannelHandler> handlers = new ArrayList<ChannelHandler>();
        initializer.initPipeline(handlers);
        for(ChannelHandler handler : handlers){
             p.addLast((ChannelHandler)handler); 
        }
    }    
    p.addLast(this.nettyToIoAdaptor);
}
项目:firebase-admin-java    文件:NettyWebSocketClient.java   
@Override
public void connect() {
  checkState(channel == null, "channel already initialized");
  try {
    TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
    trustFactory.init((KeyStore) null);
    final SslContext sslContext = SslContextBuilder.forClient()
        .trustManager(trustFactory).build();
    Bootstrap bootstrap = new Bootstrap();
    final int port = uri.getPort() != -1 ? uri.getPort() : DEFAULT_WSS_PORT;
    bootstrap.group(group)
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) {
            ChannelPipeline p = ch.pipeline();
            p.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), port));
            p.addLast(
                new HttpClientCodec(),
                // Set the max size for the HTTP responses. This only applies to the WebSocket
                // handshake response from the server.
                new HttpObjectAggregator(32 * 1024),
                channelHandler);
          }
        });

    ChannelFuture channelFuture = bootstrap.connect(uri.getHost(), port);
    this.channel = channelFuture.channel();
    channelFuture.addListener(
        new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
              eventHandler.onError(future.cause());
            }
          }
        }
    );
  } catch (Exception e) {
    eventHandler.onError(e);
  }
}
项目:monica    文件:SocketServer.java   
public void start() throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new FileServerHandlerInitializer());

        // Start the server.
        ChannelFuture f = b.bind(getHostAddress(), PORT).sync();
        // System.out.println("server is started "+f.isSuccess());
        setStarted(true);
        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}
项目:nitmproxy    文件:TlsUtil.java   
public static SslContext ctxForClient(NitmProxyConfig config) throws SSLException {
    SslContextBuilder builder = SslContextBuilder
            .forClient()
            .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            .applicationProtocolConfig(applicationProtocolConfig(config, config.isServerHttp2()));
    if (config.isInsecure()) {
        builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    }
    return builder.build();
}
项目:nitmproxy    文件:TlsUtil.java   
public static SslContext ctxForServer(NitmProxyConfig config, String serverHost) throws SSLException {
    Certificate certificate = CertUtil.newCert(config.getCertFile(), config.getKeyFile(), serverHost);
    return SslContextBuilder
            .forServer(certificate.getKeyPair().getPrivate(), certificate.getChain())
            .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            .applicationProtocolConfig(applicationProtocolConfig(config, config.isClientHttp2()))
            .build();
}
项目:nitmproxy    文件:TlsHandler.java   
private SslContext sslCtx() throws SSLException {
    if (client) {
        return TlsUtil.ctxForServer(master.config(), connectionInfo.getServerAddr().getHost());
    } else {
        return TlsUtil.ctxForClient(master.config());
    }
}
项目:drift    文件:ReloadableSslContext.java   
public SslContext getSslContext()
{
    if (exception != null) {
        throw exception;
    }
    return sslContext;
}
项目:drift    文件:ThriftClientInitializer.java   
public ThriftClientInitializer(
        MessageFraming messageFraming,
        MessageEncoding messageEncoding,
        Duration requestTimeout,
        Optional<HostAndPort> socksProxyAddress,
        Optional<Supplier<SslContext>> sslContextSupplier)
{
    this.messageFraming = messageFraming;
    this.requestTimeout = requestTimeout;
    this.messageEncoding = messageEncoding;
    this.socksProxyAddress = socksProxyAddress;
    this.sslContextSupplier = sslContextSupplier;
}
项目:neto    文件:ProtocolUnificationHandler.java   
private ProtocolUnificationHandler(boolean isUnificationMode, BiMap<Integer, Class<? extends NetoJsonMessage>> opcodeMap, SslContext sslCtx, boolean detectSsl, int maxFrameLength, String charset) {
    this.isUnificationMode = isUnificationMode;
    this.opcodeMap = opcodeMap;
    this.sslCtx = sslCtx;
    this.detectSsl = detectSsl;
    this.maxFrameLength = maxFrameLength;
    this.charset = charset;
}
项目:kafka-connect-cassandra    文件:CassandraSessionFactoryImpl.java   
@Override
public CassandraSession newSession(CassandraSinkConnectorConfig config) {
  Cluster.Builder clusterBuilder = Cluster.builder()
      .withPort(config.port)
      .addContactPoints(config.contactPoints)
      .withProtocolVersion(ProtocolVersion.NEWEST_SUPPORTED);
  if (config.securityEnabled) {
    clusterBuilder.withCredentials(config.username, config.password);
  }
  if (config.sslEnabled) {
    final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
    sslContextBuilder.sslProvider(config.sslProvider);
    final SslContext context;
    try {
      context = sslContextBuilder.build();
    } catch (SSLException e) {
      throw new ConnectException(e);
    }
    final SSLOptions sslOptions = new RemoteEndpointAwareNettySSLOptions(context);
    clusterBuilder.withSSL(sslOptions);
  }
  clusterBuilder.withCompression(config.compression);
  Cluster cluster = clusterBuilder.build();
  log.info("Creating session");
  final Session session = cluster.newSession();
  return new CassandraSessionImpl(config, cluster, session);
}
项目:hekate    文件:NettySslUtils.java   
/**
 * Builds a new client SSL context.
 *
 * @param cfg SSL configuration.
 * @param res Resource service for loading {@link KeyStore}.
 *
 * @return SSL context.
 */
public static SslContext clientContext(NetworkSslConfig cfg, ResourceService res) {
    ConfigCheck check = checkConfig(cfg);

    try {
        return SslContextBuilder.forClient()
            .sslProvider(provider(cfg))
            .trustManager(trustManager(cfg, res))
            .sessionCacheSize(cfg.getSslSessionCacheSize())
            .sessionTimeout(cfg.getSslSessionCacheTimeout())
            .build();
    } catch (ResourceLoadingException | GeneralSecurityException | IOException e) {
        throw check.fail(e);
    }
}
项目:hekate    文件:NettySslUtils.java   
/**
 * Builds a new server SSL context.
 *
 * @param cfg SSL configuration.
 * @param res Resource service for loading {@link KeyStore}.
 *
 * @return SSL context.
 */
public static SslContext serverContext(NetworkSslConfig cfg, ResourceService res) {
    ConfigCheck check = checkConfig(cfg);

    try {
        return SslContextBuilder.forServer(keyManager(cfg, res))
            .sslProvider(provider(cfg))
            .trustManager(trustManager(cfg, res))
            .sessionCacheSize(cfg.getSslSessionCacheSize())
            .sessionTimeout(cfg.getSslSessionCacheTimeout())
            .build();
    } catch (ResourceLoadingException | GeneralSecurityException | IOException e) {
        throw check.fail(e);
    }
}
项目:xitk    文件:HttpServer.java   
public HttpServer(SslContext sslContext, int port, int numThreads) {
    this.sslContext = sslContext;
    this.port = port;
    if (numThreads > 0) {
        this.numThreads = numThreads;
    } else {
        this.numThreads = 4 * Runtime.getRuntime().availableProcessors();
    }
}
项目:saluki    文件:GrpcEngine.java   
private SslContext buildClientSslContext() {
  try {
    InputStream certs = SslUtil.loadInputStreamCert("server.pem");
    return GrpcSslContexts
        .configure(SslContextBuilder.forClient()//
            .trustManager(certs))//
        .build();
  } catch (SSLException e) {
    throw new RpcFrameworkException(e);
  }
}
项目:saluki    文件:GrpcEngine.java   
private SslContext buildServerSslContext() {
  try {
    InputStream certs = SslUtil.loadInputStreamCert("server.pem");
    InputStream keys = SslUtil.loadInputStreamCert("server_pkcs8.key");
    return GrpcSslContexts.configure(SslContextBuilder.forServer(certs, keys)).build();
  } catch (SSLException e) {
    throw new RpcFrameworkException(e);
  }
}
项目:indeed-grpc-java    文件:SslContextReloader.java   
public SslContextReloader(
        @Nullable final String suffix,
        final ExceptionalSupplier<SslContext> loader
) {
    super(computeNamespace(suffix));

    this.loader = loader;

    load(); // force the load of the data for the first time
}
项目:qonduit    文件:Server.java   
protected SslContext createSSLContext(Configuration config) throws Exception {

        Configuration.Ssl sslCfg = config.getSecurity().getSsl();
        Boolean generate = sslCfg.isUseGeneratedKeypair();
        SslContextBuilder ssl;
        if (generate) {
            LOG.warn("Using generated self signed server certificate");
            Date begin = new Date();
            Date end = new Date(begin.getTime() + 86400000);
            SelfSignedCertificate ssc = new SelfSignedCertificate("localhost", begin, end);
            ssl = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey());
        } else {
            String cert = sslCfg.getCertificateFile();
            String key = sslCfg.getKeyFile();
            String keyPass = sslCfg.getKeyPassword();
            if (null == cert || null == key) {
                throw new IllegalArgumentException("Check your SSL properties, something is wrong.");
            }
            ssl = SslContextBuilder.forServer(new File(cert), new File(key), keyPass);
        }

        ssl.ciphers(sslCfg.getUseCiphers());

        // Can't set to REQUIRE because the CORS pre-flight requests will fail.
        ssl.clientAuth(ClientAuth.OPTIONAL);

        Boolean useOpenSSL = sslCfg.isUseOpenssl();
        if (useOpenSSL) {
            ssl.sslProvider(SslProvider.OPENSSL);
        } else {
            ssl.sslProvider(SslProvider.JDK);
        }
        String trustStore = sslCfg.getTrustStoreFile();
        if (null != trustStore) {
            if (!trustStore.isEmpty()) {
                ssl.trustManager(new File(trustStore));
            }
        }
        return ssl.build();
    }
项目:qonduit    文件:Server.java   
protected ChannelHandler setupHttpChannel(Configuration config, SslContext sslCtx) {

        return new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {

                ch.pipeline().addLast("ssl", new NonSslRedirectHandler(config, sslCtx));
                ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                ch.pipeline().addLast("decoder", new HttpRequestDecoder());
                ch.pipeline().addLast("compressor", new HttpContentCompressor());
                ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
                ch.pipeline().addLast("chunker", new ChunkedWriteHandler());
                final Configuration.Cors corsCfg = config.getHttp().getCors();
                final CorsConfig.Builder ccb;
                if (corsCfg.isAllowAnyOrigin()) {
                    ccb = new CorsConfig.Builder();
                } else {
                    ccb = new CorsConfig.Builder(corsCfg.getAllowedOrigins().stream().toArray(String[]::new));
                }
                if (corsCfg.isAllowNullOrigin()) {
                    ccb.allowNullOrigin();
                }
                if (corsCfg.isAllowCredentials()) {
                    ccb.allowCredentials();
                }
                corsCfg.getAllowedMethods().stream().map(HttpMethod::valueOf).forEach(ccb::allowedRequestMethods);
                corsCfg.getAllowedHeaders().forEach(ccb::allowedRequestHeaders);
                CorsConfig cors = ccb.build();
                LOG.trace("Cors configuration: {}", cors);
                ch.pipeline().addLast("cors", new CorsHandler(cors));
                ch.pipeline().addLast("queryDecoder", new qonduit.netty.http.HttpRequestDecoder(config));
                ch.pipeline().addLast("strict", new StrictTransportHandler(config));
                ch.pipeline().addLast("login", new X509LoginRequestHandler(config));
                ch.pipeline().addLast("doLogin", new BasicAuthLoginRequestHandler(config));
                ch.pipeline().addLast("error", new HttpExceptionHandler());
            }
        };
    }
项目:qonduit    文件:NonSslRedirectHandler.java   
public NonSslRedirectHandler(Configuration conf, SslContext sslContext) {
    super(sslContext);
    String timelyHost = conf.getHttp().getHost();
    int timelyPort = conf.getHttp().getPort();
    String path = conf.getHttp().getRedirectPath();
    redirectAddress = "https://" + timelyHost + ":" + timelyPort + path;
}
项目:qonduit    文件:TestServer.java   
@Override
protected ChannelHandler setupHttpChannel(Configuration config, SslContext sslCtx) {
    return new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", new NonSslRedirectHandler(config, sslCtx));
            ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
            ch.pipeline().addLast("decoder", new HttpRequestDecoder());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
            ch.pipeline().addLast("queryDecoder", new qonduit.netty.http.HttpRequestDecoder(config));
            ch.pipeline().addLast("capture", httpRequests);
        }
    };
}
项目:qonduit    文件:TwoWaySSLFailureIT.java   
protected SSLSocketFactory getSSLSocketFactory() throws Exception {
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    // Use server cert / key on client side
    builder.keyManager(serverCert.key(), (String) null, serverCert.cert());
    builder.sslProvider(SslProvider.JDK);
    builder.trustManager(clientTrustStoreFile); // Trust the server cert
    SslContext ctx = builder.build();
    Assert.assertEquals(JdkSslClientContext.class, ctx.getClass());
    JdkSslContext jdk = (JdkSslContext) ctx;
    SSLContext jdkSslContext = jdk.context();
    return jdkSslContext.getSocketFactory();
}