How to do SSL pinning via public key

What is  SSL ?

SSL stands for Secure Socket Layer. It is a protocol for establishing secure data transfer between networked computers or servers.

Need For SSL-

Many developers assume that using HTTPS in a network layer is enough to be sure that user data transfer will be fully secured and not compromised by a Man-in-the-Middle (MitM) attack. In most cases that is true, but not always.

This is why to secure information passed by a browser, like a customer’s credit card number or password to a web server, most of the applications like an online store or online banking application uses SSL to prevent Man-in-the-Middle.

Android SSL Pinning–

There multiple ways we can perform SSL pinning in android 

1- Certificate pinning

2-Public key pinning 

3- SPKI (SubjectPublicKeyInfo) pinning 

Here we will focus our attention on Public key pinning as it is the most recommended way for safe SSL pinning operations.

To implement the pinning you need to know your certificates SPKI data.

we can retrieve it using OpenSSL.

Pinning on Android N(API 24) and above-:

If minimum SDK is Android N  then the implementation is very simple as Android has a new API in Android SDK from API 24 onwards the Network Security Configuration.

you just need to enter an XML configuration file that defines the pins you require in our  AndroidManifest.xml file.

<?xml version=”1.0″ encoding=”utf-8″?>



        <domain includeSubdomains=”true”></domain>


            <pin digest=”SHA-256″>6jj6tz+scE+XW+mlai6ZipDfFWn1dqvfLG+nU7tq1V8=</pin>

            <pin digest=”SHA-256″>LLh6dUR9y6Kka30RrAn7fKbQG/uEtLMkBgFF2Fuihg=</pin>




Declaration of Configuration file in AndroidManifest.xml:-

<?xml version=”1.0″ encoding=”utf-8″?>

<manifest xmlns:android=””















if  you want to use network libraries for pinning we can do the following 

Pinning with Retrofit-

Pining with Retrofit is easy being built on top of OkHttp.

CertificatePinner certPinner = new CertificatePinner.Builder()




OkHttpClient okHttpClient = new OkHttpClient.Builder()



Retrofit retrofit = new Retrofit.Builder()





Pinning with HttpUrlConnection-

if you are still using HttpURlconnection consider upgrading it to some other network libraries.

Leave a Reply