首页 > Web开发 > 详细

netty ssl

时间:2015-11-24 20:22:46      阅读:1151      评论:0      收藏:0      [点我收藏+]

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

 

netty ssl

原文:http://www.cnblogs.com/hujihon/p/4992636.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!