Skip to main content
Be Bitwise

Certificate Pinning & TLS

Mobile Cryptographic Implementation · Mobile Application Security track

11 min read

In this module

The CA Trust Model Problem

When a mobile app speaks TLS to a server, it checks the server's certificate against the OS's bundled set of trusted Certificate Authorities (CAs). iOS ships with roughly 150 roots; Android is in the same neighbourhood. Any one of them can mint a certificate for any domain.

That's the structural problem. Any single CA out of those 150+ — breached, coerced, or just clumsy — and an attacker has a valid-looking certificate for your server. The app accepts it because the chain ends at a trusted root.

Real CAs have minted fraudulent certificates for real domains. Government-run CAs in certain jurisdictions have been caught intercepting traffic. Corporate networks routinely jam custom roots into devices to inspect employee HTTPS.

Walk through what happens when the app connects through a proxy holding a certificate from a compromised CA. Both versions of the app run the same chain check, and it passes. Only the pinned one asks a second question.

Certificate pinning fixes this by hard-coding which certificates or keys the app will tolerate, OS trust store opinions be damned.

Pin Types: Certificate vs Public Key

Two flavours, and the choice carries real operational weight.

Certificate Pinning

A certificate pin is a hash (usually SHA-256) of the whole DER-encoded X.509 certificate. The app stores it, and during the TLS handshake hashes whatever the server presents and compares.

The catch: certificates expire, and renewals reshuffle the validity dates, serial number, and signature. The hash changes even if the underlying key pair stays the same. So every renewal becomes an app release race — ship the new pin before the old cert dies.

Public Key (SPKI) Pinning

A public key pin hashes the SubjectPublicKeyInfo (SPKI) structure — the algorithm identifier and the public key, nothing else. No validity dates, no serial, no issuer signature.

Pinning the SPKI means the pin tracks the key pair, not the paperwork around it. Reuse the same key pair across renewals and the pin keeps working. That's a much friendlier operational story than certificate pinning.

SPKI Pinning Resilience

Public key (SPKI) pinning is preferred over certificate pinning because SPKI hashes are stable across certificate renewals. A server operator can renew their certificate with any CA, change validity dates, and update metadata - as long as the same key pair is used, the SPKI hash does not change. This decouples pin rotation from certificate renewal, reducing the risk of bricking deployed apps.

iOS: App Transport Security and Pinning

App Transport Security (ATS)

iOS turns on App Transport Security by default. Every HTTP call has to go HTTPS, TLS 1.2 minimum, with forward secrecy and SHA-256 (or better) signatures. ATS doesn't pin, but it locks the door on the worst TLS misconfigurations before you even start.

NSURLSession Pinning

For custom pinning in iOS, you implement the URLSession:didReceiveChallenge:completionHandler: delegate. The callback fires mid-handshake, handing you the server's certificate chain to examine:

swift
func urlSession(_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (
URLSession.AuthChallengeDisposition,
URLCredential?) -> Void) {
guard let serverTrust = challenge.protectionSpace.serverTrust,
let certificate = SecTrustCopyCertificateChain(
serverTrust)?.first
else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
// SecKeyCopyExternalRepresentation returns the raw key, not the SPKI,
// so prepend the fixed ASN.1 header for your key type before hashing
guard let serverKey = SecCertificateCopyKey(certificate),
let keyData = SecKeyCopyExternalRepresentation(
serverKey, nil) as Data?
else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
let spki = spkiHeaderForKeyType + keyData
let computedHash = Data(SHA256.hash(data: spki))
.base64EncodedString()
// Compare against pinned hashes
if pinnedHashes.contains(computedHash) {
completionHandler(.useCredential,
URLCredential(trust: serverTrust))
} else {
completionHandler(.cancelAuthenticationChallenge, nil)
}
}

TrustKit

TrustKit is an open-source library that takes the rough edges off pinning on iOS. It hooks the TLS validation path lower than the delegate, so pins apply to every connection — including ones made by third-party libraries that never expose a delegate hook. Bonus features: pin expiry, backup pins, and a reporting endpoint for validation failures.

Android: Network Security Config and OkHttp

Network Security Config

Since Android 7.0 (API level 24), Android offers a declarative pinning path through the Network Security Config XML file. No custom code, just configuration — which is why it's the recommended route:

xml
<!-- res/xml/network_security_config.xml -->
<network-security-config>
<domain-config>
<domain includeSubdomains="true">
api.example.com
</domain>
<!-- Pick a date after your next planned release -->
<pin-set expiration="2027-06-01">
<!-- Primary pin (current key) -->
<pin digest="SHA-256">
base64EncodedSPKIHash1=
</pin>
<!-- Backup pin (next key) -->
<pin digest="SHA-256">
base64EncodedSPKIHash2=
</pin>
</pin-set>
</domain-config>
</network-security-config>

The expiration attribute is your safety valve. Past the date, pinning quietly switches off and connections fall back to standard CA validation. Stale pins won't permanently brick the app's connectivity. The flip side: copy a date that's already gone by and you've shipped no pinning at all, so set it relative to your own release schedule.

