需要将android应用(改进的REST API)与具有自签名证书的服务器连接,因此我必须信任此证书。
我必须使用:file_certificate.crt,file_chain.chain和file_key.key
在linux中,我运行以下命令:
openssl s_client -connect my.host.com:443 -state -tls1_2 -key file_key.key -cert file_certificate.crt -CAfile file_chain.chain
并且连接成功完成... Verify return code: 0 (ok)
那么如何创建OkHttpClient来使用这3个文件,因为我发现的是使用单个CA文件,如下所示:
public static OkHttpClient createClient(Context context) {
OkHttpClient client = null;
CertificateFactory cf = null;
InputStream cert = null;
Certificate ca = null;
SSLContext sslContext = null;
try {
cf = CertificateFactory.getInstance("X.509");
cert = context.getResources().openRawResource(R.raw.file_certificate); // Place your 'my_cert.crt' file in `res/raw`
ca = cf.generateCertificate(cert);
cert.close();
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.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
client = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory())
.build();
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException | KeyManagementException e) {
e.printStackTrace();
}
return client;
}