当前位置: 首页 > news >正文

Netty使用SslHandler实现加密通信-单向认证篇

引入依赖

<dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.100.Final</version>
</dependency>

生成keystore.jks文件

keytool -genkeypair -alias your_alias -keyalg RSA -keystore keystore.jks -keysize 2048

Server端

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.CharsetUtil;import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;public class NettySslServer {private static final int PORT = 8888;public static void main(String[] args) throws Exception {// 加载SSL证书String keyStorePath = "/home/admin/keystore.jks";String keyStorePassword = "happya";// 创建SSL上下文SSLContext sslContext = SSLContext.getInstance("TLS");KeyStore keyStore = KeyStore.getInstance("JKS");keyStore.load(new FileInputStream(keyStorePath), keyStorePassword.toCharArray());KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());sslContext.init(keyManagerFactory.getKeyManagers(), null, null);// 创建EventLoopGroupEventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try {// 创建服务器BootstrapServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();// 在ChannelPipeline中添加SSL处理器SSLEngine sslEngine = sslContext.createSSLEngine();sslEngine.setUseClientMode(false);pipeline.addLast(new SslHandler(sslEngine));// 添加加密通信处理器pipeline.addLast(new SecureChatServerHandler());}}).childOption(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);// 启动服务器System.out.println("======Begin to start ssl server======");ChannelFuture future = serverBootstrap.bind(PORT).sync();System.out.println("======Ssl server started======");future.channel().closeFuture().sync();} finally {workerGroup.shutdownGracefully();bossGroup.shutdownGracefully();}}public static class SecureChatServerHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {// 当连接建立时,发送欢迎消息System.out.println("Server channel active : " + ctx.channel().toString());ctx.channel().writeAndFlush(Unpooled.wrappedBuffer("Welcome to the secure chat server!\n".getBytes(StandardCharsets.UTF_8)));ctx.channel().writeAndFlush(Unpooled.wrappedBuffer("Your connection is protected by SSL.\n".getBytes(StandardCharsets.UTF_8)));}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {ByteBuf byteBuf= (ByteBuf) msg;System.out.println("Server received message: " + byteBuf.toString(CharsetUtil.UTF_8));super.channelRead(ctx, msg);}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {// 处理异常cause.printStackTrace();ctx.close();}}
}

Client端

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.CharsetUtil;import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;public class NettySslClient {private static final String HOST = "localhost";private static final int PORT = 8888;public static void main(String[] args) throws Exception {// 加载SSL证书String trustStorePath = "/home/admin/keystore.jks";String trustStorePassword = "happya";// 创建SSL上下文SSLContext sslContext = SSLContext.getInstance("TLS");KeyStore trustStore = KeyStore.getInstance("JKS");trustStore.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray());TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());trustManagerFactory.init(trustStore);sslContext.init(null, trustManagerFactory.getTrustManagers(), null);// 创建EventLoopGroupEventLoopGroup group = new NioEventLoopGroup();try {// 创建客户端BootstrapBootstrap bootstrap = new Bootstrap();bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();// 在ChannelPipeline中添加SSL处理器SSLEngine sslEngine = sslContext.createSSLEngine();sslEngine.setUseClientMode(true);pipeline.addLast(new SslHandler(sslEngine));// 添加加密通信处理器pipeline.addLast(new SecureChatClientHandler());}});// 连接服务器System.out.println("======Begin to start ssl client======");ChannelFuture future = bootstrap.connect(HOST, PORT).sync();System.out.println("======Ssl client started======");future.channel().closeFuture().sync();} finally {group.shutdownGracefully();}}public static class SecureChatClientHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {// 连接建立时,发送一条消息给服务器System.out.println("Client channel active : " + ctx.channel().toString());ctx.channel().writeAndFlush(Unpooled.wrappedBuffer("Hello from client!\n".getBytes(StandardCharsets.UTF_8)));}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {ByteBuf byteBuf = (ByteBuf) msg;System.out.println("Client received message: \n" + byteBuf.toString(CharsetUtil.UTF_8));super.channelRead(ctx, msg);}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {// 处理异常cause.printStackTrace();ctx.close();}}
}

相关文章:

Netty使用SslHandler实现加密通信-单向认证篇

引入依赖 <dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.100.Final</version> </dependency>生成keystore.jks文件 keytool -genkeypair -alias your_alias -keyalg RSA -keysto…...

Jetpack:007-Kotlin中的Button

文章目录 1. 概念介绍2. 使用方法2.1 Button2.2 IconButton2.3 ElevatedButton2.4 OutlinedButton2.5 TextButton2.6 FloatingActionButton 3. 示例代码4. 内容总结 我们在上一章回中介绍了Jetpack中输入框相关的内容&#xff0c;本章回中将要介绍 Button。闲话休提&#xff0…...

opencv图形绘制2

目录 制作宣传语&#xff08;中文&#xff09; 制作宣传语&#xff08;英文&#xff09; 绘制标记 鼠标交互绘制十字线 鼠标交互绘制图形 鼠标交互制作几何画板 滚动条控制 鼠标事件练习 制作宣传语&#xff08;中文&#xff09; import cv2 import numpy as np from …...

“华为杯”研究生数学建模竞赛2019年-【华为杯】A题:无线智能传播模型(附优秀论文及Pyhton代码实现)(续)

目录 六、问题三的分析与建模 6.1 问题三的分析 6.2 问题三的建模 6.2.1 模型介绍...

爬虫 | 正则、Xpath、BeautifulSoup示例学习

文章目录 &#x1f4da;import requests&#x1f4da;import re&#x1f4da;from lxml import etree&#x1f4da;from bs4 import BeautifulSoup&#x1f4da;小结 契机是课程项目需要爬取一份数据&#xff0c;于是在CSDN搜了搜相关的教程。在博主【朦胧的雨梦】主页学到很多…...

nginx的location的优先级和匹配方式

nginx的location的优先级和匹配方式 在http模块中有server&#xff0c;server模块中有location&#xff0c;location匹配的是uri 在一个server中&#xff0c;会有多个location&#xff0c;如何来确定匹配哪个location niginx的正则表达式 ^ 字符串的起始位置 $ 字符串的…...

深入了解Spring Boot Actuator

文章目录 引言什么是ActuatorActuator的底层技术和原理端点自动配置端点请求处理端点数据提供端点数据暴露 如何使用Actuator添加依赖访问端点自定义端点 实例演示结论 引言 Spring Boot Actuator是一个非常强大且广泛使用的模块&#xff0c;它为Spring Boot应用程序提供了一套…...

【SQL】NodeJs 连接 MySql 、MySql 常见语句

1.安装 mysql npm install mysql 2.引入MySql import mysql from mysql 3.连接MySql const connection mysql.createConnection({host: yourServerip,user: yourUsername,password: yourPassword,database: yourDatabase })connection.connect(err > {if (err) {console…...

SSH 基础学习使用

什么是SSH 1.SSH SSH&#xff08;Secure Shell&#xff09; 是较可靠&#xff0c;专为远程登录会话和其他网络服务提供安全性的协议&#xff0c;利用 SSH 协议可以有效防止远程管理过程中的信息泄露问题。 实际应用中&#xff0c;主要用于保证远程登录和远程通信的安全&#…...

JavaFX: 使用本地openjfx包

JavaFX: 使用本地openjfx包 1、注释配置2、下载openjfx包3、导入openjfx的jar包 1、注释配置 build.gradle配置注释&#xff1a; 2、下载openjfx包 下载javaFx地址&#xff1a;https://gluonhq.com/products/javafx/ 3、导入openjfx的jar包...

【HCIA】静态路由综合实验

实验要求&#xff1a; 1、R6为ISP&#xff0c;接口IP地址均为公有地址&#xff0c;该设备只能配置IP地址之后不能再对其进行任何配置 2、R1-R5为局域网&#xff0c;私有IP地址192.168.1.0/24&#xff0c;请合理分配 3、R1、R2、R4&#xff0c;各有两个环回IP地址;R5,R6各有一…...

Django框架集成Celery异步-【2】:django集成celery,拿来即用,可用操作django的orm等功能

一、项目结构和依赖 study_celery | --user |-- models.py |--views.py |--urls.py |--celery_task |--__init__.py |--async_task.py |-- celery.py | --check_task.py | --config.py | --scheduler_task.py | --study_celery | --settings.py | --manage.py 依赖&#xff1a…...

获取本地缓存数据修改后,本地缓存中的值也修改问题

获取本地缓存数据修改后&#xff0c;本地缓存中的值也修改问题 JAVA缓存&#xff0c;获取数据后修改&#xff0c;缓存中的数值也会修改&#xff0c;解决方法是创建新的对象再修改值比如使用BeanUtils.copyProperties()方法。如果值是List&#xff0c;可以使用两种方法解决循环…...

云开发校园宿舍/企业/部门/物业故障报修小程序源码

微信小程序云开发校园宿舍企业单位部门物业报修小程序源码&#xff0c;这是一款云开发校园宿舍报修助手工具系统微信小程序源码&#xff0c;适用于学校机房、公司设备、物业管理以及其他团队后勤部&#xff0c;系统为简单云开发&#xff0c;不需要服务器域名即可部署&#xff0…...

K邻近算法(KNN,K-nearest Neighbors Algorithm)

文章目录 前言应用场景欧几里得距离&#xff08;欧氏距离&#xff09;两类、单一属性&#xff08;1D&#xff09;两类、两种属性&#xff08;2D&#xff09;两类、两种以上属性&#xff08;>3D&#xff09; Examples in R再来一个补充一下什么是变量 什么是变量&#xff1f;…...

前端基础一:用Formdata对象来上传图片的原因

最近有人问&#xff1a;你是否能用json来传图片&#xff0c;其实应该这么理解就对了。 一、上传的数据体格式Content-Type 1.application/x-www-form-urlencoded 2.application/json 3.multipart/form-data 以上三种类型旨在告诉服务器需要接收的数据类型同事要…...

CSS的布局 Day03

一、显示模式&#xff1a; 网页中HTML的标签多种多样&#xff0c;具有不同的特征。而我们学习盒子模型、使用定位和弹性布局把内容分块&#xff0c;利用CSS布局使内容脱离文本流&#xff0c;使用定位或弹性布局让每块内容摆放在想摆放的位置&#xff0c;让网站页面布局更合理、…...

nodejs+vue+elementui养老院老年人服务系统er809

“养老智慧服务平台”是运用nodejs语言和vue框架&#xff0c;以MySQL数据库为基础而发出来的。为保证我国经济的持续性发展&#xff0c;必须要让互联网信息时代在我国日益壮大&#xff0c;蓬勃发展。伴随着信息社会的飞速发展&#xff0c;养老智慧服务平台所面临的问题也一个接…...

antd表格宽度超出屏幕,列宽自适应失效

最近遇到个诡异的问题&#xff0c;Table用的好好的&#xff0c;可就有一个页面的表格显示不全&#xff0c;超出浏览器宽&#xff0c;设定表格宽度也没用。 仔细分析了用户上传展示的数据后发现&#xff0c;不自动换行的超宽列都是url地址&#xff0c;一开始还以为是地址里有不…...

布局--QT Designer

一、在我们使用Qt做界面设计时&#xff0c;为了界面的整洁美观&#xff0c;往往需要对界面中的所有控件做一个有序的排列&#xff0c;以及设置各个控件之间的间距等等&#xff0c;为此Qt为界面设计提供了基本布局功能&#xff0c;使用基本布局可以使组件有规则地分布。 1.1 基…...

Spark 之 入门讲解详细版(1)

1、简介 1.1 Spark简介 Spark是加州大学伯克利分校AMP实验室&#xff08;Algorithms, Machines, and People Lab&#xff09;开发通用内存并行计算框架。Spark在2013年6月进入Apache成为孵化项目&#xff0c;8个月后成为Apache顶级项目&#xff0c;速度之快足见过人之处&…...

Java 语言特性(面试系列1)

一、面向对象编程 1. 封装&#xff08;Encapsulation&#xff09; 定义&#xff1a;将数据&#xff08;属性&#xff09;和操作数据的方法绑定在一起&#xff0c;通过访问控制符&#xff08;private、protected、public&#xff09;隐藏内部实现细节。示例&#xff1a; public …...

Oracle查询表空间大小

1 查询数据库中所有的表空间以及表空间所占空间的大小 SELECTtablespace_name,sum( bytes ) / 1024 / 1024 FROMdba_data_files GROUP BYtablespace_name; 2 Oracle查询表空间大小及每个表所占空间的大小 SELECTtablespace_name,file_id,file_name,round( bytes / ( 1024 …...

Golang dig框架与GraphQL的完美结合

将 Go 的 Dig 依赖注入框架与 GraphQL 结合使用&#xff0c;可以显著提升应用程序的可维护性、可测试性以及灵活性。 Dig 是一个强大的依赖注入容器&#xff0c;能够帮助开发者更好地管理复杂的依赖关系&#xff0c;而 GraphQL 则是一种用于 API 的查询语言&#xff0c;能够提…...

Java + Spring Boot + Mybatis 实现批量插入

在 Java 中使用 Spring Boot 和 MyBatis 实现批量插入可以通过以下步骤完成。这里提供两种常用方法&#xff1a;使用 MyBatis 的 <foreach> 标签和批处理模式&#xff08;ExecutorType.BATCH&#xff09;。 方法一&#xff1a;使用 XML 的 <foreach> 标签&#xff…...

20个超级好用的 CSS 动画库

分享 20 个最佳 CSS 动画库。 它们中的大多数将生成纯 CSS 代码&#xff0c;而不需要任何外部库。 1.Animate.css 一个开箱即用型的跨浏览器动画库&#xff0c;可供你在项目中使用。 2.Magic Animations CSS3 一组简单的动画&#xff0c;可以包含在你的网页或应用项目中。 3.An…...

uniapp手机号一键登录保姆级教程(包含前端和后端)

目录 前置条件创建uniapp项目并关联uniClound云空间开启一键登录模块并开通一键登录服务编写云函数并上传部署获取手机号流程(第一种) 前端直接调用云函数获取手机号&#xff08;第三种&#xff09;后台调用云函数获取手机号 错误码常见问题 前置条件 手机安装有sim卡手机开启…...

Golang——6、指针和结构体

指针和结构体 1、指针1.1、指针地址和指针类型1.2、指针取值1.3、new和make 2、结构体2.1、type关键字的使用2.2、结构体的定义和初始化2.3、结构体方法和接收者2.4、给任意类型添加方法2.5、结构体的匿名字段2.6、嵌套结构体2.7、嵌套匿名结构体2.8、结构体的继承 3、结构体与…...

基于PHP的连锁酒店管理系统

有需要请加文章底部Q哦 可远程调试 基于PHP的连锁酒店管理系统 一 介绍 连锁酒店管理系统基于原生PHP开发&#xff0c;数据库mysql&#xff0c;前端bootstrap。系统角色分为用户和管理员。 技术栈 phpmysqlbootstrapphpstudyvscode 二 功能 用户 1 注册/登录/注销 2 个人中…...

根目录0xa0属性对应的Ntfs!_SCB中的FileObject是什么时候被建立的----NTFS源代码分析--重要

根目录0xa0属性对应的Ntfs!_SCB中的FileObject是什么时候被建立的 第一部分&#xff1a; 0: kd> g Breakpoint 9 hit Ntfs!ReadIndexBuffer: f7173886 55 push ebp 0: kd> kc # 00 Ntfs!ReadIndexBuffer 01 Ntfs!FindFirstIndexEntry 02 Ntfs!NtfsUpda…...