muhittincamdali/iOSSecurityTools

GitHub: muhittincamdali/iOSSecurityTools

一套适用于 Apple 平台的生产级安全工具库,集成了加密存储、生物识别、运行时防护和越狱检测等移动应用安全功能。

Stars: 4 | Forks: 0

Swift 6.0 Platform Standard

## 🚀 杀手级功能:Runtime Tamper Defender 军工级防护。`RuntimeDefender` 会主动监控内存和 Swift method swizzling,一旦检测到调试器或越狱钩子,便会立即销毁敏感的 `SecureVault` 数据。 ``` ███████╗███████╗ ██████╗██╗ ██╗██████╗ ██╗████████╗██╗ ██╗ ██╔════╝██╔════╝██╔════╝██║ ██║██╔══██╗██║╚══██╔══╝╚██╗ ██╔╝ ███████╗█████╗ ██║ ██║ ██║██████╔╝██║ ██║ ╚████╔╝ ╚════██║██╔══╝ ██║ ██║ ██║██╔══██╗██║ ██║ ╚██╔╝ ███████║███████╗╚██████╗╚██████╔╝██║ ██║██║ ██║ ██║ ╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ iOS Security Tools ```

Swift 5.9+ iOS 15+ SPM MIT License

适用于 iOS 应用的生产级安全工具包
加密 • Keychain • 生物识别 • Certificate Pinning • Secure Enclave

