- SSL验证Handler创建.
//1.使用秘钥库给对方进行身份验证
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream("/home/my.jks"), "1234567".toCharArray());
//2.使用某个证书验证
KeyStore keyStore2 = KeyStore.getInstance("JKS");
keyStore2.load(null, null);
CertificateFactory factory = CertificateFactory.getInstance("X.509");
Certificate certificate = factory.generateCertificate(new FileInputStream("/home/my.cer"));
keyStore2.setCertificateEntry("my",certificate);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, "654321".toCharArray());
// keyManagerFactory.init(keyStore2, "654321".toCharArray());
//本机证书,从秘钥库获取.
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new FileInputStream("home/my.jks"), "1234567".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
//init SSLContext实例
SSLContext sslContext = SSLContext.getInstance("TLS");
//keyManagerFactory 自己的身份证,trustManagerFactory 自己的验证器
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
//服务端
SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setNeedClientAuth(true);
sslEngine.setUseClientMode(false);
//客户端
sslEngine.setNeedClientAuth(true);
sslEngine.setUseClientMode(true);
//pipeline SslHandler,放在addLast最前
SslHandler tlsHandler = new SslHandler(sslEngine, false);
/*
* RSA签名认证
* pipeline.addLast(tlsHandler) ;
*
**/
2.netty配置
//配置netty服务
nettyBoot.group(bossEventLoop, workerEventLoop)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ChannelPipeline pipeline = ch.pipeline();
//RSA签名认证
pipeline.addLast(tlsHandler) ;
//入站,1,2,3出站5,4
pipeline.addLast(new LoggingHandler(LogLevel.INFO)) //日志打印
.addLast("4", prepender)//4 分包,bytes -> http数据包
.addLast("5", encoder)//5 //msg -> bytes
.addLast("1", new LengthFieldBasedFrameDecoder(1000000, 0, 4, -4, 4))//1,http网络数据包,组包
.addLast("2", decoder)//2 //bytes -> msg ,自定义解码
.addLast("3", msgServerHandler);//3 //msg -> msg,数据转换,转发数据
}
});