添加自签名证书OkHttpClient

时间:2019-04-02 02:13:40

标签: java android ssl certificate

我有一个Android应用程序,需要使用REST连接到服务器。我将Retrofit 2用于请求,并且效果很好。 问题是当我想使用SSL连接时。与开放的SSL,我有一个client.crt,myPrivateKey.pem和request.csr。我还有一个rootCA,用于加密客户端和服务器证书。

当我在线检查时,我发现了很多使用一个CA文件的解决方案。

这是我到目前为止的代码。

range

当我向客户端发送请求时,我没有找到证书路径的java.security.cert.CertPathValidatorException信任锚。

您能帮我用我的证书和密钥创建我的客户吗?

1 个答案:

答案 0 :(得分:0)

我通过此website

修复了代码库

私有OkHttpClient initClient()抛出KeyStoreException,CertificateException,NoSuchAlgorithmException,IOException,UnrecoverableKeyException,KeyManagementException {

// Trust self signed certificate
InputStream certificateFileCRT = mContext.getResources().openRawResource(R.raw.server);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(certificateFileCRT);
String alias = cert.getSubjectX500Principal().getName();
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);

// KeyStore containing client certificate
KeyStore keyStore = KeyStore.getInstance("PKCS12");
InputStream fis = mContext.getResources().openRawResource(R.raw.client);
keyStore.load(fis, "PASSWORD".toCharArray());

// Build an SSL context
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
kmf.init(keyStore, "PASSWORD".toCharArray());
KeyManager[] keyManagers = kmf.getKeyManagers();
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();

SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(keyManagers, trustManagers, null);

return new OkHttpClient.Builder()
        .readTimeout(60, TimeUnit.SECONDS)
        .sslSocketFactory(sslContext.getSocketFactory())
        .hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        })
        .build();               

}