当前位置: 首页 > 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();}}
}
http://www.lryc.cn/news/192961.html

相关文章:

  • Jetpack:007-Kotlin中的Button
  • opencv图形绘制2
  • “华为杯”研究生数学建模竞赛2019年-【华为杯】A题:无线智能传播模型(附优秀论文及Pyhton代码实现)(续)
  • 爬虫 | 正则、Xpath、BeautifulSoup示例学习
  • nginx的location的优先级和匹配方式
  • 深入了解Spring Boot Actuator
  • 【SQL】NodeJs 连接 MySql 、MySql 常见语句
  • SSH 基础学习使用
  • JavaFX: 使用本地openjfx包
  • 【HCIA】静态路由综合实验
  • Django框架集成Celery异步-【2】:django集成celery,拿来即用,可用操作django的orm等功能
  • 获取本地缓存数据修改后,本地缓存中的值也修改问题
  • 云开发校园宿舍/企业/部门/物业故障报修小程序源码
  • K邻近算法(KNN,K-nearest Neighbors Algorithm)
  • 前端基础一:用Formdata对象来上传图片的原因
  • CSS的布局 Day03
  • nodejs+vue+elementui养老院老年人服务系统er809
  • antd表格宽度超出屏幕,列宽自适应失效
  • 布局--QT Designer
  • 2024第八届杭州国际智慧城市博览会:建筑与智能,智慧与未来
  • Text-to-SQL小白入门(八)RLAIF论文:AI代替人类反馈的强化学习
  • C语言联合体和枚举
  • Ubuntu 上传项目到 GitHub
  • CSS 复杂卡片/导航栏特效运用目录
  • QT: 一种精确定时器类的实现与使用
  • SQLite4Unity3d安卓 在手机上创建sqlite失败解决
  • 跨站请求伪造:揭秘攻击与防御
  • matlab 图像均值滤波
  • P1433 吃奶酪
  • c++string类的赋值问题