Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Certificate Pinning: Pros and Cons

By Kokil Thapa | Last reviewed: September 2026

Certificate pinning: pros and cons sit at the centre of a trade-off every mobile and API team faces. Standard TLS trusts any certificate signed by a public CA in the device trust store. Pinning adds a second check: your app accepts only specific public keys or certificates for your domain. That can block sophisticated man-in-the-middle attacks. It can also take your app offline when a cert rotates unexpectedly. This guide walks through how pinning works, where it helps, and where the operational pain outweighs the security gain—grounded in patterns from production TLS deployments and client integrations.

What is certificate pinning and how does it work?

Certificate pinning (often called SSL pinning or public key pinning) tells a client to trust only a predefined set of cryptographic identities for a host. Instead of accepting any valid chain from a trusted CA, the client compares the server’s leaf certificate or public key against a hard-coded or shipped allowlist.

Three pin types appear in real projects. Each has different rotation behaviour.

  • Certificate pinning — match the entire leaf X.509 certificate. Most brittle; any reissue breaks clients.
  • Public key (SPKI) pinning — match the Subject Public Key Info hash. Survives reissue if you reuse the same key pair.
  • Intermediate CA pinning — pin an issuing CA. Broader trust; weaker than leaf pinning but easier to rotate leaf certs.

On a production Laravel API I maintain, clients connect over HTTPS with a standard chain. Pinning would add a client-side hash check after the TLS handshake completes. The server does not know pinning is active—the enforcement lives entirely in the mobile app or SDK. That asymmetry matters when you debug “works in browser, fails in app” tickets.

Standard TLS vs Certificate PinningMobile AppClientTLS HandshakeServer presents chainAPI ServerLaravel / RESTStandard TLS PathTrust any public CA in storeChain must validate to rootPinned PathSPKI hash must match allowlistMismatch = hard connection failPinning adds client-side identity lock after CA validationServer unchanged — enforcement is entirely in the app
Certificate pinning adds a second validation step after the normal TLS handshake and CA chain check.

The deprecated browser mechanism HTTP Public Key Pinning (HPKP) tried to push pinning via response headers. Chrome removed HPKP in 2018. Firefox never shipped it widely. Pinning today lives mainly in native mobile apps, desktop clients, IoT firmware, and some SDKs—not in public websites. If you read older posts about HPKP, treat them as historical context. Modern browser security relies on Certificate Transparency, CT enforcement, and built-in CA programmes instead.

For background on what gets pinned, see the anatomy of an X.509 certificate and how the certificate chain of trust is assembled. Pinning typically targets the leaf SPKI or a known intermediate—not the root, which would be too broad to add value.

What are the main pros of certificate pinning?

Pinning exists because CA-based trust has real failure modes. A compromised CA, a mis-issued certificate, or a device with a user-installed rogue root can all produce a “valid” chain that points at an attacker’s server. Pinning closes that gap for clients you control.

Stronger protection against MITM on untrusted networks

On coffee-shop Wi-Fi, airport hotspots, or compromised ISP paths, an attacker with a fraudulent but CA-trusted cert can intercept traffic. A pinned app rejects that cert even if the OS trust store accepts it. For legal-tech portals and payment flows I have worked on, that extra layer matters when users handle sensitive documents on mobile networks.

Defence when a CA or intermediate is misused

Public CAs issue millions of certificates. Occasional mis-issuance happens. Pinning to your known SPKI means only your legitimate key works—not a substitute cert from another CA. This is niche but real for high-value targets: banking apps, enterprise VPN clients, government-adjacent services.

Visibility into unexpected certificate changes

When pinning fails in telemetry, you often learn about a cert change before users report vague “network error” messages. Teams that monitor pin failure rates catch CDN migrations, accidental wildcard swaps, and staging cert leaks early. Pair this with automated certificate rotation on the server side so changes are predictable.

Compliance and client expectations

Some security questionnaires and mobile app review processes still ask about pinning. Documenting SPKI pins with a rotation runbook satisfies auditors even when pinning is not strictly required. For API development projects serving financial or legal data, clients sometimes mandate it in the RFP.

