Netty进行SSL认证

第一步:   生成Netty服务端私钥和证书仓库命令,用于将客户端的证书保存到服务端的授信证书仓库中 
 keytool -genkey -alias securechat -keysize 2048 -validity 365 -keyalg RSA -dname "CN=localhost" -keypass sNetty -storepass sNetty -keystore sChat.jks

第二步:生成Netty服务端自签名证书 用于颁给使用者 从 证书仓库中导出证书

keytool -export -alias securechat -keystore sChat.jks -storepass sNetty -file sChat.cer

 第三步:生成客户端的私钥和证书仓库,用于将服务端的证书保存到客户端的授信证书仓库中 

    keytool -genkey -alias smcc -keysize 2048 -validity 365  -keyalg RSA -dname "CN=localhost" -keypass sNetty  -storepass sNetty -keystore cChat.jks

第四步:生成客户端自签名证书

  keytool -export -alias smcc -keystore cChat.jks -storepass sNetty -file cChat.cer

第五步:将Netty服务端证书导入到客户端的证书仓库中

keytool -import -trustcacerts -alias securechat -file sChat.cer -storepass sNetty -keystore cChat.jks

第六步:将客户端的自签名证书导入到服务端的信任证书仓库中:

   keytool -import -trustcacerts -alias smcc -file cChat.cer -storepass sNetty -keystore sChat.jks


 -keysize 2048 密钥长度2048位(这个长度的密钥目前可认为无法被暴力破解)
-validity 365 证书有效期365天
-keyalg RSA 使用RSA非对称加密算法
-dname "CN=localhost" 设置Common Name为localhost
-keypass sNetty密钥的访问密码为sNetty
-storepass sNetty密钥库的访问密码为sNetty(其实这两个密码也可以设置一样,通常都设置一样,方便记)
-keystore sChat.jks 指定生成的密钥库文件为sChata.jks

SecureChatClient
import java.io.BufferedReader;
import java.io.InputStreamReader;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class SecureChatClient {

    public void start(String host,int port) throws Exception{
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .handler(new SecureChatClientInitializer());

            // Start the connection attempt.
            Channel ch = b.connect(host, port).sync().channel();
            // Read commands from the stdin.
            ChannelFuture lastWriteFuture = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    System.in));
            for (;;) {
                String line = in.readLine();
                if (line == null) {
                    break;
                }
                /**
                 * 所有的输入最后 加上分隔符 用于分割 因为我们使用的是 依照 回车作为分隔符的
                 */
                lastWriteFuture = ch.writeAndFlush(line + "\r\n");

                if ("bye".equals(line.toLowerCase())) {
                    ch.closeFuture().sync();
                    break;
                }
            }

            // Wait until all messages are flushed before closing the channel.
            if (lastWriteFuture != null) {
                lastWriteFuture.sync();
            }
        }finally{
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new SecureChatClient().start("localhost", 8765);

    }

}

 

SecureChatClientHandler
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class SecureChatClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
        System.err.println(msg);
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

 

 

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.CharsetUtil;

import javax.net.ssl.SSLEngine;
import java.nio.ByteOrder;

public class SecureChatClientInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        String cChatPath = System.getProperty("user.dir") + "\\src\\main\\resources\\cChat.jks";

        SSLEngine engine = SecureChatSslContextFactory.getClientContext(cChatPath)
                .createSSLEngine();//创建SSLEngine
        engine.setUseClientMode(true);//客户方模式
        pipeline.addLast("ssl", new SslHandler(engine));


         pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
       // pipeline.addLast(new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2, true));

        // pipeline.addLast("decoder", new JsonDecoder());
        // pipeline.addLast("encoder", new StringEncoder());
        //pipeline.addLast(new JsonDecoder());
       //pipeline.addLast(new LengthFieldPrepender(2));
        pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
        //pipeline.addLast(new JsonEncoder());

        pipeline.addLast("handler", new SecureChatClientHandler());

    }

    /*public static void main(String[] args) {
        String s=System.getProperty("user.dir")+"\\src\\main\\resources\\cChat.jks";
        System.out.println(s);
    }*/
}

 

 

 

package edu.mi.oneway;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class SecureChatServer {

    public void run(int port) throws InterruptedException{
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new SecureChatServerInitializer());

            ChannelFuture cf = b.bind(port).sync();

            cf.channel().closeFuture().sync();

        }finally{
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws InterruptedException {
        new SecureChatServer().run(8765);

    }

}

 

package edu.mi.oneway;

import java.net.InetAddress;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.GlobalEventExecutor;

