我是靠谱客的博主 痴情红酒,最近开发中收集的这篇文章主要介绍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

最后

以上就是痴情红酒为你收集整理的netty ssl的全部内容,希望文章能够帮你解决netty ssl所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(54)

评论列表共有 0 条评论

立即
投稿
返回
顶部