首页 > 代码库 > JSSE编程基本代码
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编程基本代码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。