前言介绍 SSL(Secure Sockets Layer 安全套接层),及其继任者传输层安全(Transport Layer Security,TLS)是为网络通信提供安全及数据完整性的一种安全协议。TLS与SSL在传输层对网络连接进行加密。
在实际通信过程中,如果不使用SSL那么信息就是明文传输,从而给非法分子一些可乘之机;
窃听风险[eavesdropping]:第三方可以获知通信内容。
篡改风险[tampering]:第三方可以修改通信内容。
冒充风险[pretending]:第三方可以冒充他人身份参与通信。
SSL/TLS协议就是为了解决这三大风险而设计的;
那么本章节我们通过在netty的channHandler中添加SSL安全模块{sslContext.newHandler(channel.alloc())},来实现加密传输的效果。
测试注释掉客户端SSL安全模块:
1 io.netty.handler.ssl.NotSslRecordException: not an SSL/TLS record: cea2d0c5b9abd6dabac5a3ba627567737461636bb3e6b6b4d5bb207c20cda8d6aab7fecef1b6cbc1b4bdd3bda8c1a2b3c9b9a6204d6f6e205365702032332031333a35303a3535204353542032303139203132372e302e302e310d0a
测试篡改服务端时间:
1 javax.net.ssl.SSLHandshakeException: General SSLEngine problem
开发环境 1、jdk1.8【jdk1.7以下只能部分支持netty】 2、Netty4.1.36.Final【netty3.x 4.x 5每次的变化较大,接口类名也随着变化】 3、OpenSSL-Win64 可以按照自己的需要进行下载;http:///products/Win32OpenSSL.html
生成证书 | 过程较长,耐心完成 微信公众号:bustack虫洞栈 | 生成证书 1、安装OpenSSL
安装完成后D:\Program Files\OpenSSL-Win64\bin目录下,cnf文件复制到bin目录里,否则在操作工程中如果未指定路径,会报错; https:///questions/22906927/openssl-windows-error-in-req/27918971
OpenSSL Windows: error in req 2、生成服务端和客户端私钥 | 命令中需要输入密码测试可以都输入123456
1 openssl genrsa -des3 -out server.key 1024 2 openssl genrsa -des3 -out client.key 1024
3、根据key生成csr文件 | -config openssl.cnf 默认在cnf文件夹,如果未复制出来,需要指定路径“D://..cnf//openssl.cnf”
1 openssl req -new -key server.key -out server.csr -config openssl.cnf2 openssl req -new -key client.key -out client.csr -config openssl.cnf
4、根据ca证书server.csr、client.csr生成x509 证书
1 openssl x509 -req -days 3650 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt2 openssl x509 -req -days 3650 -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt
5、将key文件进行PKCS#8 编码
1 openssl pkcs8 -topk8 -in server.key -out pkcs8_server.key -nocrypt2 openssl pkcs8 -topk8 -in client.key -out pkcs8_client.key -nocrypt
6、最终将bin文件夹下,如下文件复制出来;
1 server端:ca.crt、server.crt、pkcs8_server.key2 client端:ca.crt、client.crt、pkcs8_client.key
代码示例 1 itstack-demo-netty-2 -13 2 └── src 3 ├── main 4 │ └── java 5 │ └── org.itstack.demo.netty 6 │ ├── client 7 │ │ ├── MyChannelInitializer.java 8 │ │ ├── MyClientHandler.java 9 │ │ └── NettyClient.java10 │ ├── server11 │ │ ├── MyChannelInitializer.java12 │ │ ├── MyServerHandler.java 13 │ │ └── NettyServer.java14 │ └── ssl15 │ ├── client16 │ │ ├── ca.crt17 │ │ ├── client.crt 18 │ │ └── pkcs8_client.key 19 │ └── server20 │ ├── ca.crt21 │ ├── pkcs8_server.key22 │ └── server.crt23 │24 └── test25 └── java26 └── org.itstack.demo.test27 └── ApiTest.java
以下重点代码块讲解,完整代码,关注公众号:bugstack虫洞栈 | 回复Netty源码获取
客户端: client/NettyClient.java | 引入SSL认证
1 /** 2 * 虫洞栈:https:// 3 * 公众号:bugstack虫洞栈 {获取学习源码} 4 * Create by fuzhengwei on 2019 5 */ 6 public class NettyClient { 7 8 public static void main (String[] args) throws SSLException { 9 new NettyClient().connect("127.0.0.1" , 7398 );10 }11 12 private void connect (String inetHost, int inetPort) throws SSLException {13 14 //引入SSL安全验证 15 File certChainFile = new File("E:\\itstack\\GIT\\itstack.org\\itstack-demo-netty\\itstack-demo-netty-2-13\\src\\main\\java\\org\\itstack\\demo\\netty\\ssl\\client\\client.crt" );16 File keyFile = new File("E:\\itstack\\GIT\\itstack.org\\itstack-demo-netty\\itstack-demo-netty-2-13\\src\\main\\java\\org\\itstack\\demo\\netty\\ssl\\client\\pkcs8_client.key" );17 File rootFile = new File("E:\\itstack\\GIT\\itstack.org\\itstack-demo-netty\\itstack-demo-netty-2-13\\src\\main\\java\\org\\itstack\\demo\\netty\\ssl\\client\\ca.crt" );18 SslContext sslCtx = SslContextBuilder.forClient().keyManager(certChainFile, keyFile).trustManager(rootFile).build();19 20 //配置客户端NIO线程组 21 EventLoopGroup workerGroup = new NioEventLoopGroup();22 try {23 Bootstrap b = new Bootstrap();24 b.group(workerGroup);25 b.channel(NioSocketChannel.class);26 b.option(ChannelOption.AUTO_READ, true );27 b.handler(new MyChannelInitializer(sslCtx));28 ChannelFuture f = b.connect(inetHost, inetPort).sync();29 System.out.println("itstack-demo-netty client start done. {关注公众号:bugstack虫洞栈 | 获取专题源码}" );30 f.channel().closeFuture().sync();31 } catch (InterruptedException e) {32 e.printStackTrace();33 } finally {34 workerGroup.shutdownGracefully();35 }36 }37 38 }
client/NettyClient.java | 添加SSL认证模块,测试过程中可以尝试注释掉
1 /** 2 * 虫洞栈:https:// 3 * 公众号:bugstack虫洞栈 {获取学习源码} 4 * Create by fuzhengwei on 2019 5 */ 6 public class MyChannelInitializer extends ChannelInitializer <SocketChannel > { 7 8 private SslContext sslContext; 9 10 public MyChannelInitializer (SslContext sslContext) {11 this .sslContext = sslContext;12 }13 14 @Override 15 protected void initChannel (SocketChannel channel) throws Exception {16 // 添加SSL安全验证 17 channel.pipeline().addLast(sslContext.newHandler(channel.alloc()));18 // 基于换行符号 19 channel.pipeline().addLast(new LineBasedFrameDecoder(1024 ));20 // 解码转String,注意调整自己的编码格式GBK、UTF-8 21 channel.pipeline().addLast(new StringDecoder(Charset.forName("GBK" )));22 // 解码转String,注意调整自己的编码格式GBK、UTF-8 23 channel.pipeline().addLast(new StringEncoder(Charset.forName("GBK" )));24 // 在管道中添加我们自己的接收数据实现方法 25 channel.pipeline().addLast(new MyClientHandler());26 }27 28 }
服务端: server/NettyServer.java | 引入SSL安全验证
1 /** 2 * 虫洞栈:https:// 3 * 公众号:bugstack虫洞栈 {获取学习源码} 4 * Create by fuzhengwei on 2019 5 */ 6 public class NettyServer { 7 8 public static void main (String[] args) throws SSLException { 9 new NettyServer().bing(7398 );10 }11 12 private void bing (int port) throws SSLException {13 14 //引入SSL安全验证 15 File certChainFile = new File("E:\\itstack\\GIT\\itstack.org\\itstack-demo-netty\\itstack-demo-netty-2-13\\src\\main\\java\\org\\itstack\\demo\\netty\\ssl\\server\\server.crt" );16 File keyFile = new File("E:\\itstack\\GIT\\itstack.org\\itstack-demo-netty\\itstack-demo-netty-2-13\\src\\main\\java\\org\\itstack\\demo\\netty\\ssl\\server\\pkcs8_server.key" );17 File rootFile = new File("E:\\itstack\\GIT\\itstack.org\\itstack-demo-netty\\itstack-demo-netty-2-13\\src\\main\\java\\org\\itstack\\demo\\netty\\ssl\\server\\ca.crt" );18 SslContext sslCtx = SslContextBuilder.forServer(certChainFile, keyFile).trustManager(rootFile).clientAuth(ClientAuth.REQUIRE).build();19 20 //配置服务端NIO线程组 21 EventLoopGroup parentGroup = new NioEventLoopGroup(1 ); //NioEventLoopGroup extends MultithreadEventLoopGroup Math.max(1, SystemPropertyUtil.getInt("io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2)); 22 EventLoopGroup childGroup = new NioEventLoopGroup();23 try {24 ServerBootstrap b = new ServerBootstrap();25 b.group(parentGroup, childGroup)26 .channel(NioServerSocketChannel.class) //非阻塞模式 27 .option(ChannelOption.SO_BACKLOG, 128 )28 .childHandler(new MyChannelInitializer(sslCtx));29 ChannelFuture f = b.bind(port).sync();30 System.out.println("itstack-demo-netty server start done. {关注公众号:bugstack虫洞栈 | 获取专题源码}" );31 f.channel().closeFuture().sync();32 } catch (InterruptedException e) {33 e.printStackTrace();34 } finally {35 childGroup.shutdownGracefully();36 parentGroup.shutdownGracefully();37 }38 39 }40 41 }
server/NettyServer.java | 添加SSL认证模块
1 ** 2 * 虫洞栈:https:// 3 * 公众号:bugstack虫洞栈 {获取学习源码} 4 * Create by fuzhengwei on 2019 5 */ 6 public class MyChannelInitializer extends ChannelInitializer <SocketChannel > { 7 8 private SslContext sslContext; 9 10 public MyChannelInitializer (SslContext sslContext) {11 this .sslContext = sslContext;12 }13 14 @Override 15 protected void initChannel (SocketChannel channel) {16 // 添加SSL安装验证 17 channel.pipeline().addLast(sslContext.newHandler(channel.alloc()));18 // 基于换行符号 19 channel.pipeline().addLast(new LineBasedFrameDecoder(1024 ));20 // 解码转String,注意调整自己的编码格式GBK、UTF-8 21 channel.pipeline().addLast(new StringDecoder(Charset.forName("GBK" )));22 // 解码转String,注意调整自己的编码格式GBK、UTF-8 23 channel.pipeline().addLast(new StringEncoder(Charset.forName("GBK" )));24 // 在管道中添加我们自己的接收数据实现方法 25 channel.pipeline().addLast(new MyServerHandler());26 }27 28 }
测试结果 启动服务端NettyServer