问题:android在网络各种教程里面,都是只有BKS的格式,但是一般后端给我们的公钥证书都是crt/cer/pem格式的,这种时候,常用的做法就是用keytools转换成bks格式。个人感觉,这种做法很low,一眼就能让别人感觉你完全不懂证书
其实我们常用的证书就2大种:
- 16进制的
- 16进制进行base64编码后(这种尤其常用),添加----BEGIN CERTIFICATE------ END…………
SSLContext sslContext = SSLContext.getInstance("TLS");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream in = BaseUtils.getApp().getAssets().open("puk.crt");
// 这个puk.crt文件可以是16进制的也可以是Base64后的
Certificate ca = cf.generateCertificate(in);
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
trustStore.setCertificateEntry("ca", ca);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
OkHttpClient okHttpClient = new OkHttpClient.Builder()// 构建OKHttp客户端
.sslSocketFactory(socketFactory)
.build();
【android|android 使用crt/cer/pem格式的公钥证书】