This question can be a duplicate of How can I pin a certificate with Square OKHTTP? But since it's not clear I'm asking again. I have to attach SSL certificate to my http client. I'm using retrofit version 2.2.0
and okHttp version 3.6.0
I have a certificate in .crt
format. Currently I'm doing the certificate pinning as shown here. But I don't know its proper or not.
Following is my code
static void pinCertificate(Context context, OkHttpClient.Builder builder) {
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream cert = context.getResources().openRawResource(R.raw.certificate);
Certificate ca;
ca = cf.generateCertificate(cert);
// creating a KeyStore containing our trusted CAs
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);
builder.sslSocketFactory(sslContext.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
Is it the proper way to pin a .crt
certificate with okHttp? How can we test if it is doing the handshake properly?
If it is wrong can anyone show a sample code to pin the certificate properly?
I saw some samples and documenst like this https://medium.com/@develodroid/android-ssl-pinning-using-okhttp-ca1239065616
but it is entirely different from what I have implemented. Nowhere they have used a crt
file.
If someone could share a better explanation about certificate pinning and how it can be done in okHttp , it would be very helpful. Thanks in advance!!