Skip to content
Görkem KaraLead Mobile Developer

How to SSL Pinning with OkHttp on Android?

Android Development6 min read

Securing Android apps with SSL Pinning using OkHttp

While developing secure android applications, SSL Pinning is a security measure that ensures that the application communicates with trusted servers only by verifying SSL certificates. This is very important to protect sensitive data from man-in-the-middle (MITM) attacks. Otherwise, hackers who access your application with malware can cause serious damage to you. In this article, we will look at how to implement SSL Pinning on Android using OkHttp and Ktor.

Diagram of the key steps in How to SSL Pinning with OkHttp on Android?: What is SSL Pinning?, Implementing SSL Pinning with OkHttp, Export Your Server’s Certificate

What is SSL Pinning?

SSL is actually encrypted certificates as a secure socket layer.
SSL Pinning allows you to send/read the data you send and receive while communicating with your Android application’s backend servers by encrypting it.
While sending this data, we encrypt the secure SSL with TLS and provide communication.
When our server sees that we have come with a secure vehicle, it gives us the necessary information flow.
Of course, this security measure can be easily broken by a hacker in Android applications.

Before doing this, if you have any questions like how to create an android application? How to create a service structure? Please visit here to learn them.

Can SSL Pinning be Bypassed?

Yes, Our aim is only to make the hackers’ job difficult (to increase the work they will do in 1 step to 10 steps), otherwise it is normal for every security measure to be broken.

Implementing SSL Pinning with OkHttp

OkHttp is a popular networking library used in Android. To implement SSL Pinning with OkHttp, you need to obtain the certificate of the server you are communicating with.

Note: Since Retrofit is a library built on Okhttp, you can also do this with Retrofit or similar tools.

Export Your Server’s Certificate

Go to your server address in a browser. This could be something like api.server.com.

Then click on the lock (secure) icon to the left of the URL in the browser. In the window that opens, click on the “Certified valid” or “Show certificate” buttons. If you are using Windows, you can go to the detail page in the window and save it by saying copy to file.

display certificate in opened browser

Click on the certificate’s logo or drag it to the desktop and download it as a .cert file.

If you can’t download the “cert” file this way, try downloading it using online tools. For example, I found a site for you. Click here.

Convert Certificate To Pem

We want to convert the .cert file to .pem file and obtain the base64 code. And as I will explain below, we will pull this from the server and perform a fully secure ssl pinning.

Install OpenSSL

openssl converts the .cert file to .pem file and allows us to obtain base64 code.

Download openssl for windows from: https://openssl-library.org/source/

For macos, type the following command in terminal:

brew install openssl

.cert to pem

Open the command window. Go to the directory where the .cert file you downloaded is located and run the following command.

openssl x509 -in CERT_TO_DOWNLOANDED.crt -out certificate.pem -outform PEM

Note: Remember to replace the certificate file name in the command with your own.

Right click on the resulting .pem file and open it with a text editor. And here is the base64 of the certificate.

Add this base64 code as a STRING to the “initial setup api” or firebase remote config from the apis you use for your application and complete the retrieval processes from there.

SSL Certificate Pinning in Okhttp

Let’s add the certificate you received from the remote server as a string to okhttp.

Create X509Certificate

Certificates are known as X509Certificate in Android and you can decode a string certificate to it.

X509Certificate x509Certificate = okhttp3.tls.Certificates.decodeCertificatePem(cert);

You can give the base64 string you received from your remote server to the cert parameter here.

Add SSL Certifacete to Okhttp

Install Okhttp in a standard way.

OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder()
                // establish connection with server
                .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
                // time between each byte read from server
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                // time between each byte sent to server
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .addNetworkInterceptor(interceptor)
                .addInterceptor(httpLoggingInterceptor);

Now add SSL pinning. HandshakeCertificates and Certificates come from the com.squareup.okhttp3:okhttp-tls artifact; use the same version as your okhttp dependency.

java
X509Certificate x509Certificate = Certificates.decodeCertificatePem(cert);
HandshakeCertificates handshakeCertificates = new HandshakeCertificates.Builder()
        .addTrustedCertificate(x509Certificate)
        .build();
okHttpClient.sslSocketFactory(
        handshakeCertificates.sslSocketFactory(),
        handshakeCertificates.trustManager());
OkHttpClient client = okHttpClient.build();

Bypass if SSL Pinning fails

If the certificate could not be loaded from your remote config, the code below falls back to a client that trusts every certificate. Keep that fallback in debug builds only: in a release build it turns TLS verification off completely and makes MITM attacks trivial.