Pin Types ComparedLeaf Cert PinExact X.509 matchBreaks on every reissueHighest riskSPKI PinPublic key hashSurvives cert renewalRecommendedCA PinIntermediate issuerEasier leaf rotationWeaker MITM blockBest Practice: Pin 2+ SPKI hashes (primary + backup)Primary = current production keyBackup = next rotation key pre-shipped in appNever pin only one hash with no fallback
SPKI public key pinning is the most common production choice because it survives certificate renewal when the key pair is reused.

What are the cons and risks of certificate pinning?

The cons side of certificate pinning: pros and cons is where most production incidents originate. Pinning shifts trust from a managed PKI ecosystem to your release pipeline. Get the pipeline wrong and you brick clients until they update from the app store.

Certificate rotation becomes a coordinated release event

Let's Encrypt certs expire every 90 days. Many teams automate renewal with Certbot or ACME on Ubuntu. If you pin the leaf certificate and Certbot generates a new key pair, every pinned app fails immediately. Even SPKI pinning fails when you rotate keys—which you should do periodically. I have seen staging environments pass while production mobile builds fail because QA used an unpinned debug build.

No graceful degradation

Unlike HSTS or CT logs, pinning offers no in-band recovery. The connection fails hard. Users see a generic network error. Support teams cannot fix it server-side. You must ship an app update or push new pins through a remote config channel you built in advance.

Breaks corporate inspection and debugging

Enterprises terminate TLS on internal proxies using custom roots. Browsers trust the corporate root; pinned apps do not. Your app may work for consumers but fail inside a bank’s network. Document this trade-off before pinning a B2B API consumed on corporate devices.

False sense of security on web properties

Pinning does not protect against compromised app binaries, jailbroken devices with hooking frameworks, or server-side breaches. It addresses one threat model: fraudulent certs on the wire. Phishing, XSS, and stolen tokens remain unchanged. Teams sometimes over-invest in pinning while neglecting API rate limiting and server-side validation.

Operational cost and key-person risk

Someone must extract SPKI hashes, embed them in iOS and Android builds, maintain backup pins, and run rotation drills. On small teams—common for Nepal SMB clients—that overhead often exceeds the threat they face. A well-maintained TLS stack with short-lived certs and monitoring may be enough.

Pin Rotation Failure TimelineDay 0Cert renewsMinute 1Pin mismatchHour 1All apps downDay 3+Store approvalOutage Window: Server OK, Clients Reject ConnectionBrowser users unaffected — only pinned native clients failFix requires app release or pre-built backup pinPrevention: Ship backup SPKI before rotationRun rotation drill in staging with pinned QA buildsMonitor pin failure metrics in crash reporting
A certificate rotation without a pre-shipped backup pin can leave pinned mobile clients offline until an app store update propagates.

When should you use certificate pinning vs standard TLS?

Not every project needs pinning. Use this decision framework before adding it to a roadmap.

ScenarioStandard TLSCertificate Pinning
Public marketing website (WordPress, Laravel Blade)Yes — browsers deprecated HPKPNo — no client to pin in
Consumer mobile app (payments, PII)Baseline onlyConsider SPKI pinning + backup pin
Internal admin panel on trusted networkYesRarely worth the cost
Third-party API consumed by many integratorsYes — pinning breaks partnersNo on public API surface
IoT firmware with long update cyclesRisky aloneOften required — plan years ahead
Legal-tech client portal (web only)Yes + HSTS + CT monitoringOnly if native app exists

For most web development projects I deliver—law firm portals, booking systems, WooCommerce stores—standard TLS with automated renewal, strong cipher suites, and HSTS is sufficient. Pinning enters the picture when the client ships a native app that stores session tokens locally and calls a proprietary API.

Projects like secure client portals with document sharing rely on server-side auth, short session lifetimes, and HTTPS everywhere. Pinning the web app is impossible in practice. Pinning the companion mobile app may help if one exists and handles sensitive uploads on public Wi-Fi.

