我需要信任管理器默认实现的源代码
问问题
1483 次
2 回答
-2
你可以试试这种方式。我相信这是最好的做法。
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
httpClient.sslSocketFactory(getSSLConfig(getApplicationContext()).getSocketFactory(), trustManager);
} catch (Exception e) {
Timber.e(String.valueOf(e));
}
private static SSLContext getSSLConfig(Context context) throws CertificateException, IOException,
KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate ca;
try (InputStream cert = context.getResources().openRawResource(R.raw.yourCERT)) {
ca = cf.generateCertificate(cert);
}
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
return sslContext;
}
于 2017-10-03T05:36:44.150 回答