java
if (x509Certificate != null) {
    HandshakeCertificates handshakeCertificates = new HandshakeCertificates.Builder()
            .addTrustedCertificate(x509Certificate)
            .build();
    okHttpClient.sslSocketFactory(
            handshakeCertificates.sslSocketFactory(),
            handshakeCertificates.trustManager());
} else if (BuildConfig.DEBUG) {
            // debug builds only, never ship a trust-all TrustManager in release
            try {
                final TrustManager[] trustAllCerts = new TrustManager[]{
                        new X509TrustManager() {
                            @Override
                            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                            }

                            @Override
                            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                            }

                            @Override
                            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                                return new java.security.cert.X509Certificate[]{};
                            }
                        }
                };

                final SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                okHttpClient.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
                okHttpClient.hostnameVerifier((hostname, session) -> true);

            } catch (Exception exception) {
                Logger.w(exception);
                CrashlyticsUtil.getInstance().setAppCrashError(exception);
            }
        }

In this way, when you implement all the code correctly, your application will be more secure.
Don’t be afraid of your SSL certificate being stolen because the method I showed you is a publicly verifiable SSL certificate.

Trusting a single certificate file works, but the simplest and most common way to pin in OkHttp is CertificatePinner. It pins the SHA-256 hash of the server’s public key instead of the whole certificate, so the pin keeps working when the certificate is renewed with the same key. The API is the same in OkHttp 4.x and 5.x.

kotlin
import okhttp3.CertificatePinner
import okhttp3.OkHttpClient

val certificatePinner = CertificatePinner.Builder()
    // current key of the server
    .add("api.example.com", "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
    // backup key, used after the next key rotation
    .add("api.example.com", "sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=")
    .build()

val client = OkHttpClient.Builder()
    .certificatePinner(certificatePinner)
    .build()

The hostname can also be a pattern: *.example.com matches one level of subdomains, **.example.com matches example.com and all of its subdomains. Retrofit and the Ktor OkHttp engine use this client as it is, so the pins apply to them too.

How to Get the Pin Hash

Run this command against your server. It prints the base64 SHA-256 hash of the public key, which goes after sha256/:

bash
openssl s_client -servername api.example.com -connect api.example.com:443 </dev/null \
  | openssl x509 -pubkey -noout \
  | openssl pkey -pubin -outform der \
  | openssl dgst -sha256 -binary \
  | openssl enc -base64

A quicker trick: add a wrong pin, make one request and read the SSLPeerUnverifiedException message. OkHttp lists the sha256/ pins of every certificate in the chain, so you can copy the right one. Always pin at least two keys, the current one and a backup. With a single pin, a key change on the server locks every installed app out until users update.

Alternative: Network Security Config (Android 7.0+)

Since Android 7.0 (API 24) you can declare pins in XML without touching your networking code. They are checked by the platform trust manager, which OkHttp uses by default. Set the expiration attribute: after that date the pins are no longer enforced, so an old app version does not break when you rotate keys.

xml
<!-- res/xml/network_security_config.xml -->
<network-security-config>
    <domain-config>
        <domain includeSubdomains="true">api.example.com</domain>
        <pin-set expiration="2027-12-31">
            <pin digest="SHA-256">AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</pin>
            <!-- backup pin -->
            <pin digest="SHA-256">BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=</pin>
        </pin-set>
    </domain-config>
</network-security-config>
xml
<application
    android:networkSecurityConfig="@xml/network_security_config"
    ... >

For debugging with a proxy, use debug-overrides instead of a trust-all TrustManager in code. It only applies when the app is debuggable, so release builds stay pinned:

xml
<network-security-config>
    <debug-overrides>
        <trust-anchors>
            <certificates src="user" overridePins="true" />
        </trust-anchors>
    </debug-overrides>
</network-security-config>

SSL Pinning Security Considerations

  • Certificate Expiration: Certificates expire over time, and if the pinned certificate is outdated, your app will fail to communicate with the server. Keep your certificates updated regularly.

  • Multiple Certificates: If your server rotates certificates, consider pinning multiple certificates.

  • Debugging: During development, SSL Pinning can make debugging difficult. Consider disabling SSL Pinning for debug builds, as shown above, to facilitate easier testing.

Conclusion

We have done a study to make your application more secure by doing SSL Pinning. Although this is sometimes necessary for security, it makes it difficult for us while developing, so please do not forget to bypass ssl with BuildConfig.DEBUG after you see that your code is working.

Last updated: Written by: Görkem KARA

What did you think of this post?

Comments

No comments yet. Be the first to write one.

Leave a comment

Comments appear after the site owner approves them.

Your comment is published without your name; your email is used only for this comment and never published. Privacy notice

Security check Runs automatically when you send