JSSE编程基本代码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JSSE编程基本代码相关的知识,希望对你有一定的参考价值。
public static void main(String[] args) throws Exception { //空实现,接受任意服务端的证书。如果用可信公钥库去构造,采用类同下面的KeyManagerFactory //的TrustManagerFactory; TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { //todo } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { //todo } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sslContext = SSLContext.getInstance("SSL"); //自身的证书需要有密钥库,不能像TrustManager那样去构造 KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream("keystore.jks"),"password".toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, "password".toCharArray()); KeyManager km = new MyKeyManager((X509KeyManager)kmf.getKeyManagers()[0]); sslContext.init(new KeyManager[]{km}, new TrustManager[]{tm}, new SecureRandom()); SSLSocket ss = (SSLSocket)sslContext.getSocketFactory().createSocket("localhost",8080); //监听handshake完成事件。 ss.addHandshakeCompletedListener(new HandshakeCompletedListener() { @Override public void handshakeCompleted(HandshakeCompletedEvent event) { System.out.println(event); } }); }
public class MyKeyManager implements X509KeyManager { private X509KeyManager delegate; public MyKeyManager(X509KeyManager delegate){ this.delegate = delegate; } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { return delegate.getClientAliases(keyType, issuers); } @Override public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { return delegate.chooseClientAlias(keyType, issuers, socket); } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { return delegate.getServerAliases(keyType, issuers); } @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { return delegate.chooseServerAlias(keyType, issuers, socket); } @Override public X509Certificate[] getCertificateChain(String alias) { return delegate.getCertificateChain(alias); } @Override public PrivateKey getPrivateKey(String alias) { return delegate.getPrivateKey(alias); } }
本文出自 “天下无贼” 博客,请务必保留此出处http://guojuanjun.blog.51cto.com/277646/1955239
以上是关于JSSE编程基本代码的主要内容,如果未能解决你的问题,请参考以下文章
在 Java (JSSE) 中使用默认 KeyStore 时如何提供特定的 TrustStore