我有一个.p12证书文件,我使用
SSL Converter将其转换为.pem证书文件.然后我在我的android代码中使用那个pem证书文件,如下所示:
OkHttpClient okHttpClient = new OkHttpClient();
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream instream = context.getResources().openRawResource(R.raw.pem_certificate);
Certificate ca;
ca = cf.generateCertificate(instream);
KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType());
kStore.load(null,null);
kStore.setCertificateEntry("ca",ca);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(kStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null,tmf.getTrustManagers(),null);
okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
} catch (CertificateException
| KeyStoreException
| NoSuchAlgorithmException
| IOException
| KeyManagementException e) {
e.printstacktrace();
}
baseURL = endpoint;
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(baseURL)
.setClient(new OkClient(okHttpClient))
.build();
service = restAdapter.create(dishService.class);
但是这段代码不起作用.它在“ca = cf.generateCertificate(instream);”行中失败了.使用CertificateException消息.
解决方法
也许您在R.raw.pem_certificate有问题…
1)尝试使用openssl从服务器获取原始公共证书:
openssl s_client -connect {HOSTNAME}:{PORT} -showcerts
(详情请看这里:https://superuser.com/questions/97201/how-to-save-a-remote-server-ssl-certificate-locally-as-a-file)
2)如何使用自定义SSL证书设置Retrofit2
https://adiyatmubarak.wordpress.com/tag/add-ssl-certificate-in-retrofit-2/
或改造1:
https://number1.co.za/use-retrofit-self-signed-unknown-ssl-certificate-android/
PS:它对我有用,请不要将PEM文件转换为BKS.