## 📋 目录 - [安全功能矩阵](#-security-features-matrix) - [安全架构](#-security-architecture) - [安装说明](#installation) - [使用方法](#usage) - [文档](#documentation) - [贡献指南](#contributing) - [许可证](#license) - [Star 历史](#-star-history) ## 🛡️ 安全功能矩阵 | 功能 | 描述 | iOS 版本 | 安全级别 | |---------|-------------|:-----------:|:--------------:| | **Keychain Services** | 安全的凭证与密钥存储 | iOS 2.0+ | 🔐 硬件 | | **生物识别认证** | Face ID / Touch ID 集成 | iOS 8.0+ | 🔐 硬件 | | **AES-256 加密** | 用于静态数据的对称加密 | iOS 2.0+ | ⚡ 软件 | | **RSA 加密** | 用于密钥交换的非对称加密 | iOS 2.0+ | ⚡ 软件 | | **Certificate Pinning** | SSL/TLS 中间人(MITM)防护 | iOS 7.0+ | 🌐 网络 | | **Secure Enclave** | 硬件隔离的密钥操作 | iOS 9.0+ | 🔒 硬件 | | **JWT 处理** | Token 生成与验证 | iOS 13.0+ | 🎫 Token | | **TOTP/HOTP** | 双因素认证验证码 | iOS 13.0+ | 🔑 2FA | ## 🔐 安全架构 ``` graph TD subgraph User Layer A[👤 User Data] B[🔑 Credentials] end subgraph Security Layer C{AES-256
Encryption} D[🔒 Keychain
Services] E{Biometric
Gate} end subgraph Hardware Layer F[💎 Secure
Enclave] G[✅ Authorized
Access] H[🚫 Access
Denied] end A --> C B --> C C -->|Encrypted| D D --> E E -->|Face ID ✓| F E -->|Touch ID ✓| F E -->|Failed| H F --> G style A fill:#e1f5fe style B fill:#e1f5fe style C fill:#fff3e0 style D fill:#e8f5e9 style E fill:#fce4ec style F fill:#f3e5f5 style G fill:#c8e6c9 style H fill:#ffcdd2 ``` ## 📦 安装说明 ### Swift Package Manager 添加到你的 `Package.swift` 中: ``` dependencies: [ .package(url: "https://github.com/muhittincamdali/iOSSecurityTools.git", from: "1.0.0") ] ``` 或者在 Xcode 中:**File → Add Package Dependencies** → 粘贴 URL。 ## 🚀 快速开始 ``` import iOSSecurityTools // Initialize let security = iOSSecurityTools.shared security.initialize() // Check security status let status = security.getSecurityStatus() print("Biometrics available: \(status.biometricAvailable)") print("Keychain ready: \(status.keychainAvailable)") ``` ## 📚 功能与示例 ### 🔒 Keychain Services 通过硬件级加密,将敏感数据安全地存储在 iOS Keychain 中。 ``` let keychain = KeychainManager.shared // Save with automatic encryption try keychain.save("api_secret_token_xyz", forKey: "apiToken") // Retrieve securely if let token: String = try keychain.get(forKey: "apiToken") { print("Token retrieved") } // Save with biometric protection try keychain.save( sensitiveData, forKey: "protectedSecret", accessibility: .whenPasscodeSetThisDeviceOnly, flags: [.biometryCurrentSet] ) // Delete when done try keychain.delete(forKey: "apiToken") ``` ### 🔐 AES-256 加密 用于静态数据的军工级对称加密。 ``` let aes = AESEncryption.shared // Generate a secure 256-bit key let key = aes.generateKey(bits: 256) // Encrypt sensitive data let plaintext = "Social Security: 123-45-6789" let encrypted = try aes.encrypt(plaintext.data(using: .utf8)!, with: key) // Decrypt when needed let decrypted = try aes.decrypt(encrypted, with: key) let original = String(data: decrypted, encoding: .utf8) ``` ### 👆 生物识别认证 无缝集成 Face ID 与 Touch ID。 ``` let biometrics = BiometricAuth.shared // Check what's available switch biometrics.biometricType { case .faceID: print("Face ID ready") case .touchID: print("Touch ID ready") case .none: print("Fallback to passcode") } // Authenticate user biometrics.authenticate(reason: "Access your vault") { result in switch result { case .success: self.unlockSensitiveContent() case .failure(let error): self.handleAuthError(error) } } // Modern async/await func authenticateUser() async throws -> Bool { return try await biometrics.authenticate(reason: "Verify your identity") } ``` ### 🌐 Certificate Pinning 防御中间人攻击(MITM)。 ``` // Configure pinned certificates let pins = CertificatePins( domain: "api.yourapp.com", hashes: [ "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", "sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=" ] ) // Create pinned session let session = PinnedURLSession(pins: [pins]) // All requests are now protected let (data, response) = try await session.data(from: apiURL) ``` ### 🎫 JWT Token 管理 生成并验证 JSON Web Token。 ``` let jwt = JWTManager.shared // Create a signed token let payload = JWTPayload( sub: "user_12345", exp: Date().addingTimeInterval(3600), customClaims: ["role": "admin"] ) let token = try jwt.sign(payload, algorithm: .hs256, secret: signingKey) // Validate incoming tokens let verified = try jwt.verify(incomingToken, secret: signingKey) if verified.isExpired { throw AuthError.tokenExpired } ``` ### 🔑 TOTP 双因素认证 生成兼容 Google Authenticator 的基于时间的一次性密码。 ``` let otp = OTPGenerator.shared // Generate secret for new user let secret = otp.generateSecret() // Store this in Keychain, show QR code to user // Generate current TOTP code let code = otp.generateTOTP(secret: secret) print("Current code: \(code)") // "847293" // Verify user-entered code let isValid = otp.verify(code: userInput, secret: secret) ``` ### 🔒 Secure Enclave 硬件隔离的加密操作(iPhone 5s+)。 ``` let enclave = SecureEnclaveManager.shared // Generate key pair inside Secure Enclave // Private key NEVER leaves the hardware let keyPair = try enclave.generateKeyPair( tag: "com.app.signing", accessControl: .biometryAny ) // Sign data with hardware-protected key let signature = try enclave.sign( data: documentHash, keyTag: "com.app.signing" ) // Verify signature let isValid = try enclave.verify( signature: signature, for: documentHash, keyTag: "com.app.signing" ) ``` ### 📁 安全文件存储 带有自动密钥管理的加密文件存储。 ``` let storage = SecureStorage.shared // Save encrypted file let document = sensitiveDocument.data(using: .utf8)! try storage.save(document, filename: "medical_records.enc") // Read and decrypt let decrypted = try storage.load(filename: "medical_records.enc") // Secure delete (overwrites before deletion) try storage.secureDelete(filename: "medical_records.enc") ``` ### 🔍 安全审计 运行时安全扫描与越狱检测。 ``` let scanner = SecurityScanner.shared // Run comprehensive audit let audit = try await scanner.performAudit() // Check results if audit.isJailbroken { // Device compromised - restrict sensitive features disableSensitiveOperations() } if audit.debuggerAttached { // Potential reverse engineering attempt logSecurityEvent(.debuggerDetected) } // Check all vulnerabilities for vulnerability in audit.vulnerabilities { print("⚠️ \(vulnerability.severity): \(vulnerability.description)") } ``` ## 🏗️ 架构 ``` iOSSecurityTools/ ├── Sources/ │ ├── Authentication/ │ │ ├── BiometricAuth.swift # Face ID / Touch ID │ │ ├── JWTManager.swift # JWT handling │ │ ├── OTPGenerator.swift # TOTP/HOTP codes │ │ └── OAuthManager.swift # OAuth 2.0 flows │ ├── Encryption/ │ │ └── AESEncryption.swift # AES-256-GCM │ ├── KeyManagement/ │ │ ├── KeychainManager.swift # Keychain wrapper │ │ ├── KeyGenerator.swift # Secure key generation │ │ ├── KeyRotation.swift # Automatic rotation │ │ └── CertificateManager.swift # Cert pinning │ ├── SecureStorage/ │ │ ├── SecureStorage.swift # Encrypted files │ │ └── FileEncryption.swift # File-level crypto │ ├── SecurityMonitoring/ │ │ ├── SecurityScanner.swift # Jailbreak detection │ │ └── AuditLogger.swift # Security logging │ └── Core/ │ └── iOSSecurityTools.swift # Main interface ├── Examples/ │ └── SecurityDemo/ # Sample app ├── Tests/ │ └── iOSSecurityToolsTests/ # Unit tests └── Documentation/ # DocC docs ``` ## ✅ 安全最佳实践 ### 推荐做法 ✓ | 实践 | 实现方式 | |----------|----------------| | **将密钥存储在 Keychain 中** | 切勿使用 `UserDefaults` 存储敏感数据 | | **使用 Secure Enclave** | 在受支持的设备上通过硬件保护签名密钥 | | **实施 Certificate Pinning** | 防止 API 调用遭受 MITM 攻击 | | **启用数据保护** | 对敏感文件使用 `.completeFileProtection` | | **加盐密码哈希** | 配合 bcrypt/Argon2 使用唯一的盐值 | | **定期轮换密钥** | 实施自动化的密钥轮换 | | **记录安全事件** | 提供合规性审计追踪 | ### 禁止行为 ✗ | 反面模式 | 风险 | |--------------|------| | ❌ 硬编码 API 密钥 | 容易通过逆向工程提取 | | ❌ 使用 HTTP 传输敏感数据 | 容易遭受流量拦截 | | ❌ 使用 MD5/SHA1 处理密码 | 容易遭受彩虹表攻击 | | ❌ 忽略越狱状态 | 安全控制机制会被绕过 | | ❌ 长期有效的 Token | 延长了攻击时间窗口 | | ❌ 禁用 ATS | 失去传输层安全防护 | ## 🔒 数据流 ``` sequenceDiagram participant U as User participant A as App participant K as Keychain participant E as Secure Enclave participant S as Server U->>A: Login Request A->>K: Retrieve stored credentials K-->>A: Encrypted credentials A->>E: Decrypt with biometrics E->>U: Face ID prompt U-->>E: Biometric verified E-->>A: Decrypted credentials A->>S: Authenticate (TLS + Pinning) S-->>A: JWT Token A->>K: Store token securely A-->>U: Login successful ``` ## 📋 环境要求 | 要求 | 最低版本 | |-------------|---------| | iOS | 15.0+ | | Xcode | 15.0+ | | Swift | 5.9+ | | Secure Enclave | iPhone 5s+ (A7 芯片) | ## 🧪 测试 ``` # 运行所有测试 swift test # 运行覆盖率测试 swift test --enable-code-coverage # 测试特定模块 swift test --filter KeychainTests ``` ## 📖 文档 完整文档可在 `Documentation/` 文件夹中查看: - [加密指南](Documentation/EncryptionGuide.md) - [Keychain 最佳实践](Documentation/KeychainGuide.md) - [生物识别集成](Documentation/BiometricGuide.md) - [Certificate Pinning 设置](Documentation/CertPinningGuide.md) - [安全审计指南](Documentation/SecurityAuditGuide.md) ## 📄 许可证 MIT License - 详情请参阅 [LICENSE](LICENSE)。 ## 👨‍💻 作者 **Muhittin Camdali** ## [![GitHub](https://img.shields.io/badge/GitHub-@muhittincamdali-181717?style=flat&logo=github)](https://github.com/muhittincamdali) [![CI](https://static.pigsec.cn/wp-content/uploads/repos/2026/06/54cefebfee184158.svg)](https://github.com/muhittincamdali/iOSSecurityTools/actions)[![LinkedIn](https://img.shields.io/badge/LinkedIn-muhittincamdali-0A66C2?style=flat&logo=linkedin)](https://linkedin.com/in/muhittincamdali) [![CI](https://static.pigsec.cn/wp-content/uploads/repos/2026/06/54cefebfee184158.svg)](https://github.com/muhittincamdali/iOSSecurityTools/actions)

以安全为核心构建 🛡️

## 📈 Star 历史 Star History Chart
标签:iOS开发, Keychain, Swift, 安全组件, 数据加密, 越狱检测, 防调试