首页 > 代码库 > 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编程基本代码