public class SecureChatServerHandler extends SimpleChannelInboundHandler<String> {

    static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.pipeline().get(SslHandler.class).handshakeFuture()
                .addListener(new GenericFutureListener<Future<Channel>>() {

                    @Override
                    public void operationComplete(Future<Channel> arg0)
                            throws Exception {
                        if(arg0.isSuccess()){
                            ctx.writeAndFlush("Welcome to "+ InetAddress.getLocalHost().getHostName()+ " secure chat service!\n");
                            ctx.writeAndFlush("Your session is protected by "+ ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()+ " cipher suite.\n");
                            channels.add(ctx.channel());

                        }
                    }
                });


    }


    @Override
    protected void messageReceived(ChannelHandlerContext ctx, String msg)
            throws Exception {
        for (Channel c : channels) {
            if (c != ctx.channel()) {
                c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] "+ msg + '\n');
            } else {
                c.writeAndFlush("[you] " + msg + '\n');
            }
        }
        if ("bye".equals(msg.toLowerCase())) {
            ctx.close();
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}

 

 

 

package edu.mi.oneway;

import javax.net.ssl.SSLEngine;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.*;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslHandler;

public class SecureChatServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel sc) throws Exception {
        ChannelPipeline pipeline = sc.pipeline();
        String sChatPath = (System.getProperty("user.dir")+ "\\src\\main\\resources\\sChat.jks");

        SSLEngine engine = SecureChatSslContextFactory.getServerContext(sChatPath).createSSLEngine();
        engine.setUseClientMode(false);//设置为服务器模式
        //engine.setNeedClientAuth(false);//不需要客户端认证,默认为false,故不需要写这行。
        pipeline.addLast("ssl", new SslHandler(engine));
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192,Delimiters.lineDelimiter()));
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        pipeline.addLast("handler", new SecureChatServerHandler());
    }


}
package edu.mi.oneway;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

public final class SecureChatSslContextFactory {

    private static final String PROTOCOL = "TLS";

    private static SSLContext SERVER_CONTEXT;//服务器安全套接字协议

    private static SSLContext CLIENT_CONTEXT;//客户端安全套接字协议


    public static SSLContext getServerContext(String pkPath){
        if(SERVER_CONTEXT!=null) return SERVER_CONTEXT;
        InputStream in =null;

        try{
            //密钥管理器
            KeyManagerFactory kmf = null;
            if(pkPath!=null){
                //密钥库KeyStore
               // KeyStore.getDefaultType()
                KeyStore ks = KeyStore.getInstance("JKS");
                //加载服务端证书
                in = new FileInputStream(pkPath);
                //加载服务端的KeyStore  ;sNetty是生成仓库时设置的密码,用于检查密钥库完整性的密码
                ks.load(in, "sNetty".toCharArray());

                kmf = KeyManagerFactory.getInstance("SunX509");
                //初始化密钥管理器
                kmf.init(ks, "sNetty".toCharArray());
            }
            //获取安全套接字协议(TLS协议)的对象
            SERVER_CONTEXT= SSLContext.getInstance(PROTOCOL);
            //初始化此上下文
            //参数一:认证的密钥
            // 参数二:对等信任认证
            // 参数三:伪随机数生成器 。 由于单向认证,服务端不用验证客户端,所以第二个参数为null
            SERVER_CONTEXT.init(kmf.getKeyManagers(), null, null);

        }catch(Exception e){
            throw new Error("Failed to initialize the server-side SSLContext", e);
        }finally{
            if(in !=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return SERVER_CONTEXT;
    }


    public static SSLContext getClientContext(String caPath){
        if(CLIENT_CONTEXT!=null) return CLIENT_CONTEXT;

        InputStream tIN = null;
        try{
            //信任库
            TrustManagerFactory tf = null;
            if (caPath != null) {
                //密钥库KeyStore
                KeyStore tks = KeyStore.getInstance("JKS");
                //加载客户端证书
                tIN = new FileInputStream(caPath);
                tks.load(tIN, "sNetty".toCharArray());
                tf = TrustManagerFactory.getInstance("SunX509");
                // 初始化信任库
                tf.init(tks);
            }

            CLIENT_CONTEXT = SSLContext.getInstance(PROTOCOL);
            //设置信任证书
            CLIENT_CONTEXT.init(null,tf == null ? null : tf.getTrustManagers(), null);

        }catch(Exception e){
            e.printStackTrace();
            throw new Error("Failed to initialize the client-side SSLContext");
        }finally{
            if(tIN !=null){
                try {
                    tIN.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return CLIENT_CONTEXT;
    }

}

 

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值