How to Implement Certificate Pinning in Android

Mahesh Galande
Globant
Published in
2 min readSep 20, 2022

For details on what SSL Pinning is, its types, how it works, and how to generate certificates for server or public keys please refer to this article.

Now we have understood what certificate pinning is, why it is necessary for the app, and the different types of certificates root, intermediate, and leaf.

Let us further understand how to implement certificate pinning in an Android application.

Now we have Public Key and Certificate, how to pin in an app?

Retrofit Way before Android 7.0 (API 24)

OkHTTP is providing CertificatePinner to make that task easy.

The implementation looks like this:

As we see using retrofit and OkHTTP it’s easy to pin a certificate before Android 7.0

What about Android 7.0 onwards ?

Network_security_config.xml way:

Using the network_security_config.xml file in the XML folder we can achieve pinning.

  1. Go to the project’s res directory, create an XML folder, and create the file network_security_config.xml inside the XML folder.

2. Pin the certificate inside the network_config.xml file use <trust-anchors> tags.

3. For pinning public key we are using <pin-set> tag with SHA 256 like below.

4. After configuring the network_security_confing.xml file, don’t forget to add this file inside the AndroidManifest.xml networkSecurityConfig tag.

Conclusion

Now we understand what certificate pinning is, the different types of certificates and how to pin certificates using certificate pinner and network config before API 24 and after API 24.

Read more about SSL Pinning

SSL Pinning — Increase Server Identity Trust

Team Credits

Darshan Mistry | Akshata Shelar

--

--