前言介紹 SSL(Secure Sockets Layer 安全套接層),及其繼任者傳輸層安全(Transport Layer Security,TLS)是為網(wǎng)絡(luò)通信提供安全及數(shù)據(jù)完整性的一種安全協(xié)議。TLS與SSL在傳輸層對網(wǎng)絡(luò)連接進(jìn)行加密。
在實際通信過程中,如果不使用SSL那么信息就是明文傳輸,從而給非法分子一些可乘之機;
竊聽風(fēng)險[eavesdropping]:第三方可以獲知通信內(nèi)容。
篡改風(fēng)險[tampering]:第三方可以修改通信內(nèi)容。
冒充風(fēng)險[pretending]:第三方可以冒充他人身份參與通信。
SSL/TLS協(xié)議就是為了解決這三大風(fēng)險而設(shè)計的;
保密:在握手協(xié)議中定義了會話密鑰后,所有的消息都被加密。
鑒別:可選的客戶端認(rèn)證,和強制的服務(wù)器端認(rèn)證。
完整性:傳送的消息包括消息完整性檢查(使用MAC)。
那么本章節(jié)我們通過在netty的channHandler中添加SSL安全模塊{sslContext.newHandler(channel.alloc())},來實現(xiàn)加密傳輸?shù)男Ч?/p>
測試注釋掉客戶端SSL安全模塊:
1 io.netty.handler.ssl.NotSslRecordException: not an SSL/TLS record: cea2d0c5b9abd6dabac5a3ba627567737461636bb3e6b6b4d5bb207c20cda8d6aab7fecef1b6cbc1b4bdd3bda8c1a2b3c9b9a6204d6f6e205365702032332031333a35303a3535204353542032303139203132372e302e302e310d0a測試篡改服務(wù)端時間:
1 javax.net.ssl.SSLHandshakeException: General SSLEngine problem開發(fā)環(huán)境 1、jdk1.8【jdk1.7以下只能部分支持netty】 2、Netty4.1.36.Final【netty3.x 4.x 5每次的變化較大,接口類名也隨著變化】 3、OpenSSL-Win64 可以按照自己的需要進(jìn)行下載;http:///products/Win32OpenSSL.html
生成證書 | 過程較長,耐心完成 微信公眾號:bustack蟲洞棧 | 生成證書 1、安裝OpenSSL
安裝完成后D:\Program Files\OpenSSL-Win64\bin目錄下,cnf文件復(fù)制到bin目錄里,否則在操作工程中如果未指定路徑,會報錯; https:///questions/22906927/openssl-windows-error-in-req/27918971
OpenSSL Windows: error in req 2、生成服務(wù)端和客戶端私鑰 | 命令中需要輸入密碼測試可以都輸入123456
1 openssl genrsa -des3 -out server.key 1024 2 openssl genrsa -des3 -out client.key 1024 3、根據(jù)key生成csr文件 | -config openssl.cnf 默認(rèn)在cnf文件夾,如果未復(fù)制出來,需要指定路徑“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.cnf4、根據(jù)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.crt5、將key文件進(jìn)行PKCS#8 編碼
1 openssl pkcs8 -topk8 -in server.key -out pkcs8_server.key -nocrypt2 openssl pkcs8 -topk8 -in client.key -out pkcs8_client.key -nocrypt6、最終將bin文件夾下,如下文件復(fù)制出來;
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以下重點代碼塊講解,完整代碼,關(guān)注公眾號:bugstack蟲洞棧 | 回復(fù)Netty源碼獲取
客戶端: client/NettyClient.java | 引入SSL認(rèn)證
1 /** 2 * 蟲洞棧:https:// 3 * 公眾號:bugstack蟲洞棧 {獲取學(xué)習(xí)源碼} 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. {關(guān)注公眾號: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認(rèn)證模塊,測試過程中可以嘗試注釋掉
1 /** 2 * 蟲洞棧:https:// 3 * 公眾號:bugstack蟲洞棧 {獲取學(xué)習(xí)源碼} 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 // 解碼轉(zhuǎn)String,注意調(diào)整自己的編碼格式GBK、UTF-8 21 channel.pipeline().addLast(new StringDecoder(Charset.forName("GBK" )));22 // 解碼轉(zhuǎn)String,注意調(diào)整自己的編碼格式GBK、UTF-8 23 channel.pipeline().addLast(new StringEncoder(Charset.forName("GBK" )));24 // 在管道中添加我們自己的接收數(shù)據(jù)實現(xiàn)方法 25 channel.pipeline().addLast(new MyClientHandler());26 }27 28 }服務(wù)端: server/NettyServer.java | 引入SSL安全驗證
1 /** 2 * 蟲洞棧:https:// 3 * 公眾號:bugstack蟲洞棧 {獲取學(xué)習(xí)源碼} 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 //配置服務(wù)端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. {關(guān)注公眾號: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認(rèn)證模塊
1 ** 2 * 蟲洞棧:https:// 3 * 公眾號:bugstack蟲洞棧 {獲取學(xué)習(xí)源碼} 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 // 解碼轉(zhuǎn)String,注意調(diào)整自己的編碼格式GBK、UTF-8 21 channel.pipeline().addLast(new StringDecoder(Charset.forName("GBK" )));22 // 解碼轉(zhuǎn)String,注意調(diào)整自己的編碼格式GBK、UTF-8 23 channel.pipeline().addLast(new StringEncoder(Charset.forName("GBK" )));24 // 在管道中添加我們自己的接收數(shù)據(jù)實現(xiàn)方法 25 channel.pipeline().addLast(new MyServerHandler());26 }27 28 }測試結(jié)果 啟動服務(wù)端NettyServer