OkHttp3, Retrofit and certificate pinning: how to give an expiration to the pinning

Viewed 1355

In my Android application, I need to use certificate pinning. I'm using Retrofit and OkHttp3 to consume web service and I already define the pinning on hashcode of the certificate.

CertificatePinner certificatePinner = new CertificatePinner.Builder()
                .add("dummy.com", "sha256/xxxxxxxxxx=")
                .build();     

OkHttpClient httpClient = new OkHttpClient.Builder()
        .certificatePinner(certificatePinner)
        .callTimeout(240, TimeUnit.SECONDS)
        .readTimeout(240, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
       .build();


Retrofit retrofitKripton = new Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(KriptonBinderConverterFactory.create())
        .addConverterFactory(ScalarsConverterFactory.create())
        .client(httpClient).build();

I want to force certificate pinning until the certificate expiration, after this I want simply to avoid certificate pinning (this is due the fact I want to avoid that application stop to work after certificate expiration). Is there a method to tell OkHpttp3/Retrofit to have the desired behaviour?

Thanks in advance

2 Answers

Is there a method to tell OkHpttp3/Retrofit to have the desired behaviour?

You can do that yourself:

OkHttpClient.Builder = new OkHttpClient.Builder();

if (applyPins()) {
    CertificatePinner certificatePinner = new CertificatePinner.Builder()
                    .add("dummy.com", "sha256/xxxxxxxxxx=")
                    .build();     

    builder..certificatePinner(certificatePinner);
}


OkHttpClient httpClient = builder
        .callTimeout(240, TimeUnit.SECONDS)
        .readTimeout(240, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
       .build();

Retrofit retrofitKripton = new Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(KriptonBinderConverterFactory.create())
        .addConverterFactory(ScalarsConverterFactory.create())
        .client(httpClient).build();

Implement applyPins() as a method that returns true if you want to apply the pins, false otherwise. For example, you might use your proposed date comparison.

Related