Compare this to PKI and certificate management basics: your CA choice, renewal automation, and chain completeness matter more for 90% of sites than any pin configuration.

Should You Pin? Decision FlowNative client you control?NoYesSkip pinningUse TLS + HSTS + CTHigh-value target?Payments / PII / legalNoYesRotation runbook?Backup pin ready?Pin SPKI2+ hashes requiredDefer — fix ops firstYes
Use certificate pinning only when you control the client, face a real MITM threat, and have rotation tooling ready.

How do you implement certificate pinning safely in production?

If the decision tree points to pinning, treat it as infrastructure—not a one-line library call. The implementation details differ by platform, but the operational pattern is the same.

Extract SPKI hashes from your live certificate

OpenSSL can print the base64 SPKI hash Android and many libraries expect. Run this against your production leaf cert or live host:

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 \
  | openssl enc -base64

Verify the output with a standalone Base64 encoder/decoder tool if you store hashes in config files. Document the primary and backup hashes in your internal runbook—not in public repos.

Android: Network Security Config

Android 7+ supports pinning via XML without third-party libraries. Place rules in res/xml/network_security_config.xml and reference it from the manifest:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <domain-config>
    <domain includeSubdomains="true">api.example.com</domain>
    <pin-set expiration="2027-01-01">
      <pin digest="SHA-256">PRIMARY_SPKI_HASH=</pin>
      <pin digest="SHA-256">BACKUP_SPKI_HASH=</pin>
    </pin-set>
  </domain-config>
</network-security-config>

Google’s Network Security Configuration guide documents pin-set behaviour and expiration attributes. Always ship two pins minimum.

iOS: URLSession and TrustKit

Apple’s URLSession delegate allows custom server trust evaluation. Many teams use the open-source TrustKit library to avoid hand-rolling delegate code. Pin SPKI hashes in your Info.plist or TrustKit config. Apple’s Certificate, Key, and Trust Services documentation covers the underlying SecTrust APIs.

Server-side preparation on Ubuntu

Before pinning, stabilise your TLS pipeline. On servers I administer, Certbot on Ubuntu handles ACME renewal with deploy hooks that reload PHP-FPM after cert swap. See installing SSL certificates on Ubuntu for the baseline setup. Use --reuse-key or equivalent when you need the same key pair across renewals and your pin targets SPKI.

certbot certonly --webroot -w /var/www/html \
  -d api.example.com \
  --reuse-key \
  --deploy-hook "systemctl reload php8.3-fpm"

Coordinate with Linux system administration if multiple services share a cert or if a CDN terminates TLS at the edge. Pin the identity your client actually sees—often the CDN cert, not the origin.

Rotation runbook (non-negotiable)

  1. Generate the new key pair and cert on staging; extract the new SPKI hash.
  2. Release an app update that adds the new hash as a backup pin while keeping the old primary.
  3. Wait until 95%+ of active users are on the new build (check analytics).
  4. Switch production to the new cert/key on the server.
  5. Release a follow-up app update that promotes the new hash to primary and drops the old one.
  6. Document the cycle in your support and maintenance playbook.

OWASP’s Certificate and Public Key Pinning guidance describes this backup-pin pattern in detail. Skip any step and you risk a multi-day outage.

Alternatives worth considering first

Before committing to pinning, evaluate:

  • Certificate Transparency monitoring — alert when a new cert appears for your domain.
  • CAA DNS records — restrict which CAs may issue for your zone.
  • Mutual TLS (mTLS) — client certificates for B2B APIs instead of public-key pinning.
  • Short-lived tokens + cert-bound channels — reduce value of intercepted sessions.

For Nepal-specific digital identity workflows, read about digital signature certificates for web apps. That is a different PKI use case—signing documents, not TLS transport pinning—but the cert lifecycle lessons overlap.

Generate strong keys for any test fixtures with a password and key generator. Never commit production private keys or pin hashes tied to dev-only self-signed certs.

