Briefing

Implementing TLS Pinning in Android to Protect Against MITM Attacks

security
by Armando Picón ·

Implement TLS pinning in Android using OkHttp's CertificatePinner and generate SHA‑256 hash with OpenSSL; handle certificate rotation and avoid hard failures.

What to do now

Add CertificatePinner to your OkHttp client with the SHA‑256 hash of your server's public key; update the hash when the certificate rotates.

Summary

By default, Android apps trust any certificate signed by a trusted Certificate Authority, which allows an attacker on a public Wi‑Fi network to install a malicious certificate and intercept traffic. Certificate pinning, also known as TLS pinning, changes this behavior so the app only accepts a specific certificate or public key, rejecting any other valid certificates. In Android, OkHttp’s `CertificatePinner` can be configured with a SHA‑256 hash of the server’s public key, as shown in the code example, and the hash can be generated with an OpenSSL pipeline that extracts the public key and computes its base64‑encoded SHA‑256 digest. Pinning mitigates man‑in‑the‑middle attacks but introduces operational discipline: you must handle certificate rotation, avoid hard failures in production, and understand when pinning adds value versus relying on backend security.

The trade‑offs include the need to update the pin whenever the certificate changes and the risk of breaking the app if the pin is incorrect. Pinning strengthens the transport layer without replacing existing security models, and should be used when the app handles sensitive data such as finance or health. Developers should plan for rotation and monitor pin failures to maintain a secure mobile app. The approach is most valuable when the app handles sensitive data, but it adds operational overhead that must be managed.

Key changes

  • Android defaults to trusting any CA‑signed certificate
  • Certificate pinning restricts trust to a specific cert or public key
  • OkHttp’s CertificatePinner uses a SHA‑256 hash of the server’s public key
  • Hash can be generated with OpenSSL pipeline extracting public key and computing SHA‑256
  • Pinning mitigates MITM attacks but requires handling certificate rotation
  • Operational discipline: update pin on rotation, avoid hard failures
  • Pinning strengthens transport layer without replacing existing security models
  • Use pinning when app handles sensitive data like finance or health

Affects

internal

Customer impact

Analyzing matches…

Ask about this story

Impact on an agency? Which customers? Compare historically Risks of waiting