Mina 单双向认证

生成服务器端密钥

keytool -genkey -alias serverkey -keystore kserver.keystore

导出服务器端证书

keytool -export -alias serverkey -keystore kserver.keystore -file server.crt

将服务器端证书保存到客户端受信密钥中

keytool -import -alias serverkey -file server.crt -keystore tclient.keystore

采用同样的方法,生成客户端的私钥,客户端的证书,并且导入到服务端的Trust KeyStore中

1)keytool -genkey -alias clientkey -keystore kclient.keystore
2)keytool -export -alias clientkey -keystore kclient.keystore -file client.crt
3)keytool -import -alias clientkey -file client.crt -keystore tserver.keystore

如此一来,生成的文件分成两组
服务端保存:kserver.keystore tserver.keystore
客户端保存:kclient.keystore  tclient.keyestore


根据需要可以使用双向或单向认证,这里给出单向认证

服务器端:

SSLContext context = SSLContext.getInstance("TLS");
KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore tks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("kserver.keystore"), "密码".toCharArray());
tks.load(new FileInputStream("tserver.keystore"), "密码".toCharArray());
keyFactory.init(ks, "密码".toCharArray());
trustFactory.init(tks);
context.init(keyFactory.getKeyManagers(), trustFactory.getTrustManagers(), null);
		
sslFilter = new SslFilter(context);
sslFilter.setUseClientMode(false);
sslFilter.setNeedClientAuth(false);
sslFilter.setWantClientAuth(false);
session.getFilterChain().addFirst("tls", sslFilter);
session.setAttribute(SslFilter.DISABLE_ENCRYPTION_ONCE, true);


客户端:

SSLContext context = SSLContext.getInstance("TLS");
KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore tks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("kclient.keystore"), "密码".toCharArray());
tks.load(new FileInputStream("tclient.keystore"), "密码".toCharArray());
keyFactory.init(ks, "密码".toCharArray());
trustFactory.init(tks);
context.init(null, trustFactory.getTrustManagers(), null);
		
sslFilter = new SslFilter(context);
sslFilter.setUseClientMode(true);
session.getFilterChain().addFirst("tls", sslFilter);

可以用网络抓包工具看到加入TLS之后的数据是经历加密之后传输的

你可能感兴趣的:(Java)