Key Takeaways

  • Certificate pinning adds a client-side allowlist on top of normal CA validation—it blocks rogue certs but breaks on rotation without planning.
  • Prefer SPKI (public key) pins over leaf certificate pins, and always ship at least two hashes (primary + backup).
  • Do not pin public websites; HPKP is dead in browsers. Pinning targets native apps, SDKs, and firmware you control.
  • Automate cert renewal with key reuse or a documented rotation runbook before enabling pins in production.
  • For most Laravel, WordPress, and API projects, strong TLS + HSTS + CT monitoring delivers better ROI than pinning.
  • Test pinned builds in staging QA—not just debug builds—before every certificate change.

People Also Ask

For native mobile apps handling sensitive data, SPKI pinning with backup pins remains a valid defence-in-depth measure. For public websites and browser-based apps, no—HPKP was removed from Chrome and pinning provides no benefit when you do not control the client binary.

What happens if certificate pinning fails?

The TLS connection is aborted before any HTTP request completes. Users typically see a network or SSL error with no actionable message. The fix requires an app update with correct pins or a pre-shipped backup pin that already matches the new server key.

Is certificate pinning the same as SSL pinning?

Yes. SSL pinning, TLS pinning, and public key pinning refer to the same concept with slightly different emphasis. Engineers usually mean SPKI hash pinning when they say "SSL pinning" in mobile contexts.

Does Let's Encrypt work with certificate pinning?

It works if you pin SPKI hashes and reuse the key pair across renewals using Certbot's --reuse-key flag. Pinning the full leaf certificate fails every 90 days because Let's Encrypt always reissues the cert file even when the key stays the same.

Make the right call for your stack

Certificate pinning: pros and cons are not abstract—they depend on whether you ship native clients, how often certs rotate, and whether your team can run a rotation drill without panic. Pinning earns its keep on high-risk mobile apps with mature release pipelines. For most web platforms, invest first in automated TLS, chain correctness, and monitoring.

If you are planning a mobile app plus API and want help designing the TLS and pinning strategy before launch, contact us to review your architecture. For broader context on my approach to secure delivery, see about me or browse the blog archive for related PKI and DevOps guides.

Frequently Asked Questions

Certificate pinning tells a client to trust only predefined cryptographic identities for a host—not every valid CA-signed chain. After the normal TLS handshake, the app compares the server’s leaf certificate or public key against a hard-coded or shipped allowlist. Enforcement lives entirely in the mobile app or SDK; the server does not know pinning is active.

For native mobile apps handling sensitive data, SPKI pinning with backup pins remains valid defence-in-depth. For public websites and browser apps, no—HPKP was removed from Chrome in 2018 and pinning provides no benefit when you do not control the client binary.

The TLS connection aborts before any HTTP request completes. Users see a generic network or SSL error. There is no in-band recovery—you must ship an app update with correct pins or rely on a pre-shipped backup pin matching the new server key.

Pinning closes gaps in CA-based trust. On untrusted networks like coffee-shop Wi-Fi, a pinned app rejects fraudulent but CA-trusted certificates that the OS would accept. It also defends against CA mis-issuance by accepting only your known SPKI, gives telemetry visibility when certs change unexpectedly, and satisfies security questionnaires or RFP requirements for financial and legal data apps. SPKI public key pinning is the most common production choice because it survives certificate renewal when the key pair is reused.

Most production incidents come from the cons side. Certificate rotation becomes a coordinated release event—Let’s Encrypt certs expire every 90 days, and pinning the leaf or rotating keys breaks every pinned client immediately. There is no graceful degradation; support cannot fix it server-side. Pinning breaks corporate TLS inspection proxies, creates a false sense of security against app compromise or server breaches, and adds operational overhead that small teams often cannot sustain.

Certificate pinning matches the entire leaf X.509 certificate—the most brittle approach, since any reissue breaks clients. Public key (SPKI) pinning matches the Subject Public Key Info hash and survives reissue if you reuse the same key pair. Intermediate CA pinning trusts an issuing CA—broader and easier to rotate leaf certs but weaker than leaf pinning. In production, SPKI pinning is preferred because it balances security with more manageable renewal when keys are reused via Certbot’s --reuse-key option.

