netty ssl

netty提供的例子中有secury的实现,不过是一个伪证书。修改了一下其中的SecureChatSslContextFactory类,使用证书的方式实现ssl。修改后代码如下:

public final class SecureChatSslContextFactory {

private static final String PROTOCOL = "SSL";
//private static final String PROTOCOL = "TLS";
private static final SSLContext SERVER_CONTEXT;
private static final SSLContext CLIENT_CONTEXT;

static {
String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
}

SSLContext serverContext;
SSLContext clientContext;
try {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new ClassPathResource("keystore").getInputStream(),"123456".toCharArray());

// Set up key manager factory to use our key store
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(ks, "123456".toCharArray());

// Initialize the SSLContext to work with our key managers.
serverContext = SSLContext.getInstance(PROTOCOL);
serverContext.init(kmf.getKeyManagers(), null, null);
} catch (Exception e) {
throw new Error(
"Failed to initialize the server-side SSLContext", e);
}

try {

KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new ClassPathResource("truststore").getInputStream(),"123456".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(trustStore);

clientContext = SSLContext.getInstance(PROTOCOL);
clientContext.init(null, tmf.getTrustManagers(), null);
} catch (Exception e) {
throw new Error(
"Failed to initialize the client-side SSLContext", e);
}

SERVER_CONTEXT = serverContext;
CLIENT_CONTEXT = clientContext;
}

public static SSLContext getServerContext() {
return SERVER_CONTEXT;
}

public static SSLContext getClientContext() {
return CLIENT_CONTEXT;
}

private SecureChatSslContextFactory() {
// Unused
}
}

证书生成过程如下:
1. 生成keystore和自签名的certificate, 并生成相应公钥和私钥
keytool -genkeypair -alias rock -keyalg RSA -validity 7 -keystore keystore
2. 查看keystore
keytool -list -v -keystore keystore
3. 导出证书
keytool -export -alias rock -keystore keystore -rfc -file rock.cer
cat duke.cer
4. 将第三步导出的证书导入到一个truststore
keytool -import -alias rockcert -file rock.cer -keystore truststore
5. 检查 truststore
keytool -list -v -keystore truststore

原文地址:https://www.cnblogs.com/hujihon/p/4992636.html