To get the value for a pin, pull the server's certificate, extract its public key (the SPKI), hash it with SHA-256 and base64 the result:

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

Google's own Network Security Config documentation advises against pinning for most Android apps, because a CA or key change on the server side can cut off every installed copy until users update. If you do pin, always carry a backup pin and an expiry.

OkHttp CertificatePinner

OkHttp is the dominant HTTP client on Android, and its pinning is wired up in code:

kotlin
val client = OkHttpClient.Builder()
.certificatePinner(
CertificatePinner.Builder()
.add("api.example.com",
"sha256/<44-char base64 SPKI hash>") // Primary
.add("api.example.com",
"sha256/<backup SPKI hash>") // Backup
.build())
.build()

OkHttp checks pins against every certificate in the chain, leaf to root. Pin an intermediate CA's key and you keep your protection while letting the leaf rotate freely underneath.

Pin Rotation Strategies

The scariest pinning failure is bricking — the server rotates to a key the app doesn't know about, and every user on the old version loses connectivity until they update. There's no remote fix.

Backup Pins

Always ship at least one backup pin for a key you've generated but not yet deployed. When the primary needs to rotate (compromise or routine), the backup is already trusted across the install base. Generate the backup offline and stash it somewhere boring and locked.

Pin Expiry

Android's Network Security Config supports the expiration attribute, which switches pinning off after a given date. On iOS you build the expiry logic yourself or hand the job to TrustKit. Either way, the safety net is the same: stale pins degrade to standard CA validation rather than dropping connectivity.

Remote Pin Updates

Some apps pull updated pin sets from a trusted server, which lets you rotate pins without shipping a release. You inherit a chicken-and-egg problem — how do you pin the connection that fetches the pins? — and a fresh batch of attack surface to think through. Worth doing, easy to do badly.

Here's the decision an NSC pin-set makes on each connection, with labels standing in for the SPKI hashes. Predict the four verdicts first. The last row is the bricking scenario from the top of this section.

Try itMove today past the expiry date and rerun, then pin R11_KEY (the intermediate) instead of the leaf keys and see which rows change.
C (GCC 9.2.0)

Certificate Transparency on Mobile

Certificate Transparency (CT) runs alongside pinning. Every issued certificate gets logged to an append-only public ledger. A CA mints a fraudulent cert and it shows up in the logs — auditable, undeniable.

Apple requires CT compliance for any certificate iOS will trust. Certificates must carry Signed Certificate Timestamps (SCTs) from approved CT logs, or the connection drops. A rogue CA can't quietly issue a certificate for your domain without leaving a trail.

Android has historically left CT to apps. Android 16 (API level 36) added a <certificateTransparency> element to Network Security Config so an app can switch on platform CT checking for all or some domains; on older releases, third-party libraries fill the gap when you need hard enforcement.

CT and pinning solve different halves of the problem. CT gives you detection of misissuance after the fact; pinning gives you prevention at the moment of attack. Run both — that's defence in depth.

Bypass Techniques

Knowing how pinning gets bypassed is half the job — for testers and defenders both.

Frida

Frida is a runtime instrumentation toolkit that hooks TLS validation functions on the fly. Scripts like frida-ssl-pinning-bypass swap the validation routine for a stub that always returns success. Pinning lives in the app's process, Frida owns that process, end of story.

Objection

Objection wraps Frida with friendlier ergonomics. One command — android sslpinning disable or ios sslpinning disable — and the validation methods are hooked.

Custom CA Injection

Android lets a user or enterprise admin push a custom root CA into the device trust store. Apps targeting API level 24+ ignore user-installed CAs by default and stick to the system trust store. They can opt in through Network Security Config, and debug builds often do exactly that.

iOS makes the user jump through hoops — install a configuration profile, then explicitly enable trust in Settings — but once that's done, any standard NSURLSession code without pinning will trust the custom CA.

Pinning Only Raises the Bar

Certificate pinning does not make interception impossible - it makes it significantly harder. An attacker with root access to the device can bypass application-level pinning using Frida, Objection, or similar tools. Pinning protects against network-level attackers (rogue Wi-Fi, compromised CAs) but not against a fully compromised device. Defence in depth requires combining pinning with tamper detection, root detection, and server-side security measures.

When NOT to Pin

Pinning isn't a free lunch. A few situations where you'd think twice:

Enterprise Environments

Enterprise networks love TLS inspection proxies with custom roots. Pinning breaks those proxies, which means breaking the app for anyone on a corporate network. Enterprise apps often need configurable trust or a managed-environment kill switch.

Debug and Development

Engineers need to look at network traffic. Pinning you can't switch off in debug builds turns Charles Proxy into a wall. Android's Network Security Config has a clean answer here — trust user CAs only in debug builds, leave production locked down.

CDN and Multi-Server Architectures

If the app talks to CDNs or third-party services that rotate certificates on their own schedule, pinning every endpoint turns into a permanent maintenance tax. Pin the endpoints you control, where the security upside actually pays for the work.

Low Update Frequency Apps

Got users who never update? Pinning gets dangerous fast. Any pin rotation that needs an app update strands the laggards. Pin expiry softens the blow, but only when the expiry window is generous enough to cover the slow movers.