当SSL碰到证书不合法应该怎么办?
当你用HttpsURLConnection来查看https网页内容而对方证书无效时候,回出现Exception,怎么办。
1.自己有一TrustManager 类 import com.sun.net.ssl.SSLContext; import com.sun.net.ssl.TrustManager; import com.sun.net.ssl.X509TrustManager; import com.sun.net.ssl.TrustManagerFactory; publicclass MyTrustManager implements X509TrustManager { private KeyStore keyStore; private String keyStorePath; private char[] keyStorePassword;public MyTrustManager(){}
// MyTrustManager constructor. Save off keyStore object along with // the path to the keystore (keyStorePath) and it's password // (keyStorePassword). public MyTrustManager(KeyStore keyStore, String keyStorePath, char[] keyStorePassword) { this.keyStore = keyStore; this.keyStorePath = keyStorePath; this.keyStorePassword = keyStorePassword; }// isClientTrusted checks to see if the chain is in the keyStore object.
// This is done with a call to isChainTrusted. public boolean isClientTrusted(X509Certificate[] chain) { return isChainTrusted(chain); }// isServerTrusted checks to see if the chain is in the keyStore object.
// This is done with a call to isChainTrusted. If not it queries the // user to see if the chain should be trusted and stored into the // keyStore object. The keyStore is then saved in the file whose path // keyStorePath public boolean isServerTrusted(X509Certificate[] chain) { return true; }// getAcceptedIssuers retrieves all of the certificates in the keyStore
// and returns them in an X509Certificate array. public X509Certificate[] getAcceptedIssuers() { X509Certificate[] X509Certs = null; try { // See how many certificates are in the keystore. int numberOfEntry = keyStore.size(); // If there are any certificates in the keystore. if(numberOfEntry > 0) { // Create an array of X509Certificates X509Certs = new X509Certificate[numberOfEntry];// Get all of the certificate alias out of the keystore.
Enumeration aliases = keyStore.aliases();// Retrieve all of the certificates out of the keystore
// via the alias name. int i = 0; while (aliases.hasMoreElements()) { X509Certs[i] = (X509Certificate)keyStore. getCertificate((String)aliases.nextElement()); i++; }}
} catch( Exception e ) { System.out.println( "getAcceptedIssuers Exception: " + e.toString() ); X509Certs = null; } return X509Certs; }// isChainTrusted searches the keyStore for any certificate in the
// certificate chain. private boolean isChainTrusted(X509Certificate[] chain) { return true; } } 2.注册你的 TrustManager类 X509TrustManager xtm = new MyTrustManager(); TrustManager mytm[] = { xtm}; SSLContext ctx = SSLContext.getInstance("SSL"); ctx.init(null, mytm, null);SSLSocketFactory factory = ctx.getSocketFactory();
//注册TrustManager类(factory) HttpsURLConnection huc = (HttpsURLConnection) (new URL(“http://www.aaa.com”).openConnection(); //huc.setHostnameVerifier(new com.smartghost.ssl.MyHostnameVerifier()); huc.setSSLSocketFactory(factory); ...... //错误不再