public static KeyStore getKeystore(){ KeyStore keyStore = null; try { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try { keyStore.load(null); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } } catch (KeyStoreException e) { e.printStackTrace(); } return keyStore; } public static X509TrustManager getX509TrustManager(KeyStore keystore) throws Exception { X509TrustManager pkixTrustManager = null; // TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); // tmf.init(keystore); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keystore); TrustManager tms[] = tmf.getTrustManagers(); for (int i = 0; i < tms.length; i++) { if (tms[i] instanceof X509TrustManager) { pkixTrustManager = (X509TrustManager) tms[i]; break; } } // throw new Exception("Couldn't initialize"); return pkixTrustManager; } public static void checkClientTrusted(X509TrustManager pkixTrustManager,X509Certificate[] arg0, String arg1) throws CertificateException { try { pkixTrustManager.checkClientTrusted(arg0, arg1); } catch (CertificateException excep) { excep.printStackTrace(); } } public static void checkServerTrusted(X509TrustManager pkixTrustManager,X509Certificate[] arg0, String arg1) throws CertificateException { try { pkixTrustManager.checkServerTrusted(arg0, arg1); } catch (CertificateException excep) { excep.printStackTrace(); } } public static X509Certificate[] getAcceptedIssuers(X509TrustManager pkixTrustManager) { LogUtils.d( "Number of trusted certificates is "+ pkixTrustManager.getAcceptedIssuers().length); return pkixTrustManager.getAcceptedIssuers(); }
//获取证书列表,keystore需要传null public static void listX509Certificate(){ try { //获取所有证书信息 X509Certificate[] x509Certificates = getAcceptedIssuers(getX509TrustManager((KeyStore) null)); for(int i=0;i<x509Certificates.length;i++){ X509Certificate x509Certificate = x509Certificates[i]; LogUtils.d("证书名信息 : "+x509Certificate.toString()+"\n\n\n"); } } catch (Exception e) { e.printStackTrace(); } }
注:参考资料:
https://stackoverflow.com/questions/36254459/how-to-find-trusted-certificate-for-both-android-and-ios/36254460#36254460
https://stackoverflow.com/questions/24843825/need-help-in-understanding-getacceptedissuers-method
https://stackoverflow.com/questions/7822381/need-help-understanding-certificate-chains
https://stackoverflow.com/search?q=android+get+trust+certificate+list+by+code+
https://blog.csdn.net/eaglet/article/details/1685737
https://www.cnblogs.com/webster1/p/5663807.html