资讯专栏INFORMATION COLUMN

netty ssl 服务器

rickchen / 321人阅读

摘要:一证书本文只介绍版,其他系统只供参考生成证书下载并安装未编译编译好在目录下打开命令行,输入在本目录得到和文件生成服务端和客户端私钥命令行输入密码自己设定,好几个密码,别弄乱了就好,分不清的话都设成一样的根据生成文件

一、证书 (本文只介绍windows版,其他系统只供参考) 1.生成ca证书

下载 openssl 并安装 未编译 编译好

openssl/bin目录下打开命令行,输入

openssl req -new -x509 -keyout ca.key -out ca.crt -config openssl.cnf

在本目录得到 ca.key 和 ca.crt 文件

2.生成服务端和客户端私钥

命令行输入

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

密码自己设定,好几个密码,别弄乱了就好,分不清的话都设成一样的

3.根据 key 生成 csr 文件
openssl req -new -key server.key -out server.csr -config openssl.cnf
openssl req -new -key client.key -out client.csr -config openssl.cnf
4.根据 ca 证书 server.csr 和 client.csr 生成 x509 证书
openssl x509 -req -days 3650 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt
openssl x509 -req -days 3650 -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt
5.将 key 文件进行 PKCS#8 编码
openssl pkcs8 -topk8 -in server.key -out pkcs8_server.key -nocrypt
openssl pkcs8 -topk8 -in client.key -out pkcs8_client.key -nocrypt

最后得到有用的文件分别为
服务器端: ca.crt、server.crt、pkcs8_server.key
客户端端: ca.crt、client.crt、pkcs8_client.key

二、服务器端代码 Main.java
public class Main {
    private static final int m_port = 23333;

    public void run() throws Exception {
        File certChainFile = new File(".sslserver.crt");
        File keyFile = new File(".sslpkcs8_server.key");
        File rootFile = new File(".sslca.crt");
        SslContext sslCtx = SslContextBuilder.forServer(certChainFile, keyFile).trustManager(rootFile).clientAuth(ClientAuth.REQUIRE).build();
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new Initializer(sslCtx));
            ChannelFuture f = b.bind(m_port).sync();
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
    public static void main(String[] args) throws Exception {
        new Main().run();
    }
}
Initializer.java
public class Initializer extends ChannelInitializer {
    private final SslContext sslCtx;
    public Initializer(SslContext sslCtx) {
        this.sslCtx = sslCtx;
    }
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new StringDecoder());
        pipeline.addLast(new StringEncoder());
        pipeline.addLast(new Handler());
    }
}
Handler.java
public class Handler extends SimpleChannelInboundHandler {

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        ctx.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 加入
");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        Channel incoming = ctx.channel();
        System.out.println("收到消息" + s)
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        System.out.println(incoming.remoteAddress() + "在线");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        ctx.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 离开
");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        System.out.println(incoming.remoteAddress() + "掉线");
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel incoming = ctx.channel();
        System.out.println(incoming.remoteAddress() + "异常");
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }
三、客户端代码 Main.java
public class Main {
    private static String m_host = "127.0.0.1";
    private static int m_prot = 23333;

    public static void main(String[] args) throws Exception {
        new Main().run();
    }

    public void run() throws Exception {
        File certChainFile = new File(".sslclient.crt");
        File keyFile = new File(".sslpkcs8_client.key");
        File rootFile = new File(".sslca.crt"); 
        final SslContext sslCtx = SslContextBuilder.forClient().keyManager(certChainFile, keyFile).trustManager(rootFile).build();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class).handler(new Initializer(sslCtx));
            Channel ch = b.connect(m_host, m_prot).sync().channel();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                ch.writeAndFlush(in.readLine() + "
");
            }
        } finally {
            group.shutdownGracefully();
        }
    }
}
Initializer.java
public class Initializer extends ChannelInitializer{
    private final SslContext sslCtx;
    public Initializer(SslContext sslCtx) {
        this.sslCtx = sslCtx;
    }
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new StringDecoder());
        pipeline.addLast(new StringEncoder());
        pipeline.addLast(new Handler());
    }
}
Handler.java
public class Handler extends SimpleChannelInboundHandler{
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println("收到:" + s);
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/67288.html

相关文章

  • 一个简单的Netty-EchoDemo

    摘要:它甚至使用不安全的伪随机生成器在内部更快地生成项目源码一个简单的应答通讯的实例判断是否加密监听本地服务监听端口发送消息的大小,用于公共抽象类,安全套接字协议实现充当工厂和。 本博客 猫叔的博客,转载请申明出处阅读本文约 4分钟 适读人群:Java-Netty 初级 Echo简易通讯案例 版本:netty 4.1.*申明:本文旨在重新分享讨论Netty官方相关案例,添加部分个人理解与要...

    I_Am 评论0 收藏0
  • Netty3文档翻译(二)

    摘要:丰富的缓存数据结构使用它自己的缓存来表示字节序列而不是的。针对有一个定义良好的事件模型。有一些协议是多层的建立在其他低级协议基础上。此外,甚至不是完全线程安全的。协议由标准化为。协议缓存整合是一个高效二进制协议的快速实现。 Chapter 2、结构概览 这一节我们将确认Netty提供的核心功能是什么,以及它们怎么构成一个完整的网络应用开发堆栈。 1、丰富的缓存数据结构 Netty使用它...

    Zhuxy 评论0 收藏0
  • Netty使用JSSE实现SSLSocket通信

    摘要:上文讲了如何使用生成的签名证书进行加密通信,结果客户端告诉我他们用的版本没有类,并且由于一些交易的原因还不能更新没有你总有吧,来吧。 上文讲了netty如何使用openssl生成的签名证书进行加密通信,结果客户端告诉我他们用的netty版本没有SslContextBuilder类,并且由于一些PY交易的原因还不能更新netty....showImg(https://segmentfau...

    DTeam 评论0 收藏0
  • Netty概念和体系结构

    摘要:异步和事件驱动是一款异步的事件驱动的网络应用程序框架,支持快速地开发可维护的高性能的面向协议的服务器和客户端。由提供的通知机制消除了手动检查对应的操作是否完成的必要。事件和使用不同的事件来通知我们状态的改变或者是操作的状态。 异步和事件驱动  Netty是一款异步的事件驱动的网络应用程序框架,支持快速地开发可维护的高性能的面向协议的服务器和客户端。 Netty简介 分类 Netty...

    FingerLiu 评论0 收藏0
  • Netty 源码分析之 一 揭开 Bootstrap 神秘的红盖头 (务器端)

    摘要:目录源码分析之番外篇的前生今世的前生今世之一简介的前生今世之二小结的前生今世之三详解的前生今世之四详解源码分析之零磨刀不误砍柴工源码分析环境搭建源码分析之一揭开神秘的红盖头源码分析之一揭开神秘的红盖头客户端源码分析之一揭开神秘的红盖头服务器 目录 Netty 源码分析之 番外篇 Java NIO 的前生今世 Java NIO 的前生今世 之一 简介 Java NIO 的前生今世 ...

    张金宝 评论0 收藏0

发表评论

0条评论

rickchen

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<