惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
H
Help Net Security
量子位
The Cloudflare Blog
博客园 - Franky
博客园 - 聂微东
博客园 - 司徒正美
Last Week in AI
Last Week in AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Apple Machine Learning Research
Apple Machine Learning Research
宝玉的分享
宝玉的分享
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
有赞技术团队
有赞技术团队
罗磊的独立博客
GbyAI
GbyAI
雷峰网
雷峰网
T
The Blog of Author Tim Ferriss
Martin Fowler
Martin Fowler
S
SegmentFault 最新的问题
美团技术团队
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
U
Unit 42
MongoDB | Blog
MongoDB | Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
🔐 SSL Pinning in Mobile Apps: Android & iOS (Practical Gu...
Armando Picó · 2026-05-05 · via DEV Community

Armando Picón

Unlike Android, where libraries like OkHttp abstract much of the complexity, iOS takes a more low-level approach to networking and security.

This means one thing:

You have more control — but also more responsibility.

In this second part, we’ll explore how SSL pinning is implemented in iOS using two different strategies:

  • Certificate Pinning (.cer)

  • Public Key Pinning (recommended for production)

Both approaches achieve the same goal — trusting only your backend — but they differ significantly in terms of stability, maintainability, and real-world viability.

We’ll also take a step back and look at the bigger picture:

  • When pinning makes sense

  • When it becomes a liability

  • And how it fits into a broader mobile security strategy

Let’s dive in.

🍎 iOS Implementation

iOS is more low-level. You’ll work with:

  • URLSession
  • URLSessionDelegate
  • Security.framework

There are two approaches:


🟢 Approach 1: Certificate Pinning with .cer

This is what your teammate probably mentioned.

🔧 Steps

  1. Export your backend certificate as .cer
  2. Add it to your Xcode project
  3. Compare it at runtime

🧪 Example

class PinningDelegate: NSObject, URLSessionDelegate {

    func urlSession(_ session: URLSession,
                    didReceive challenge: URLAuthenticationChallenge,
                    completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

        guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
              let serverTrust = challenge.protectionSpace.serverTrust,
              let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) else {
            completionHandler(.cancelAuthenticationChallenge, nil)
            return
        }

        let serverCertData = SecCertificateCopyData(serverCertificate) as Data

        guard let localCertPath = Bundle.main.path(forResource: "server", ofType: "cer"),
              let localCertData = try? Data(contentsOf: URL(fileURLWithPath: localCertPath)) else {
            completionHandler(.cancelAuthenticationChallenge, nil)
            return
        }

        if serverCertData == localCertData {
            completionHandler(.useCredential, URLCredential(trust: serverTrust))
        } else {
            completionHandler(.cancelAuthenticationChallenge, nil)
        }
    }
}

Enter fullscreen mode Exit fullscreen mode


⚠️ Downside (critical)

This approach is:

💣 Fragile

  • Certificates expire
  • Renewal changes .cer
  • Your app breaks

👉 You must release a new version of the app


🟡 Approach 2: Public Key Pinning (Recommended)

Instead of comparing full certificates:

👉 Compare public keys

✔️ Advantages

  • Survives certificate renewal
  • More stable in production
  • Equivalent to Android approach

🧪 Conceptual Example

let serverPublicKey = SecCertificateCopyKey(serverCertificate)
let localPublicKey = SecCertificateCopyKey(localCertificate)

// Compare keys or their hashes
// ⚠️ Apple APIs here are verbose and require careful handling.

Enter fullscreen mode Exit fullscreen mode


🧭 Better Option: Use a Library

Instead of manual implementation, use:

  • Alamofire (widely used networking library)

Example

let evaluators: [String: ServerTrustEvaluating] = [
    "api.yourservice.com": PinnedCertificatesTrustEvaluator()
]

let manager = ServerTrustManager(evaluators: evaluators)

let session = Session(serverTrustManager: manager)

Enter fullscreen mode Exit fullscreen mode


🔍 What SSL Pinning DOES NOT Do

Let’s be clear:

Feature Covered by Pinning
Encrypt traffic ✔ (via TLS)
Prevent MITM
Authenticate user
Protect API access
Replace VPN

👉 You still need:

  • JWT / OAuth
  • API Gateway
  • Rate limiting
  • Backend security

⚠️ Real-World Trade-offs

Before adding pinning, ask yourself:

❗ Operational cost

  • Certificate rotation becomes risky
  • You need fallback pins
  • You need monitoring

❗ Release dependency

  • A backend change can break clients instantly

❗ Debugging complexity

  • Harder to inspect traffic (Charles Proxy, etc.)

🧠 When Should You Use It?

Use pinning if:

  • You build fintech / healthcare apps
  • You operate in hostile network environments
  • You have strong DevOps practices

Avoid (or delay) if:

  • You’re building a typical consumer app
  • You don’t control backend infrastructure
  • Your team lacks experience with cert rotation

🧩 Recommended Architecture (No VPN)

Mobile App
   ↓
HTTPS (TLS)
   ↓
API Gateway
   ↓
Authentication (JWT / OAuth)
   ↓
Microservices

Enter fullscreen mode Exit fullscreen mode

Optional hardening:

  • Certificate Pinning 🔐
  • WAF 🛡️
  • Rate limiting 🚦

🧠 Final Thoughts

“SSL pinning” is often mentioned casually, but:

👉 It’s not a silver bullet
👉 It’s not a replacement for authentication
👉 It’s not trivial to maintain

Used correctly, it adds a strong extra layer of defense.

Used blindly, it becomes a production risk.


👋 Closing

If you’re working with Kotlin Multiplatform or shared logic, keep in mind:

  • Pinning is platform-specific
  • You’ll need separate implementations for Android and iOS