Netty使用记录-自定义证书单向认证

1、通过openssl生成自签名证书,得到证书文件(x509格式)和私钥(pkcs8格式)(过程参考其他文章)

2、Netty服务器端加载证书与私钥。

File certChainFile=new File("/home/certs/nginx.crt");
File keyFile=new File("/home/certs/pkcs8_rsa_private_key.pem");
SslContext sslCtx = SslContextBuilder.forServer(certChainFile, keyFile).clientAuth(ClientAuth.NONE).build();
ch.pipeline().addLast("ssl", sslCtx.newHandler(ByteBufAllocator.DEFAULT));

3、Netty客户端加载证书,重写TrustManagerFactory

//加载服务器端证书,创建keystore
CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    Certificate cfet = cf.generateCertificate(new FileInputStream("C:\\Users\\Administrator\\Desktop\\nginx.crt"));
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", cfet);


//初始化TrustManagerFactory
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
                    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
                    tmf.init(keyStore);


//Netty客户端
SslContext sslCtx = SslContextBuilder.forClient().trustManager(tmf).build();
ch.pipeline().addLast("ssl", sslCtx.newHandler(ByteBufAllocator.DEFAULT));

 

你可能感兴趣的:(Netty)