【Netty源码解读和权威指南】第38篇:Netty SSL TLS安全传输——HTTPS背后的Netty实现
上一篇【第37篇】Netty流量整形——优雅控制客户端发送速率下一篇【第39篇】Netty内存泄漏检测机制源码解析——守护ByteBuf的生死账本一、TLS握手流程客户端 服务端 |------ClientHello-----------| (支持的加密套件) |-----ServerHello------------| (选定加密套件证书) |-----Certificate-----------| (服务端证书) |-----ServerHelloDone-------| (握手完成) |------ClientKeyExchange-----| (加密的预主密钥) |------ChangeCipherSpec------| (切换加密模式) |------Finished--------------| |-----ChangeCipherSpec-------| |-----Finished---------------| | | |加密通信开始|二、SslContext配置// 服务端SSL配置SelfSignedCertificatecertnewSelfSignedCertificate();SslContextsslCtxSslContextBuilder.forServer(cert.certificate(),cert.privateKey()).sslProvider(SslProvider.OPENSSL)// 优先使用OpenSSL.build();// 客户端SSL配置SslContextclientCtxSslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)// 仅测试用.build();三、SslHandler集成// 服务端Pipelinepipeline.addLast(sslCtx.newHandler(ch.alloc()));// SSL加解密pipeline.addLast(newHttpServerCodec());// HTTP编解码pipeline.addLast(newHttpServerHandler());// 业务逻辑// 客户端Pipelinepipeline.addLast(clientCtx.newHandler(ch.alloc(),host,port));pipeline.addLast(newHttpClientCodec());pipeline.addLast(newHttpClientHandler());四、OpenSSL vs JDK SSL对比JDK SSLOpenSSL性能基准快2-3倍内存堆内堆外(更少GC)依赖无需安装OpenSSL支持全平台Linux最佳启用OpenSSL// pom.xmldependencygroupIdio.netty/groupIdartifactIdnetty-tcnative-boringssl-static/artifactId/dependency// 代码配置.sslProvider(SslProvider.OPENSSL)五、完整HTTPS服务器publicclassHttpsServer{publicstaticvoidmain(String[]args)throwsException{SelfSignedCertificatecertnewSelfSignedCertificate();SslContextsslCtxSslContextBuilder.forServer(cert.certificate(),cert.privateKey()).build();EventLoopGroupbossnewNioEventLoopGroup(1);EventLoopGroupworkernewNioEventLoopGroup();try{newServerBootstrap().group(boss,worker).channel(NioServerSocketChannel.class).childHandler(newChannelInitializerChannel(){protectedvoidinitChannel(Channelch){ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()));ch.pipeline().addLast(newHttpServerCodec());ch.pipeline().addLast(newHttpServerExpectContinueHandler());ch.pipeline().addLast(newSimpleChannelInboundHandlerHttpRequest(){protectedvoidchannelRead0(ChannelHandlerContextctx,HttpRequestreq){StringbodyHello HTTPS!;FullHttpResponserespnewDefaultFullHttpResponse(HTTP_1_1,OK,ctx.alloc().buffer().writeBytes(body.getBytes()));resp.headers().set(CONTENT_LENGTH,body.length());resp.headers().set(CONTENT_TYPE,text/plain);ctx.writeAndFlush(resp);}});}}).bind(8443).sync().channel().closeFuture().sync();}finally{boss.shutdownGracefully();worker.shutdownGracefully();}}}六、总结步骤配置证书SelfSignedCertificate(测试) / CA证书(生产)SslContextSslContextBuilder配置Provider和证书集成SslHandler添加到Pipeline首位性能建议生产环境使用OpenSSL Provider上一篇【第37篇】Netty流量整形——优雅控制客户端发送速率下一篇【第39篇】Netty内存泄漏检测机制源码解析——守护ByteBuf的生死账本