1、ssl证书生成参考:
(28条消息) Keytool生成证书_特特专属的博客-CSDN博客_keytool生成证书
2、把SslHandler 添加到Netty处理链的最前面
SSLEngine serverEngine = SslEngineFactory.getServerEngine("D:\\jdk\\jdk8\\bin\\server.keystore", "123456", "D:\\jdk\\jdk8\\bin\\server.keystore", "123456");
pipeline.addLast("ssl", new SslHandler(serverEngine));
3、SslEngineFactory
public final class SslEngineFactory {
private static final String PROTOCOL = "TLS";
private volatile static SSLEngine SERVER_ENGINE;
private volatile static SSLEngine CLIENT_ENGINE;
/**
* 获取服务端 sslEngine
* @param ksPath 本机证书库地址
* @param ksPasswd 本机证书库密码
* @param tsPath 信任证书库地址
* @param tsPasswd 信任证书库密码
* @return
*/
public static SSLEngine getServerEngine(String ksPath, String ksPasswd, String tsPath, String tsPasswd) {
if(null == SERVER_ENGINE){
synchronized (SslEngineFactory.class){
if(null == SERVER_ENGINE){
SSLContext sslContext = getSSLContext(ksPath, ksPasswd, tsPath, tsPasswd);
SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(false);
sslEngine.setNeedClientAuth(true);
SERVER_ENGINE = sslEngine;
}
}
}
return SERVER_ENGINE;
}
/**
* 获取客户端 sslEngine
* @param ksPath 本机证书库地址
* @param ksPasswd 本机证书库密码
* @param tsPath 信任证书库地址
* @param tsPasswd 信任证书库密码
* @return
*/
public static SSLEngine getClientEngine(String ksPath, String ksPasswd, String tsPath, String tsPasswd) {
if(null == CLIENT_ENGINE){
synchronized (SslEngineFactory.class){
if(null == CLIENT_ENGINE){
SSLContext sslContext = getSSLContext(ksPath, ksPasswd, tsPath, tsPasswd);
SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(true);
sslEngine.setNeedClientAuth(true);
CLIENT_ENGINE = sslEngine;
}
}
}
return CLIENT_ENGINE;
}
/**
* 获取通用SSLContext
* @param ksPath 本机证书库地址
* @param ksPasswd 本机证书库密码
* @param tsPath 信任证书库地址
* @param tsPasswd 信任证书库密码
* @return
*/
private static SSLContext getSSLContext(String ksPath, String ksPasswd, String tsPath, String tsPasswd) {
try (InputStream in = new FileInputStream(ksPath);
InputStream tIN = new FileInputStream(tsPasswd)) {
// 本机库
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, ksPasswd.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, ksPasswd.toCharArray());
KeyManager[] keyManagers = kmf.getKeyManagers();
// 信任库
TrustManager[] trustManagers;
KeyStore tks = KeyStore.getInstance(KeyStore.getDefaultType());
tks.load(tIN, tsPasswd.toCharArray());
TrustManagerFactory tf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tf.init(tks);
trustManagers = tf.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance(PROTOCOL);
//参数一:认证的密钥 参数二:对等信任认证 参数三:伪随机数生成器
sslContext.init(keyManagers, trustManagers, null);
return sslContext;
} catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException("SSLContext 创建失败");
}
}
}