Use standard TLS for public marketing websites, WordPress or Laravel Blade sites, internal admin panels on trusted networks, and third-party APIs consumed by many integrators. Consider SPKI pinning plus a backup pin for consumer mobile apps handling payments or PII, and often for IoT firmware with long update cycles. For most web projects—law firm portals, booking systems, WooCommerce stores—automated renewal, strong cipher suites, HSTS, and Certificate Transparency monitoring deliver better ROI than pinning.

HPKP tried to push pinning via response headers, but Chrome removed it in 2018 and Firefox never shipped it widely. Pinning offers no graceful degradation when pins go wrong—connections fail hard with no in-band recovery. Modern browser security relies on Certificate Transparency enforcement and built-in CA programmes instead. Pinning today lives mainly in native mobile apps, desktop clients, IoT firmware, and SDKs—not public websites. Older posts about HPKP are historical context only.

Android 7 and later supports pinning via Network Security Config XML without third-party libraries. Place rules in res/xml/network_security_config.xml, reference it from the manifest, and define a pin-set with SHA-256 digests for your domain. Google’s Network Security Configuration guide documents pin-set behaviour and expiration attributes. Always ship two pins minimum—a primary and a backup hash. Pin the identity your client actually sees, which is often a CDN certificate rather than your origin server cert.

Apple’s URLSession delegate allows custom server trust evaluation, and many teams use the open-source TrustKit library to avoid hand-rolling delegate code. Pin SPKI hashes in your Info.plist or TrustKit config. Apple’s Certificate, Key, and Trust Services documentation covers the underlying SecTrust APIs. As on Android, ship at least two hashes and test pinned release builds in staging—not just unpinned debug builds, which is a common reason QA passes while production mobile builds fail after a cert change.

Use OpenSSL against your production leaf cert or live host: connect with openssl s_client, pipe the public key through pkey and dgst to produce the base64 SHA-256 SPKI hash Android and most libraries expect. Verify output with a standalone Base64 encoder if you store hashes in config files. Document primary and backup hashes in an internal runbook—not in public repos. Never commit production private keys or pin hashes tied to dev-only self-signed certificates used in local staging.

Follow a non-negotiable backup-pin rotation runbook. Generate the new key pair and cert on staging, extract the new SPKI hash, then release an app update adding the new hash as backup while keeping the old primary. Wait until 95% or more of active users are on the new build, switch production to the new cert, then release a follow-up update promoting the new hash to primary and dropping the old one. OWASP’s Certificate and Public Key Pinning guidance describes this pattern. Skip any step and you risk a multi-day outage.

No, not in practice for the web app itself. Browsers deprecated HPKP, so there is no client binary to pin for public websites. For most Laravel, WordPress, and WooCommerce projects, standard TLS with automated Certbot renewal, strong cipher suites, and HSTS is sufficient. Pinning enters the picture only when the client ships a native app that stores session tokens locally and calls a proprietary API. A companion mobile app handling sensitive uploads on public Wi-Fi may benefit; the web portal relies on server-side auth and HTTPS everywhere.

Before committing to pinning, evaluate Certificate Transparency monitoring to alert when new certs appear for your domain, CAA DNS records to restrict which CAs may issue for your zone, mutual TLS with client certificates for B2B APIs, and short-lived tokens plus cert-bound channels to reduce the value of intercepted sessions. For most API and web development projects, a well-maintained TLS stack with short-lived certs and monitoring may be enough without the release-pipeline fragility pinning introduces on small teams.

Yes, often. Enterprises terminate TLS on internal proxies using custom roots installed on managed devices. Browsers trust the corporate root; pinned apps do not, because the proxy presents a different certificate chain than your pinned SPKI hash. Your app may work for consumers on public networks but fail inside a bank’s network. Document this trade-off before pinning a B2B API consumed on corporate devices. Unlike HSTS or CT logs, pinning offers no in-band recovery when the expected identity does not match.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: