小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

netty案例,netty4.1中級拓展篇十三《Netty基于SSL實現(xiàn)信息傳輸過程中雙向加密驗證》

 小傅哥 2021-12-13

前言介紹

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安全模塊:

1io.netty.handler.ssl.NotSslRecordException: not an SSL/TLS record: cea2d0c5b9abd6dabac5a3ba627567737461636bb3e6b6b4d5bb207c20cda8d6aab7fecef1b6cbc1b4bdd3bda8c1a2b3c9b9a6204d6f6e205365702032332031333a35303a3535204353542032303139203132372e302e302e310d0a

測試篡改服務(wù)端時間:

1javax.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

1openssl genrsa -des3 -out server.key 1024
2openssl genrsa -des3 -out client.key 1024

3、根據(jù)key生成csr文件 | -config openssl.cnf 默認(rèn)在cnf文件夾,如果未復(fù)制出來,需要指定路徑“D://..cnf//openssl.cnf”

1openssl req -new -key server.key -out server.csr -config openssl.cnf
2openssl req -new -key client.key -out client.csr -config openssl.cnf

4、根據(jù)ca證書server.csr、client.csr生成x509證書

1openssl x509 -req -days 3650 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt
2openssl x509 -req -days 3650 -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt

5、將key文件進(jìn)行PKCS#8編碼

1openssl pkcs8 -topk8 -in server.key -out pkcs8_server.key -nocrypt
2openssl pkcs8 -topk8 -in client.key -out pkcs8_client.key -nocrypt

6、最終將bin文件夾下,如下文件復(fù)制出來;

1server端:ca.crt、server.crt、pkcs8_server.key
2client端:ca.crt、client.crt、pkcs8_client.key

代碼示例

1itstack-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.java
10    │           ├── server
11    │           │    ├── MyChannelInitializer.java
12    │           │    ├── MyServerHandler.java    
13    │           │    └── NettyServer.java
14    │           └── ssl
15    │               ├── client
16    │               │   ├── ca.crt
17    │               │   ├── client.crt  
18    │               │   └── pkcs8_client.key    
19    │               └── server
20    │                   ├── ca.crt
21    │                   ├── pkcs8_server.key
22    │                   └── server.crt
23    │
24    └── test
25         └── java
26             └── org.itstack.demo.test
27                 └── 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 */

6public 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 */

6public 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 */

6public 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 */
6public 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

    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多