Netty使用技巧-使用Openssl加密传输

JDK原生使用数字证书和PKCS#8格式的私钥完成SSL引擎的初始化。

 

#使用JDK的SslEngine引擎初始化SslContent

File certChainFile=new File("/home/certs/nginx.crt");
File keyFile=new File("/home/certs/pkcs8_rsa_private_key.pem");
SslContext sslCtx = SslContextBuilder.forServer(certChainFile, keyFile).clientAuth(ClientAuth.NONE).sslProvider(SslProvider.JDK).build();

 

 

另外还可以使用OpenSSL模块来初始化SslContent,据说性能上比JDK的好一些。

		
		    io.netty
		    netty-tcnative-boringssl-static
		    2.0.26.Final
		
		File certChainFile=new File("/home/certs/nginx.crt");
        File keyFile=new File("/home/certs/pkcs8_rsa_private_key.pem");
        SslContext sslCtx = SslContextBuilder.forServer(certChainFile, keyFile).clientAuth(ClientAuth.NONE)
        		.sslProvider(SslProvider.OPENSSL).build();

在netty-tcnative-boringssl-static-jar包内部包含了操作系统的类库,可以使用jni调用。

Netty使用技巧-使用Openssl加密传输_第1张图片

 

把SSLhander放入pipeline的第一个位置,这样出入的字节流都会通过它进行加密。

		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler())
					.childHandler(new ChannelInitializer() {
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							System.out.println("initChannel:" + ch.localAddress());
							ch.pipeline().addLast("ssl", sslCtx.newHandler(ByteBufAllocator.DEFAULT));
							//ch.pipeline().addLast("lengthDecoder", new LengthFieldBasedFrameDecoder(2000, 0, 2, 0, 2));
							//ch.pipeline().addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
							ch.pipeline().addLast("DiscardMsg", new DiscardMsg());
							ch.pipeline().addLast(new HeartBeatServerHandler());
						}
					});
			ChannelFuture f = b.bind(port).sync();
			f.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
		}

 

你可能感兴趣的:(Netty)