swift-security-expert

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Keychain & Security Expert Skill

Keychain & 安全专家技能

Philosophy: Non-opinionated, correctness-focused. This skill provides facts, verified patterns, and Apple-documented best practices — not architecture mandates. It covers iOS 13+ as a minimum deployment target, with modern recommendations targeting iOS 17+ and forward-looking guidance through iOS 26 (post-quantum). Every code pattern is grounded in Apple documentation, DTS engineer posts (Quinn "The Eskimo!"), WWDC sessions, and OWASP MASTG — never from memory alone.
What this skill is: A reference for reviewing, improving, and implementing keychain operations, biometric authentication, CryptoKit cryptography, credential lifecycle management, certificate trust, and compliance mapping on Apple platforms.
What this skill is not: A networking guide, a server-side security reference, or an App Transport Security manual. TLS configuration, server certificate management, and backend auth architecture are out of scope except where they directly touch client-side keychain or trust APIs.

理念: 无主观倾向,以正确性为核心。本技能提供事实、经验证的模式以及Apple官方文档推荐的最佳实践——而非架构强制要求。最低部署目标为iOS 13+,同时提供针对iOS 17+的现代建议,以及面向iOS 26(后量子时代)的前瞻性指导。所有代码模式均基于Apple官方文档、DTS工程师帖子(Quinn "The Eskimo!")、WWDC会议内容以及OWASP MASTG——绝非仅凭记忆生成。
本技能涵盖范围: 用于在Apple平台上审查、改进和实现Keychain操作、生物识别认证、CryptoKit加密、凭证生命周期管理、证书信任以及合规性映射的参考指南。
本技能不涵盖范围: 网络指南、服务端安全参考或App Transport Security手册。除与客户端Keychain或信任API直接相关的内容外,TLS配置、服务端证书管理和后端认证架构均不在范围内。

Decision Tree

决策树

Determine the user's intent, then follow the matching branch. If ambiguous, ask.
                        ┌─────────────────────┐
                        │  What is the task?   │
                        └─────────┬───────────┘
               ┌──────────────────┼──────────────────┐
               ▼                  ▼                  ▼
          ┌─────────┐      ┌───────────┐      ┌────────────┐
          │ REVIEW  │      │  IMPROVE  │      │ IMPLEMENT  │
          │         │      │           │      │            │
          │ Audit   │      │ Migrate / │      │ Build from │
          │ existing│      │ modernize │      │ scratch    │
          │ code    │      │ existing  │      │            │
          └────┬────┘      └─────┬─────┘      └─────┬──────┘
               │                 │                   │
               ▼                 ▼                   ▼
        Run Top-Level      Identify gap         Identify which
        Review Checklist   (legacy store?        domain(s) apply,
        (§ below) against  wrong API?            load reference
        the code.          missing auth?)        file(s), follow
        Flag each item     Load migration +      ✅ patterns.
        as ✅ / ❌ /       domain-specific        Implement with
        ⚠️ N/A.           reference files.       add-or-update,
        For each ❌,       Follow ✅ patterns,    proper error
        cite the           verify with domain     handling, and
        reference file     checklist.             correct access
        and specific                              control from
        section.                                  the start.

确定用户的需求意图,然后遵循对应的分支流程。若意图不明确,请询问用户。
                        ┌─────────────────────┐
                        │  用户的需求是什么?   │
                        └─────────┬───────────┘
               ┌──────────────────┼──────────────────┐
               ▼                  ▼                  ▼
          ┌─────────┐      ┌───────────┐      ┌────────────┐
          │ 审查代码  │      │ 优化改进  │      │ 从零实现  │
          │         │      │           │      │            │
          │ 审计现有│      │ 迁移 / 现代化│      │ 全新构建  │
          │ 代码    │      │ 现有代码   │      │            │
          └────┬────┘      └─────┬─────┘      └─────┬──────┘
               │                 │                   │
               ▼                 ▼                   ▼
        运行顶层审查      识别差距(如旧存储?   确定适用的领域,
        检查清单(见下)    错误API?缺失认证?)  加载参考文件,
        对照代码进行检查。  加载迁移及领域特定的   遵循✅推荐模式。
        标记每个项为✅ / ❌ / 参考文件。           从一开始就采用
        ⚠️ 不适用。         遵循✅推荐模式,      新增或更新的方式,
        对于每个❌项,引用   结合领域特定检查清单   正确的错误处理
        参考文件及具体章节。  进行验证。            和访问控制。

Branch 1 — REVIEW (Audit Existing Code)

分支1 — 审查代码(审计现有代码)

Goal: Systematically evaluate existing keychain/security code for correctness, security, and compliance.
Procedure:
  1. Run the Top-Level Review Checklist (below) against the code under review. Score each item ✅ / ❌ / ⚠️ N/A.
  2. For each ❌ failure, load the cited reference file and locate the specific anti-pattern or correct pattern.
  3. Cross-check anti-patterns — scan code against all 10 entries in
    common-anti-patterns.md
    . Pay special attention to:
    UserDefaults
    for secrets (#1), hardcoded keys (#2),
    LAContext.evaluatePolicy()
    as sole auth gate (#3), ignored
    OSStatus
    (#4).
  4. Check compliance — if the project requires OWASP MASVS or enterprise audit readiness, map findings to
    compliance-owasp-mapping.md
    categories M1, M3, M9, M10.
  5. Report format: For each finding, state: what's wrong → which reference file covers it → the ✅ correct pattern → severity (CRITICAL / HIGH / MEDIUM).
Key reference files for review:
  • Start with:
    common-anti-patterns.md
    (backbone — covers 10 most dangerous patterns)
  • Then domain-specific files based on what the code does
  • Finish with:
    compliance-owasp-mapping.md
    (if compliance is relevant)

目标: 系统性评估现有Keychain/安全代码的正确性、安全性和合规性。
流程:
  1. 运行顶层审查检查清单(如下)对照待审查代码。为每个项评分✅ / ❌ / ⚠️ 不适用。
  2. 对于每个❌项,加载对应的参考文件并定位具体的反模式或正确模式。
  3. 交叉检查反模式 —— 扫描代码以匹配
    common-anti-patterns.md
    中的全部10条内容。需特别注意:使用
    UserDefaults
    存储密钥(第1条)、硬编码密钥(第2条)、仅用
    LAContext.evaluatePolicy()
    作为认证 gate(第3条)、忽略
    OSStatus
    (第4条)。
  4. 合规性检查 —— 如果项目要求符合OWASP MASVS或企业审计标准,将检查结果映射到
    compliance-owasp-mapping.md
    中的M1、M3、M9、M10类别。
  5. 报告格式: 对于每个检查结果,需说明:问题所在 → 对应的参考文件 → ✅ 正确模式 → 严重程度(CRITICAL / HIGH / MEDIUM)。
审查用核心参考文件:
  • 首先:
    common-anti-patterns.md
    (核心文件——涵盖10种最危险的模式)
  • 然后根据代码功能加载领域特定文件
  • 最后:
    compliance-owasp-mapping.md
    (若涉及合规性)

Branch 2 — IMPROVE (Migrate / Modernize)

分支2 — 优化改进(迁移/现代化)

Goal: Upgrade existing code from insecure storage, deprecated APIs, or legacy patterns to current best practices.
Procedure:
  1. Identify the migration type:
    • Insecure storage → Keychain: Load
      migration-legacy-stores.md
      +
      credential-storage-patterns.md
    • Legacy Security framework → CryptoKit: Load
      cryptokit-symmetric.md
      or
      cryptokit-public-key.md
      +
      migration-legacy-stores.md
    • RSA → Elliptic Curve: Load
      cryptokit-public-key.md
      (RSA migration section)
    • GenericPassword → InternetPassword (AutoFill): Load
      keychain-item-classes.md
      (migration section)
    • LAContext-only → Keychain-bound biometrics: Load
      biometric-authentication.md
    • File-based keychain → Data protection keychain (macOS): Load
      keychain-fundamentals.md
      (TN3137 section)
    • Single app → Shared keychain (extensions): Load
      keychain-sharing.md
    • Leaf pinning → SPKI/CA pinning: Load
      certificate-trust.md
  2. Follow the migration pattern in the relevant reference file. Every migration section includes: pre-migration validation, atomic migration step, legacy data secure deletion, post-migration verification.
  3. Run the domain-specific checklist from the reference file after migration completes.
  4. Verify no regressions using guidance from
    testing-security-code.md
    .

目标: 将现有代码从不安全存储、已弃用API或旧模式升级为当前最佳实践。
流程:
  1. 确定迁移类型:
    • 不安全存储 → Keychain:加载
      migration-legacy-stores.md
      +
      credential-storage-patterns.md
    • 旧版Security框架 → CryptoKit:加载
      cryptokit-symmetric.md
      cryptokit-public-key.md
      +
      migration-legacy-stores.md
    • RSA → 椭圆曲线:加载
      cryptokit-public-key.md
      (RSA迁移章节)
    • GenericPassword → InternetPassword(自动填充):加载
      keychain-item-classes.md
      (迁移章节)
    • 仅LAContext → 绑定Keychain的生物识别:加载
      biometric-authentication.md
    • 基于文件的Keychain → 数据保护Keychain(macOS):加载
      keychain-fundamentals.md
      (TN3137章节)
    • 单应用 → 跨应用/扩展共享Keychain:加载
      keychain-sharing.md
    • 证书叶子节点固定 → SPKI/CA固定:加载
      certificate-trust.md
  2. 遵循参考文件中的迁移模式。每个迁移章节均包含:迁移前验证、原子迁移步骤、旧数据安全删除、迁移后验证。
  3. 迁移完成后运行领域特定检查清单
  4. 使用
    testing-security-code.md
    中的指南验证无回归问题

Branch 3 — IMPLEMENT (Build from Scratch)

分支3 — 从零实现(全新构建)

Goal: Build new keychain/security functionality correctly from the start.
Procedure:
  1. Identify which domain(s) the task touches. Use the Domain Selection Guide below.
  2. Load the relevant reference file(s). Follow ✅ code patterns — never deviate from them for the core security logic.
  3. Apply Core Guidelines (below) to every implementation.
  4. Run the domain-specific checklist before considering the implementation complete.
  5. Add tests following
    testing-security-code.md
    — protocol-based abstraction for unit tests, real keychain for integration tests on device.
Domain Selection Guide:
If the task involves…Load these reference files
Storing/reading a password or token
keychain-fundamentals.md
+
credential-storage-patterns.md
Choosing which
kSecClass
to use
keychain-item-classes.md
Setting when items are accessible
keychain-access-control.md
Face ID / Touch ID gating
biometric-authentication.md
+
keychain-access-control.md
Hardware-backed keys
secure-enclave.md
Encrypting / hashing data
cryptokit-symmetric.md
Signing / key exchange / HPKE
cryptokit-public-key.md
OAuth tokens / API keys / logout
credential-storage-patterns.md
Sharing between app and extension
keychain-sharing.md
TLS pinning / client certificates
certificate-trust.md
Replacing UserDefaults / plist secrets
migration-legacy-stores.md
Writing tests for security code
testing-security-code.md
Enterprise audit / OWASP compliance
compliance-owasp-mapping.md

目标: 从一开始就正确构建新的Keychain/安全功能。
流程:
  1. 确定任务涉及的领域。使用下方的领域选择指南。
  2. 加载对应的参考文件。遵循✅代码模式——核心安全逻辑绝不偏离这些模式。
  3. 将核心准则(如下)应用于所有实现
  4. 在完成实现前运行领域特定检查清单
  5. 按照
    testing-security-code.md
    添加测试
    ——单元测试使用基于协议的抽象,设备上的集成测试使用真实Keychain。
领域选择指南:
任务涉及内容…加载对应的参考文件
存储/读取密码或令牌
keychain-fundamentals.md
+
credential-storage-patterns.md
选择使用哪个
kSecClass
keychain-item-classes.md
设置Keychain项的可访问时机
keychain-access-control.md
Face ID / Touch ID 权限控制
biometric-authentication.md
+
keychain-access-control.md
硬件-backed密钥
secure-enclave.md
加密 / 哈希数据
cryptokit-symmetric.md
签名 / 密钥交换 / HPKE
cryptokit-public-key.md
OAuth令牌 / API密钥 / 登出
credential-storage-patterns.md
应用与扩展之间共享
keychain-sharing.md
TLS固定 / 客户端证书
certificate-trust.md
替换UserDefaults / plist中的密钥
migration-legacy-stores.md
为安全代码编写测试
testing-security-code.md
企业审计 / OWASP合规性
compliance-owasp-mapping.md

Core Guidelines

核心准则

These seven rules are non-negotiable. Every keychain/security implementation must satisfy all of them.
1. Never ignore
OSStatus
.
Every
SecItem*
call returns an
OSStatus
. Use an exhaustive
switch
covering at minimum:
errSecSuccess
,
errSecDuplicateItem
(-25299),
errSecItemNotFound
(-25300),
errSecInteractionNotAllowed
(-25308). Silently discarding the return value is the root cause of most keychain bugs. →
keychain-fundamentals.md
2. Never use
LAContext.evaluatePolicy()
as a standalone auth gate.
This returns a
Bool
that is trivially patchable at runtime via Frida. Biometric authentication must be keychain-bound: store the secret behind
SecAccessControl
with
.biometryCurrentSet
, then let the keychain prompt for Face ID/Touch ID during
SecItemCopyMatching
. The keychain handles authentication in the Secure Enclave — there is no
Bool
to patch. →
biometric-authentication.md
3. Never store secrets in
UserDefaults
,
Info.plist
,
.xcconfig
, or
NSCoding
archives.
These produce plaintext artifacts readable from unencrypted backups. The Keychain is the only Apple-sanctioned store for credentials. →
credential-storage-patterns.md
,
common-anti-patterns.md
4. Never call
SecItem*
on
@MainActor
.
Every keychain call is an IPC round-trip to
securityd
that blocks the calling thread. Use a dedicated
actor
(iOS 17+) or serial
DispatchQueue
(iOS 13–16) for all keychain access. →
keychain-fundamentals.md
5. Always set
kSecAttrAccessible
explicitly.
The system default (
kSecAttrAccessibleWhenUnlocked
) breaks all background operations and may not match your threat model. Choose the most restrictive class that satisfies your access pattern. For background tasks:
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
. For highest sensitivity:
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
. →
keychain-access-control.md
6. Always use the add-or-update pattern.
SecItemAdd
followed by
SecItemUpdate
on
errSecDuplicateItem
. Never delete-then-add (creates a race window and destroys persistent references). Never call
SecItemAdd
without handling the duplicate case. →
keychain-fundamentals.md
7. Always target the data protection keychain on macOS. Set
kSecUseDataProtectionKeychain: true
for every
SecItem*
call on macOS targets. Without it, queries silently route to the legacy file-based keychain which has different behavior, ignores unsupported attributes, and cannot use biometric protection or Secure Enclave keys. Mac Catalyst and iOS-on-Mac do this automatically. →
keychain-fundamentals.md

以下七条规则为强制性要求。所有Keychain/安全实现必须全部满足这些规则。
1. 绝不忽略
OSStatus
每个
SecItem*
调用都会返回
OSStatus
。使用详尽的
switch
语句,至少覆盖:
errSecSuccess
errSecDuplicateItem
(-25299)、
errSecItemNotFound
(-25300)、
errSecInteractionNotAllowed
(-25308)。静默丢弃返回值是大多数Keychain bug的根本原因。→
keychain-fundamentals.md
2. 绝不单独使用
LAContext.evaluatePolicy()
作为认证 gate。
该方法返回的
Bool
可通过Frida在运行时轻松绕过。生物识别认证必须与Keychain绑定:将密钥存储在带有
.biometryCurrentSet
SecAccessControl
之后,然后在
SecItemCopyMatching
时由Keychain触发Face ID/Touch ID提示。Keychain在Secure Enclave中处理认证——不存在可被篡改的
Bool
值。→
biometric-authentication.md
3. 绝不将密钥存储在
UserDefaults
Info.plist
.xcconfig
NSCoding
归档中。
这些存储方式会生成明文文件,可从未加密备份中读取。Keychain是Apple唯一认可的凭证存储方案。→
credential-storage-patterns.md
,
common-anti-patterns.md
4. 绝不在
@MainActor
中调用
SecItem*
每个Keychain调用都是与
securityd
的IPC往返,会阻塞调用线程。所有Keychain访问需使用专用
actor
(iOS 17+)或串行
DispatchQueue
(iOS 13–16)。→
keychain-fundamentals.md
5. 始终显式设置
kSecAttrAccessible
系统默认值(
kSecAttrAccessibleWhenUnlocked
)会破坏所有后台操作,且可能不符合你的威胁模型。选择满足访问模式的最严格类别。对于后台任务:
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
。对于最高敏感度数据:
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
。→
keychain-access-control.md
6. 始终使用新增或更新模式。
errSecDuplicateItem
时先调用
SecItemAdd
再调用
SecItemUpdate
。绝不使用删除后新增的方式(会产生竞争窗口并破坏持久引用)。绝不调用
SecItemAdd
而不处理重复项的情况。→
keychain-fundamentals.md
7. 在macOS上始终使用数据保护Keychain。 针对macOS目标的每个
SecItem*
调用都需设置
kSecUseDataProtectionKeychain: true
。若不设置,查询会静默路由到旧版基于文件的Keychain,其行为不同、会忽略不支持的属性,且无法使用生物识别保护或Secure Enclave密钥。Mac Catalyst和iOS-on-Mac会自动处理此设置。→
keychain-fundamentals.md

Quick Reference Tables

快速参考表格

Accessibility Constants — Selection Guide

可访问性常量选择指南

ConstantWhen DecryptableSurvives BackupSurvives Device MigrationBackground SafeUse When
WhenPasscodeSetThisDeviceOnly
Unlocked + passcode setHighest-security secrets; removed if passcode removed
WhenUnlockedThisDeviceOnly
UnlockedDevice-bound secrets not needed in background
WhenUnlocked
UnlockedSyncable secrets (system default — avoid implicit use)
AfterFirstUnlockThisDeviceOnly
After first unlock → restartBackground tasks, push handlers, device-bound
AfterFirstUnlock
After first unlock → restartBackground tasks that must survive restore
Deprecated (never use):
kSecAttrAccessibleAlways
,
kSecAttrAccessibleAlwaysThisDeviceOnly
— deprecated iOS 12.
Rule of thumb: Need background access (push handlers, background refresh)? Start with
AfterFirstUnlockThisDeviceOnly
. Foreground-only? Start with
WhenUnlockedThisDeviceOnly
. Tighten to
WhenPasscodeSetThisDeviceOnly
for high-value secrets. Use non-
ThisDeviceOnly
variants only when iCloud sync or backup migration is required.
常量可解密时机支持备份支持设备迁移后台可用使用场景
WhenPasscodeSetThisDeviceOnly
设备解锁且已设置密码最高安全等级密钥;移除密码时会被删除
WhenUnlockedThisDeviceOnly
设备解锁时设备绑定密钥,后台无需访问
WhenUnlocked
设备解锁时可同步密钥(系统默认值——避免隐式使用)
AfterFirstUnlockThisDeviceOnly
首次解锁后至设备重启前后台任务、推送处理器、设备绑定密钥
AfterFirstUnlock
首次解锁后至设备重启前需在恢复后保留的后台任务密钥
已弃用(绝不使用):
kSecAttrAccessibleAlways
,
kSecAttrAccessibleAlwaysThisDeviceOnly
— iOS 12已弃用。
经验法则: 需要后台访问(推送处理器、后台刷新)?优先选择
AfterFirstUnlockThisDeviceOnly
。仅前台使用?优先选择
WhenUnlockedThisDeviceOnly
。高价值密钥选择
WhenPasscodeSetThisDeviceOnly
。仅当需要iCloud同步或备份迁移时才使用非
ThisDeviceOnly
的变体。

CryptoKit Algorithm Selection

CryptoKit算法选择

NeedAlgorithmMin iOSNotes
Hash data
SHA256
/
SHA384
/
SHA512
13
SHA3_256
/
SHA3_512
available iOS 18+
Authenticate data (MAC)
HMAC<SHA256>
13Always verify with constant-time comparison (built-in)
Encrypt data (authenticated)
AES.GCM
13256-bit key, 96-bit nonce, 128-bit tag. Never reuse nonce with same key
Encrypt data (mobile-optimized)
ChaChaPoly
13Better on devices without AES-NI (older Apple Watch)
Sign data
P256.Signing
/
Curve25519.Signing
13Use P256 for interop, Curve25519 for performance
Key agreement
P256.KeyAgreement
/
Curve25519.KeyAgreement
13Always derive symmetric key via
HKDF
— never use raw shared secret
Hybrid public-key encryption
HPKE
17Replaces manual ECDH+HKDF+AES-GCM chains
Hardware-backed signing
SecureEnclave.P256.Signing
13P256 only; key never leaves hardware
Post-quantum key exchange
MLKEM768
26Formal verification (ML-KEM FIPS 203)
Post-quantum signing
MLDSA65
26Formal verification (ML-DSA FIPS 204)
Password → key derivationPBKDF2 (via
CommonCrypto
)
13≥600,000 iterations SHA-256 (OWASP 2024)
Key → key derivation
HKDF<SHA256>
13Extract-then-expand; always use info parameter for domain separation
需求算法最低iOS版本说明
数据哈希
SHA256
/
SHA384
/
SHA512
13
SHA3_256
/
SHA3_512
在iOS 18+可用
数据认证(MAC)
HMAC<SHA256>
13始终使用内置的恒定时间比较进行验证
数据加密(带认证)
AES.GCM
13256位密钥、96位随机数、128位标签。同一密钥绝不重复使用随机数
数据加密(移动优化)
ChaChaPoly
13在无AES-NI的设备上表现更优(旧款Apple Watch)
数据签名
P256.Signing
/
Curve25519.Signing
13跨平台互操作使用P256,追求性能使用Curve25519
密钥交换
P256.KeyAgreement
/
Curve25519.KeyAgreement
13始终通过
HKDF
派生对称密钥——绝不使用原始共享密钥
混合公钥加密
HPKE
17替代手动ECDH+HKDF+AES-GCM的链式操作
硬件-backed签名
SecureEnclave.P256.Signing
13仅支持P256;密钥绝不会离开硬件
后量子密钥交换
MLKEM768
26已通过正式验证(ML-KEM FIPS 203)
后量子签名
MLDSA65
26已通过正式验证(ML-DSA FIPS 204)
密码转密钥PBKDF2(通过
CommonCrypto
13≥600,000次迭代SHA-256(OWASP 2024标准)
密钥派生
HKDF<SHA256>
13提取-派生流程;始终使用info参数进行领域分隔

Anti-Pattern Detection — Quick Scan

反模式检测快速扫描

When reviewing code, search for these patterns. Any match is a finding.
= insecure pattern signature to detect in user code.
= apply the corrective pattern in the referenced file.
Search ForAnti-PatternSeverityReference
UserDefaults.standard.set
+ token/key/secret/password
Plaintext credential storageCRITICAL
common-anti-patterns.md
#1
Hardcoded base64/hex strings (≥16 chars) in sourceHardcoded cryptographic keyCRITICAL
common-anti-patterns.md
#2
evaluatePolicy
without
SecItemCopyMatching
nearby
LAContext-only biometric gateCRITICAL
common-anti-patterns.md
#3
SecItemAdd
without checking return /
OSStatus
Ignored error codeHIGH
common-anti-patterns.md
#4
No
kSecAttrAccessible
in add dictionary
Implicit accessibility classHIGH
common-anti-patterns.md
#5
AES.GCM.Nonce()
inside a loop with same key
Potential nonce reuseCRITICAL
common-anti-patterns.md
#6
sharedSecret.withUnsafeBytes
without HKDF
Raw shared secret as keyHIGH
common-anti-patterns.md
#7
kSecAttrAccessibleAlways
Deprecated accessibilityHIGH
keychain-access-control.md
SecureEnclave.isAvailable
without
#if !targetEnvironment(simulator)
Simulator false-negative trapMEDIUM
secure-enclave.md
kSecAttrSynchronizable: true
+
ThisDeviceOnly
Contradictory constraintsMEDIUM
keychain-item-classes.md
SecTrustEvaluate
(sync, deprecated)
Legacy trust evaluationMEDIUM
certificate-trust.md
kSecClassGenericPassword
+
kSecAttrServer
Wrong class for web credentialsMEDIUM
keychain-item-classes.md

审查代码时,搜索以下模式。任何匹配项均为问题点。
= 需在用户代码中检测的不安全模式特征。
= 应用参考文件中的修正模式。
搜索内容反模式严重程度参考文件
UserDefaults.standard.set
+ token/key/secret/password
明文凭证存储严重
common-anti-patterns.md
#1
源代码中硬编码的base64/十六进制字符串(≥16字符)硬编码加密密钥严重
common-anti-patterns.md
#2
evaluatePolicy
附近无
SecItemCopyMatching
仅依赖LAContext的生物识别验证严重
common-anti-patterns.md
#3
SecItemAdd
未检查返回值 /
OSStatus
忽略错误代码
common-anti-patterns.md
#4
新增字典中无
kSecAttrAccessible
隐式可访问性类别
common-anti-patterns.md
#5
同一密钥下循环内调用
AES.GCM.Nonce()
潜在随机数重用严重
common-anti-patterns.md
#6
sharedSecret.withUnsafeBytes
未使用HKDF
使用原始共享密钥作为加密密钥
common-anti-patterns.md
#7
kSecAttrAccessibleAlways
已弃用的可访问性类别
keychain-access-control.md
SecureEnclave.isAvailable
未加
#if !targetEnvironment(simulator)
模拟器假阴性陷阱
secure-enclave.md
kSecAttrSynchronizable: true
+
ThisDeviceOnly
矛盾的约束条件
keychain-item-classes.md
SecTrustEvaluate
(同步、已弃用)
旧版信任评估
certificate-trust.md
kSecClassGenericPassword
+
kSecAttrServer
Web凭证使用错误类别
keychain-item-classes.md

Top-Level Review Checklist

顶层审查检查清单

Use this checklist for a rapid sweep across all 14 domains. Each item maps to one or more reference files for deep-dive investigation. For domain-specific deep checks, use the Summary Checklist at the bottom of each reference file.
  • 1. Secrets are in Keychain, not UserDefaults/plist/source — No credentials, tokens, or cryptographic keys in
    UserDefaults
    ,
    Info.plist
    ,
    .xcconfig
    , hardcoded strings, or
    NSCoding
    archives. OWASP M9 (Insecure Data Storage) directly violated. →
    common-anti-patterns.md
    #1–2,
    credential-storage-patterns.md
    ,
    migration-legacy-stores.md
    ,
    compliance-owasp-mapping.md
  • 2. Every
    OSStatus
    is checked
    — All
    SecItem*
    calls handle return codes with exhaustive
    switch
    or equivalent. No ignored returns.
    errSecInteractionNotAllowed
    is handled non-destructively (retry later, never delete). →
    keychain-fundamentals.md
    ,
    common-anti-patterns.md
    #4
  • 3. Biometric auth is keychain-bound — If biometrics are used, authentication is enforced via
    SecAccessControl
    + keychain access, not
    LAContext.evaluatePolicy()
    alone. →
    biometric-authentication.md
    ,
    common-anti-patterns.md
    #3
  • 4. Accessibility classes are explicit and correct — Every keychain item has an explicit
    kSecAttrAccessible
    value matching its access pattern (background vs foreground, device-bound vs syncable). No deprecated
    Always
    constants. →
    keychain-access-control.md
  • 5. No
    SecItem*
    calls on
    @MainActor
    — All keychain operations run on a dedicated
    actor
    or background queue. No synchronous keychain access in UI code,
    viewDidLoad
    , or
    application(_:didFinishLaunchingWithOptions:)
    . →
    keychain-fundamentals.md
  • 6. Correct
    kSecClass
    for each item type
    — Web credentials use
    InternetPassword
    (not GenericPassword) for AutoFill. Cryptographic keys use
    kSecClassKey
    with proper
    kSecAttrKeyType
    . App secrets use
    GenericPassword
    with
    kSecAttrService
    +
    kSecAttrAccount
    . →
    keychain-item-classes.md
  • 7. CryptoKit used correctly — Nonces never reused with the same key. ECDH shared secrets always derived through
    HKDF
    before use as symmetric keys.
    SymmetricKey
    material stored in Keychain, not in memory or files. Crypto operations covered by protocol-based unit tests. →
    cryptokit-symmetric.md
    ,
    cryptokit-public-key.md
    ,
    testing-security-code.md
  • 8. Secure Enclave constraints respected — SE keys are P256 only (classical), never imported (always generated on-device), device-bound (no backup/sync). Availability checks guard against simulator and keychain-access-groups entitlement issues. →
    secure-enclave.md
  • 9. Sharing and access groups configured correctly
    kSecAttrAccessGroup
    uses full
    TEAMID.group.identifier
    format. Entitlements match between app and extensions. No accidental cross-app data exposure. →
    keychain-sharing.md
  • 10. Certificate trust evaluation is current — Uses
    SecTrustEvaluateAsyncWithError
    (not deprecated synchronous
    SecTrustEvaluate
    ). Pinning strategy uses SPKI hash or
    NSPinnedDomains
    (not leaf certificate pinning which breaks on annual rotation). →
    certificate-trust.md
  • 11. macOS targets data protection keychain — All macOS
    SecItem*
    calls include
    kSecUseDataProtectionKeychain: true
    (except Mac Catalyst / iOS-on-Mac where it's automatic). →
    keychain-fundamentals.md

使用此清单快速扫描所有14个领域。每个项均映射到一个或多个参考文件以进行深入调查。若需领域深度检查,请使用每个参考文件底部的摘要检查清单。
  • 1. 密钥存储在Keychain中,而非UserDefaults/plist/源代码 — 凭证、令牌或加密密钥未存储在
    UserDefaults
    Info.plist
    .xcconfig
    、硬编码字符串或
    NSCoding
    归档中。直接违反OWASP M9(不安全数据存储)。→
    common-anti-patterns.md
    #1–2,
    credential-storage-patterns.md
    ,
    migration-legacy-stores.md
    ,
    compliance-owasp-mapping.md
  • 2. 所有
    OSStatus
    均已检查
    — 所有
    SecItem*
    调用均通过详尽的
    switch
    或等效方式处理返回码。无忽略返回值的情况。
    errSecInteractionNotAllowed
    已进行非破坏性处理(稍后重试,绝不删除)。→
    keychain-fundamentals.md
    ,
    common-anti-patterns.md
    #4
  • 3. 生物识别认证与Keychain绑定 — 若使用生物识别,认证通过
    SecAccessControl
    + Keychain访问强制执行,而非仅依赖
    LAContext.evaluatePolicy()
    。→
    biometric-authentication.md
    ,
    common-anti-patterns.md
    #3
  • 4. 可访问性类别显式且正确 — 每个Keychain项均有显式的
    kSecAttrAccessible
    值,与其访问模式匹配(后台 vs 前台、设备绑定 vs 可同步)。无已弃用的
    Always
    常量。→
    keychain-access-control.md
  • 5.
    @MainActor
    中无
    SecItem*
    调用
    — 所有Keychain操作在专用
    actor
    或后台队列上运行。UI代码、
    viewDidLoad
    application(_:didFinishLaunchingWithOptions:)
    中无同步Keychain访问。→
    keychain-fundamentals.md
  • 6. 每个项类型使用正确的
    kSecClass
    — Web凭证使用
    InternetPassword
    (而非GenericPassword)以支持自动填充。加密密钥使用
    kSecClassKey
    并设置正确的
    kSecAttrKeyType
    。应用密钥使用
    GenericPassword
    并设置
    kSecAttrService
    +
    kSecAttrAccount
    。→
    keychain-item-classes.md
  • 7. CryptoKit使用正确 — 同一密钥绝不重复使用随机数。ECDH共享密钥在用作对称密钥前始终通过
    HKDF
    派生。
    SymmetricKey
    材料存储在Keychain中,而非内存或文件中。加密操作由基于协议的单元测试覆盖。→
    cryptokit-symmetric.md
    ,
    cryptokit-public-key.md
    ,
    testing-security-code.md
  • 8. 遵守Secure Enclave约束 — SE密钥仅支持P256(经典算法),绝不导入(始终在设备内生成),设备绑定(无备份/同步)。可用性检查可防范模拟器和keychain-access-groups授权问题。→
    secure-enclave.md
  • 9. 共享和访问组配置正确
    kSecAttrAccessGroup
    使用完整的
    TEAMID.group.identifier
    格式。应用与扩展的授权配置匹配。无意外的跨应用数据暴露。→
    keychain-sharing.md
  • 10. 证书信任评估使用当前API — 使用
    SecTrustEvaluateAsyncWithError
    (而非已弃用的同步
    SecTrustEvaluate
    )。固定策略使用SPKI哈希或
    NSPinnedDomains
    (而非证书叶子节点固定,后者会在年度轮换时失效)。→
    certificate-trust.md
  • 11. macOS目标使用数据保护Keychain — 所有macOS
    SecItem*
    调用均包含
    kSecUseDataProtectionKeychain: true
    (Mac Catalyst / iOS-on-Mac会自动设置此值,除外)。→
    keychain-fundamentals.md

References Index

参考文件索引

#FileOne-Line DescriptionRisk
1
keychain-fundamentals.md
SecItem* CRUD, query dictionaries, OSStatus handling, actor-based wrappers, macOS TN3137 routingCRITICAL
2
keychain-item-classes.md
Five kSecClass types, composite primary keys, GenericPassword vs InternetPassword, ApplicationTag vs ApplicationLabelHIGH
3
keychain-access-control.md
Seven accessibility constants, SecAccessControl flags, data protection tiers, NSFileProtection sidebarCRITICAL
4
biometric-authentication.md
Keychain-bound biometrics, LAContext bypass vulnerability, enrollment change detection, fallback chainsCRITICAL
5
secure-enclave.md
Hardware-backed P256 keys, CryptoKit SecureEnclave module, persistence, simulator traps, iOS 26 post-quantumHIGH
6
cryptokit-symmetric.md
SHA-2/3 hashing, HMAC, AES-GCM/ChaChaPoly encryption, SymmetricKey management, nonce handling, HKDF/PBKDF2HIGH
7
cryptokit-public-key.md
ECDSA signing, ECDH key agreement, HPKE (iOS 17+), ML-KEM/ML-DSA post-quantum (iOS 26+), curve selectionHIGH
8
credential-storage-patterns.md
OAuth2/OIDC token lifecycle, API key storage, refresh token rotation, runtime secrets, logout cleanupCRITICAL
9
keychain-sharing.md
Access groups, Team ID prefixes, app extensions, Keychain Sharing vs App Groups entitlements, iCloud syncMEDIUM
10
certificate-trust.md
SecTrust evaluation, SPKI/CA/leaf pinning, NSPinnedDomains, client certificates (mTLS), trust policiesHIGH
11
migration-legacy-stores.md
UserDefaults/plist/NSCoding → Keychain migration, secure deletion, first-launch cleanup, versioned migrationMEDIUM
12
common-anti-patterns.md
Top 10 AI-generated security mistakes with ❌/✅ code pairs, detection heuristics, OWASP mappingCRITICAL
13
testing-security-code.md
Protocol-based mocking, simulator vs device differences, CI/CD keychain, Swift Testing, mutation testingMEDIUM
14
compliance-owasp-mapping.md
OWASP Mobile Top 10 (2024), MASVS v2.1.0, MASTG test IDs, M1/M3/M9/M10 mapping, audit readinessMEDIUM

序号文件一句话描述风险等级
1
keychain-fundamentals.md
SecItem*增删改查、查询字典、OSStatus处理、基于actor的封装、macOS TN3137路由严重
2
keychain-item-classes.md
五种kSecClass类型、复合主键、GenericPassword vs InternetPassword、ApplicationTag vs ApplicationLabel
3
keychain-access-control.md
七种可访问性常量、SecAccessControl标志、数据保护层级、NSFileProtection对应关系严重
4
biometric-authentication.md
与Keychain绑定的生物识别、LAContext绕过漏洞、注册变更检测、 fallback链严重
5
secure-enclave.md
硬件-backed P256密钥、CryptoKit SecureEnclave模块、持久化、模拟器陷阱、iOS 26后量子支持
6
cryptokit-symmetric.md
SHA-2/3哈希、HMAC、AES-GCM/ChaChaPoly加密、SymmetricKey管理、随机数处理、HKDF/PBKDF2
7
cryptokit-public-key.md
ECDSA签名、ECDH密钥交换、HPKE(iOS 17+)、ML-KEM/ML-DSA后量子(iOS 26+)、曲线选择
8
credential-storage-patterns.md
OAuth2/OIDC令牌生命周期、API密钥存储、刷新令牌轮换、运行时密钥、登出清理严重
9
keychain-sharing.md
访问组、Team ID前缀、应用扩展、Keychain共享 vs App Groups授权、iCloud同步
10
certificate-trust.md
SecTrust评估、SPKI/CA/叶子节点固定、NSPinnedDomains、客户端证书(mTLS)、信任策略
11
migration-legacy-stores.md
UserDefaults/plist/NSCoding → Keychain迁移、旧数据安全删除、首次启动清理、版本化迁移
12
common-anti-patterns.md
十大AI生成的安全错误及❌/✅代码示例、检测启发式、OWASP映射严重
13
testing-security-code.md
基于协议的模拟、模拟器与设备差异、CI/CD Keychain、Swift Testing模式
14
compliance-owasp-mapping.md
OWASP移动Top 10(2024)、MASVS v2.1.0、MASTG测试ID、M1/M3/M9/M10映射、审计准备

Authoritative Sources

权威来源

These are the primary sources underpinning all reference files. When in doubt, defer to these over any secondary source.
  • Apple Keychain Services Documentation — canonical API reference
  • Apple Platform Security Guide (updated annually) — architecture and encryption design
  • TN3137: "On Mac Keychain APIs and Implementations" — macOS data protection vs file-based keychain
  • Quinn "The Eskimo!" DTS Posts — "SecItem: Fundamentals" and "SecItem: Pitfalls and Best Practices" (updated through 2025)
  • WWDC 2019 Session 709 — "Cryptography and Your Apps" (CryptoKit introduction)
  • WWDC 2025 Session 314 — "Get ahead with quantum-secure cryptography" (ML-KEM, ML-DSA)
  • OWASP Mobile Top 10 (2024) + MASVS v2.1.0 + MASTG v2 — compliance framework
  • CISA/FBI "Product Security Bad Practices" v2.0 (January 2025) — hardcoded credentials classified as national security risk

以下是支撑所有参考文件的主要来源。如有疑问,优先参考这些来源而非任何二级来源。
  • Apple Keychain Services文档 — 标准API参考
  • Apple平台安全指南(每年更新) — 架构和加密设计
  • TN3137: "On Mac Keychain APIs and Implementations" — macOS数据保护Keychain vs 基于文件的Keychain
  • Quinn "The Eskimo!"的DTS帖子 — "SecItem: Fundamentals"和"SecItem: Pitfalls and Best Practices"(更新至2025年)
  • WWDC 2019 Session 709 — "Cryptography and Your Apps"(CryptoKit介绍)
  • WWDC 2025 Session 314 — "Get ahead with quantum-secure cryptography"(ML-KEM、ML-DSA)
  • OWASP Mobile Top 10 (2024) + MASVS v2.1.0 + MASTG v2 — 合规框架
  • CISA/FBI "Product Security Bad Practices" v2.0(2025年1月) — 硬编码凭证被归类为国家安全风险

Agent Behavioral Rules

AI Agent行为规则

The sections below govern how an AI agent should behave when using this skill: what's in scope, what's out, tone calibration, common mistakes to avoid, how to select reference files, and output formatting requirements.
以下章节规定了AI Agent使用本技能时的行为方式:涵盖范围、排除范围、语气校准、需避免的常见错误、参考文件选择方式以及输出格式要求。

Scope Boundaries — Inclusions

范围边界 — 包含内容

This skill is authoritative for client-side Apple platform security across iOS, macOS, tvOS, watchOS, and visionOS:
  • Keychain Services
    SecItemAdd
    ,
    SecItemCopyMatching
    ,
    SecItemUpdate
    ,
    SecItemDelete
    , query dictionary construction,
    OSStatus
    handling, actor/thread isolation, the data protection keychain on macOS (TN3137)
  • Keychain item classes
    kSecClassGenericPassword
    ,
    kSecClassInternetPassword
    ,
    kSecClassKey
    ,
    kSecClassCertificate
    ,
    kSecClassIdentity
    , composite primary keys, AutoFill integration
  • Access control — The seven
    kSecAttrAccessible
    constants,
    SecAccessControlCreateWithFlags
    , data protection tiers,
    NSFileProtection
    correspondence
  • Biometric authentication
    LAContext
    + keychain binding, the boolean gate vulnerability, enrollment change detection, fallback chains,
    evaluatedPolicyDomainState
  • Secure Enclave — CryptoKit
    SecureEnclave.P256
    module, hardware constraints (P256-only, no import, no export, no symmetric), persistence via keychain, simulator traps, iOS 26 post-quantum (ML-KEM, ML-DSA)
  • CryptoKit symmetric — SHA-2/SHA-3 hashing, HMAC, AES-GCM, ChaChaPoly,
    SymmetricKey
    lifecycle, nonce handling, HKDF, PBKDF2
  • CryptoKit public-key — ECDSA signing (P256/Curve25519), ECDH key agreement, HPKE (iOS 17+), ML-KEM/ML-DSA (iOS 26+), curve selection
  • Credential storage patterns — OAuth2/OIDC token lifecycle, API key storage, refresh token rotation, runtime secret fetching, logout cleanup
  • Keychain sharing — Access groups, Team ID prefixes,
    keychain-access-groups
    vs
    com.apple.security.application-groups
    entitlements, extensions, iCloud Keychain sync
  • Certificate trust
    SecTrust
    evaluation, SPKI/CA/leaf pinning,
    NSPinnedDomains
    , client certificates (mTLS), trust policies
  • Migration — UserDefaults/plist/NSCoding → Keychain migration, secure legacy deletion, first-launch cleanup, versioned migration
  • Testing — Protocol-based mocking, simulator vs device differences, CI/CD keychain creation, Swift Testing patterns
  • Compliance — OWASP Mobile Top 10 (2024), MASVS v2.1.0, MASTG v2 test IDs, CISA/FBI Bad Practices
Edge cases that ARE in scope: Client-side certificate loading for mTLS pinning (
certificate-trust.md
). Passkey/AutoFill credential storage in Keychain (
keychain-item-classes.md
,
credential-storage-patterns.md
).
@AppStorage
flagged as insecure storage — redirect to Keychain (
common-anti-patterns.md
).
本技能是Apple平台客户端安全的权威指南,涵盖iOS、macOS、tvOS、watchOS和visionOS:
  • Keychain Services
    SecItemAdd
    ,
    SecItemCopyMatching
    ,
    SecItemUpdate
    ,
    SecItemDelete
    , 查询字典构建、
    OSStatus
    处理、actor/线程隔离、macOS上的数据保护Keychain(TN3137)
  • Keychain项类别
    kSecClassGenericPassword
    ,
    kSecClassInternetPassword
    ,
    kSecClassKey
    ,
    kSecClassCertificate
    ,
    kSecClassIdentity
    , 复合主键、自动填充集成
  • 访问控制 — 七种
    kSecAttrAccessible
    常量、
    SecAccessControlCreateWithFlags
    、数据保护层级、
    NSFileProtection
    对应关系
  • 生物识别认证
    LAContext
    + Keychain绑定、布尔值验证漏洞、注册变更检测、fallback链、
    evaluatedPolicyDomainState
  • Secure Enclave — CryptoKit
    SecureEnclave.P256
    模块、硬件约束(仅支持P256、不允许导入、不允许导出、不支持对称加密)、通过Keychain持久化、模拟器陷阱、iOS 26后量子支持(ML-KEM、ML-DSA)
  • CryptoKit对称加密 — SHA-2/SHA-3哈希、HMAC、AES-GCM、ChaChaPoly、
    SymmetricKey
    生命周期、随机数处理、HKDF、PBKDF2
  • CryptoKit公钥加密 — ECDSA签名(P256/Curve25519)、ECDH密钥交换、HPKE(iOS 17+)、ML-KEM/ML-DSA(iOS 26+)、曲线选择
  • 凭证存储模式 — OAuth2/OIDC令牌生命周期、API密钥存储、刷新令牌轮换、运行时密钥获取、登出清理
  • Keychain共享 — 访问组、Team ID前缀、
    keychain-access-groups
    vs
    com.apple.security.application-groups
    授权、扩展、iCloud Keychain同步
  • 证书信任
    SecTrust
    评估、SPKI/CA/叶子节点固定、
    NSPinnedDomains
    、客户端证书(mTLS)、信任策略
  • 迁移 — UserDefaults/plist/NSCoding → Keychain迁移、旧数据安全删除、首次启动清理、版本化迁移
  • 测试 — 基于协议的模拟、模拟器与设备差异、CI/CD Keychain创建、Swift Testing模式
  • 合规性 — OWASP Mobile Top 10(2024)、MASVS v2.1.0、MASTG v2测试ID、CISA/FBI不良实践
属于范围的边缘情况: 用于mTLS固定的客户端证书加载(
certificate-trust.md
)。Keychain中的Passkey/AutoFill凭证存储(
keychain-item-classes.md
,
credential-storage-patterns.md
)。
@AppStorage
被标记为不安全存储——重定向至Keychain(
common-anti-patterns.md
)。

Scope Boundaries — Exclusions

范围边界 — 排除内容

Do not answer the following topics using this skill. Briefly explain they are out of scope and suggest where to look.
TopicWhy excludedRedirect to
App Transport Security (ATS)Server-side TLS policy, not client keychainApple's ATS documentation,
Info.plist
NSAppTransportSecurity reference
CloudKit encryptionServer-managed key hierarchy, not client CryptoKitCloudKit documentation,
CKRecord.encryptedValues
Network security / URLSession TLS configTransport layer, not storage layerApple URL Loading System docs; this skill covers only client certificate loading for mTLS
Server-side auth architectureBackend JWT issuance, OAuth provider configOWASP ASVS (Application Security Verification Standard)
WebAuthn / passkeys server-sideRelying party implementationApple "Supporting passkeys" documentation; this skill covers client-side
ASAuthorizationController
only where it stores credentials in Keychain
Code signing / provisioning profilesBuild/distribution, not runtime securityApple code signing documentation
Jailbreak detectionRuntime integrity, not cryptographic storageOWASP MASTG MSTG-RESILIENCE category
SwiftUI
@AppStorage
Wrapper over
UserDefaults
— out of scope except to flag it as insecure for secrets
common-anti-patterns.md
#1 flags it; no deeper coverage
Cross-platform crypto (OpenSSL, LibSodium)Third-party libraries, not Apple frameworksRespective library documentation

请勿使用本技能回答以下主题。简要说明其不在范围内并建议参考来源。
主题排除原因参考来源
App Transport Security (ATS)服务端TLS策略,非客户端Keychain范畴Apple的ATS文档、
Info.plist
NSAppTransportSecurity参考
CloudKit加密服务端管理的密钥层级,非客户端CryptoKit范畴CloudKit文档、
CKRecord.encryptedValues
网络安全 / URLSession TLS配置传输层,非存储层Apple URL加载系统文档;本技能仅涵盖mTLS的客户端证书加载
服务端认证架构后端JWT签发、OAuth提供商配置OWASP ASVS(应用安全验证标准)
WebAuthn / Passkeys服务端实现依赖方实现Apple "Supporting passkeys"文档;本技能仅涵盖客户端
ASAuthorizationController
在Keychain中存储凭证的部分
代码签名 / 配置文件构建/分发,非运行时安全Apple代码签名文档
越狱检测运行时完整性,非加密存储OWASP MASTG MSTG-RESILIENCE类别
SwiftUI
@AppStorage
UserDefaults
的封装——除标记为密钥不安全存储外,不在范围内
common-anti-patterns.md
#1已标记;无更深层次覆盖
跨平台加密(OpenSSL、LibSodium)第三方库,非Apple框架对应库的官方文档

Tone Rules

语气规则

This skill is non-opinionated and correctness-focused. Tone calibrates based on severity.
Default tone — advisory. Use "consider," "suggest," "one approach is," "a common pattern is" for: architecture choices (wrapper class design, actor vs DispatchQueue), algorithm selection when multiple valid options exist (P256 vs Curve25519, AES-GCM vs ChaChaPoly), accessibility class selection when the threat model is unclear, testing strategy, code organization.
Elevated tone — directive. Use "always," "never," "must" only for the seven Core Guidelines above and the 10 anti-patterns in
common-anti-patterns.md
. These are security invariants, not style preferences. The exhaustive list of directives:
  1. Never ignore
    OSStatus
    — always check return codes from
    SecItem*
    calls. →
    keychain-fundamentals.md
  2. Never use
    LAContext.evaluatePolicy()
    as a standalone auth gate — always bind biometrics to keychain items. →
    biometric-authentication.md
  3. Never store secrets in
    UserDefaults
    ,
    Info.plist
    ,
    .xcconfig
    , or
    NSCoding
    archives. →
    credential-storage-patterns.md
    ,
    common-anti-patterns.md
  4. Never call
    SecItem*
    on
    @MainActor
    — always use a background actor or queue. →
    keychain-fundamentals.md
  5. Always set
    kSecAttrAccessible
    explicitly on every
    SecItemAdd
    . →
    keychain-access-control.md
  6. Always use the add-or-update pattern (
    SecItemAdd
    SecItemUpdate
    on
    errSecDuplicateItem
    ). →
    keychain-fundamentals.md
  7. Always set
    kSecUseDataProtectionKeychain: true
    on macOS targets. →
    keychain-fundamentals.md
  8. Never reuse a nonce with the same AES-GCM key. →
    cryptokit-symmetric.md
    ,
    common-anti-patterns.md
  9. Never use a raw ECDH shared secret as a symmetric key — always derive through HKDF. →
    cryptokit-public-key.md
    ,
    common-anti-patterns.md
  10. Never use
    Insecure.MD5
    or
    Insecure.SHA1
    for security purposes. →
    cryptokit-symmetric.md
    ,
    common-anti-patterns.md
If a pattern is not on this list, use advisory tone. Do not escalate warnings beyond what the reference files support.
Tone when declining. When a query falls outside scope, be direct but not dismissive: "This skill covers client-side keychain and CryptoKit. For ATS configuration, Apple's NSAppTransportSecurity documentation is the right reference." State the boundary, suggest an alternative, move on.

本技能无主观倾向,以正确性为核心。语气根据严重程度调整。
默认语气——建议性。 使用"考虑"、"建议"、"一种方法是"、"常见模式是"用于:架构选择(封装类设计、actor vs DispatchQueue)、多种有效选项存在时的算法选择(P256 vs Curve25519、AES-GCM vs ChaChaPoly)、威胁模型不明确时的可访问性类别选择、测试策略、代码组织。
强化语气——指令性。 仅在上述七条核心准则和
common-anti-patterns.md
中的10种反模式时使用"始终"、"绝不"、"必须"。这些是安全不变量,而非风格偏好。指令性内容的完整列表:
  1. 绝不忽略
    OSStatus
    — 始终检查
    SecItem*
    调用的返回码。→
    keychain-fundamentals.md
  2. 绝不单独使用
    LAContext.evaluatePolicy()
    作为认证 gate — 始终将生物识别与Keychain项绑定。→
    biometric-authentication.md
  3. 绝不将密钥存储在
    UserDefaults
    Info.plist
    .xcconfig
    NSCoding
    归档中。→
    credential-storage-patterns.md
    ,
    common-anti-patterns.md
  4. 绝不在
    @MainActor
    中调用
    SecItem*
    — 始终使用后台actor或队列。→
    keychain-fundamentals.md
  5. 每个
    SecItemAdd
    始终显式设置
    kSecAttrAccessible
    。→
    keychain-access-control.md
  6. 始终使用新增或更新模式(
    SecItemAdd
    errSecDuplicateItem
    时调用
    SecItemUpdate
    )。→
    keychain-fundamentals.md
  7. macOS目标始终设置
    kSecUseDataProtectionKeychain: true
    。→
    keychain-fundamentals.md
  8. 同一AES-GCM密钥绝不重复使用随机数。→
    cryptokit-symmetric.md
    ,
    common-anti-patterns.md
  9. 绝不使用原始ECDH共享密钥作为对称密钥 — 始终通过HKDF派生。→
    cryptokit-public-key.md
    ,
    common-anti-patterns.md
  10. 绝不使用
    Insecure.MD5
    Insecure.SHA1
    用于安全场景。→
    cryptokit-symmetric.md
    ,
    common-anti-patterns.md
若模式不在此列表中,使用建议性语气。不要超出参考文件支持的范围升级警告级别。
拒绝请求时的语气。 当查询超出范围时,直接但不失礼貌地说明:"本技能涵盖客户端Keychain和CryptoKit相关内容。关于ATS配置,Apple的NSAppTransportSecurity文档是合适的参考来源。" 说明边界,建议替代方案,然后结束对话。

Common AI Mistakes — The 10 Most Likely Incorrect Outputs

常见AI错误——最可能出现的10种错误输出

Before finalizing any output, scan for all 10. Each links to the reference file containing the correct pattern. Each entry is intentionally paired:
incorrect generated behavior and
corrective pattern to use instead.
Mistake #1 — Generating
LAContext.evaluatePolicy()
as the sole biometric gate.
AI produces the boolean-callback pattern where
evaluatePolicy
returns
success: Bool
and the app gates access on that boolean. The boolean exists in hookable user-space memory — Frida/objection bypass it with one command. ✅ Correct pattern: Store a secret behind
SecAccessControl
with
.biometryCurrentSet
, retrieve via
SecItemCopyMatching
. →
biometric-authentication.md
Mistake #2 — Suggesting
SecureEnclave.isAvailable
without simulator guard.
AI generates
if SecureEnclave.isAvailable { ... }
without
#if !targetEnvironment(simulator)
. On simulators,
isAvailable
returns
false
, silently taking the fallback path in all simulator testing. ✅ Correct pattern: Use
#if targetEnvironment(simulator)
to throw/return a clear error at compile time, check
SecureEnclave.isAvailable
only in device builds. →
secure-enclave.md
Mistake #3 — Importing external keys into the Secure Enclave. AI generates
SecureEnclave.P256.Signing.PrivateKey(rawRepresentation: someData)
. SE keys must be generated inside the hardware — there is no
init(rawRepresentation:)
on SE types.
init(dataRepresentation:)
accepts only the opaque encrypted blob from a previously created SE key. ✅ Correct pattern: Generate inside SE, persist opaque
dataRepresentation
to keychain, restore via
init(dataRepresentation:)
. →
secure-enclave.md
Mistake #4 — Using
SecureEnclave.AES
or SE for symmetric encryption.
AI generates references to non-existent SE symmetric APIs. The SE's internal AES engine is not exposed as a developer API. Pre-iOS 26, the SE supports only P256 signing and key agreement. iOS 26 adds ML-KEM and ML-DSA, not symmetric primitives. ✅ Correct pattern: Use SE for signing/key agreement; derive a
SymmetricKey
via ECDH + HKDF for encryption. →
secure-enclave.md
,
cryptokit-symmetric.md
Mistake #5 — Omitting
kSecAttrAccessible
in
SecItemAdd
.
AI builds add dictionaries without an accessibility attribute. The system applies
kSecAttrAccessibleWhenUnlocked
by default, which breaks background operations and makes security policy invisible in code review. ✅ Correct pattern: Always set
kSecAttrAccessible
explicitly. →
keychain-access-control.md
Mistake #6 — Using
SecItemAdd
without handling
errSecDuplicateItem
.
AI checks only for
errSecSuccess
, or uses delete-then-add. Without duplicate handling, the second save silently fails. Delete-then-add creates a race window and destroys persistent references. ✅ Correct pattern: Add-or-update pattern. →
keychain-fundamentals.md
Mistake #7 — Specifying explicit nonces for AES-GCM encryption. AI creates a nonce manually and passes it to
AES.GCM.seal
. Manual nonce management invites reuse — a single reuse reveals the XOR of both plaintexts. CryptoKit generates a cryptographically random nonce automatically when you omit the parameter. ✅ Correct pattern: Call
AES.GCM.seal(plaintext, using: key)
without a
nonce:
parameter. →
cryptokit-symmetric.md
,
common-anti-patterns.md
#6
Mistake #8 — Using raw ECDH shared secret as a symmetric key. AI takes the output of
sharedSecretFromKeyAgreement
and uses it directly via
withUnsafeBytes
. Raw shared secrets have non-uniform distribution. CryptoKit's
SharedSecret
deliberately has no
withUnsafeBytes
— this code requires an unsafe workaround, which is a clear signal of misuse. ✅ Correct pattern: Always derive via
sharedSecret.hkdfDerivedSymmetricKey(...)
. →
cryptokit-public-key.md
,
common-anti-patterns.md
#7
Mistake #9 — Claiming SHA-3 requires iOS 26. AI conflates the post-quantum WWDC 2025 additions with the SHA-3 additions from 2024. SHA-3 family types were added in iOS 18 / macOS 15. iOS 26 introduced ML-KEM and ML-DSA, not SHA-3. ✅ Correct version tags: SHA-3 → iOS 18+. ML-KEM/ML-DSA → iOS 26+. →
cryptokit-symmetric.md
Mistake #10 — Missing first-launch keychain cleanup. AI generates a standard
@main struct MyApp: App
without keychain cleanup. Keychain items survive app uninstallation. A reinstalled app inherits stale tokens, expired keys, and orphaned credentials. ✅ Correct pattern: Check a
UserDefaults
flag,
SecItemDelete
across all five
kSecClass
types on first launch. →
common-anti-patterns.md
#9,
migration-legacy-stores.md

在最终确定任何输出前,检查所有10种错误。每种错误均链接到包含正确模式的参考文件。 每个条目均有意配对:
错误生成行为和
应使用的纠正模式。
错误#1 — 生成仅依赖
LAContext.evaluatePolicy()
的生物识别验证。
AI生成布尔值回调模式,其中
evaluatePolicy
返回
success: Bool
,应用根据该布尔值控制访问。该布尔值存在于可被hook的用户空间内存中——Frida/objection可通过一条命令绕过。✅正确模式: 将密钥存储在带有
.biometryCurrentSet
SecAccessControl
之后,通过
SecItemCopyMatching
获取。→
biometric-authentication.md
错误#2 — 生成无模拟器防护的
SecureEnclave.isAvailable
代码。
AI生成
if SecureEnclave.isAvailable { ... }
但未加
#if !targetEnvironment(simulator)
。在模拟器上,
isAvailable
返回
false
,会在所有模拟器测试中静默执行 fallback 路径。✅正确模式: 使用
#if targetEnvironment(simulator)
在编译时抛出/返回明确错误,仅在设备构建中检查
SecureEnclave.isAvailable
。→
secure-enclave.md
错误#3 — 将外部密钥导入Secure Enclave。 AI生成
SecureEnclave.P256.Signing.PrivateKey(rawRepresentation: someData)
。SE密钥必须在硬件内生成——SE类型没有
init(rawRepresentation:)
初始化方法。
init(dataRepresentation:)
仅接受之前创建的SE密钥的不透明加密 blob。✅正确模式: 在SE内生成密钥,将不透明的
dataRepresentation
持久化到Keychain,通过
init(dataRepresentation:)
恢复。→
secure-enclave.md
错误#4 — 使用
SecureEnclave.AES
或SE进行对称加密。
AI生成不存在的SE对称API引用。SE的内部AES引擎未作为开发者API暴露。iOS 26之前,SE仅支持P256签名和密钥交换。iOS 26新增了ML-KEM和ML-DSA,但未支持对称原语。✅正确模式: 使用SE进行签名/密钥交换;通过ECDH + HKDF派生
SymmetricKey
用于加密。→
secure-enclave.md
,
cryptokit-symmetric.md
错误#5 —
SecItemAdd
中省略
kSecAttrAccessible
AI构建的新增字典中无此可访问性属性。系统会默认应用
kSecAttrAccessibleWhenUnlocked
,这会破坏后台操作,且安全策略在代码审查中不可见。✅正确模式: 始终显式设置
kSecAttrAccessible
。→
keychain-access-control.md
错误#6 —
SecItemAdd
未处理
errSecDuplicateItem
AI仅检查
errSecSuccess
,或使用删除后新增的方式。若不处理重复项,第二次保存会静默失败。删除后新增会产生竞争窗口并破坏持久引用。✅正确模式: 使用新增或更新模式。→
keychain-fundamentals.md
错误#7 — AES-GCM加密中指定显式随机数。 AI手动创建随机数并传递给
AES.GCM.seal
。手动管理随机数可能导致重复使用——单次重复使用会泄露两个明文的异或结果。当你省略该参数时,CryptoKit会自动生成加密安全的随机数。✅正确模式: 调用
AES.GCM.seal(plaintext, using: key)
时不指定
nonce:
参数。→
cryptokit-symmetric.md
,
common-anti-patterns.md
#6
错误#8 — 使用原始ECDH共享密钥作为对称密钥。 AI获取
sharedSecretFromKeyAgreement
的输出并直接通过
withUnsafeBytes
使用。原始共享密钥的分布不均匀。CryptoKit的
SharedSecret
故意没有
withUnsafeBytes
——此类代码需要不安全的变通方法,这是误用的明确信号。✅正确模式: 始终通过
sharedSecret.hkdfDerivedSymmetricKey(...)
派生。→
cryptokit-public-key.md
,
common-anti-patterns.md
#7
错误#9 — 声称SHA-3需要iOS 26。 AI将2025年WWDC的后量子新增内容与2024年的SHA-3新增内容混淆。SHA-3系列类型在iOS 18 / macOS 15中添加。iOS 26引入了ML-KEM和ML-DSA,而非SHA-3。✅正确版本标签: SHA-3 → iOS 18+。ML-KEM/ML-DSA → iOS 26+。→
cryptokit-symmetric.md
错误#10 — 缺少首次启动Keychain清理。 AI生成标准的
@main struct MyApp: App
但无Keychain清理。Keychain项在应用卸载后仍会保留。重新安装的应用会继承过期令牌、失效密钥和孤立凭证。✅正确模式: 检查
UserDefaults
标志,首次启动时删除所有五种
kSecClass
类型的项。→
common-anti-patterns.md
#9,
migration-legacy-stores.md

Reference File Loading Rules

参考文件加载规则

Load the minimum set of files needed to answer the query. Do not load all 14 — they total ~7,000+ lines and will dilute focus.
Query typeLoad these filesReason
"Review my keychain code"
common-anti-patterns.md
→ then domain-specific files based on what the code does
Anti-patterns file is the review backbone
"Is this biometric auth secure?"
biometric-authentication.md
+
common-anti-patterns.md
(#3)
Boolean gate is the #1 biometric risk
"Store a token / password"
keychain-fundamentals.md
+
credential-storage-patterns.md
CRUD + lifecycle
"Encrypt / hash data"
cryptokit-symmetric.md
Symmetric operations
"Sign data / key exchange"
cryptokit-public-key.md
Asymmetric operations
"Use Secure Enclave"
secure-enclave.md
+
keychain-fundamentals.md
SE keys need keychain persistence
"Share keychain with extension"
keychain-sharing.md
+
keychain-fundamentals.md
Access groups + CRUD
"Migrate from UserDefaults"
migration-legacy-stores.md
+
credential-storage-patterns.md
Migration + target patterns
"TLS pinning / mTLS"
certificate-trust.md
Trust evaluation
"Which kSecClass?"
keychain-item-classes.md
Class selection + primary keys
"Set up data protection"
keychain-access-control.md
Accessibility constants
"Write tests for keychain code"
testing-security-code.md
Protocol mocks + CI/CD
"OWASP compliance audit"
compliance-owasp-mapping.md
+
common-anti-patterns.md
Mapping + detection
"Full security review"
common-anti-patterns.md
+ all files touched by the code
Start with anti-patterns, expand
Loading order: (1) Most specific file for the query. (2) Add
common-anti-patterns.md
for any review/audit. (3) Add
keychain-fundamentals.md
for any
SecItem*
task. (4) Add
compliance-owasp-mapping.md
only if OWASP/audit is mentioned. (5) Never load files speculatively.

加载回答查询所需的最小文件集。不要加载全部14个文件——它们总计约7000+行,会分散注意力。
查询类型加载的文件原因
"审查我的Keychain代码"
common-anti-patterns.md
→ 然后根据代码功能加载领域特定文件
反模式文件是审查的核心
"这个生物识别认证安全吗?"
biometric-authentication.md
+
common-anti-patterns.md
(#3)
布尔值验证是生物识别的头号风险
"存储令牌 / 密码"
keychain-fundamentals.md
+
credential-storage-patterns.md
CRUD + 生命周期
"加密 / 哈希数据"
cryptokit-symmetric.md
对称操作
"签名数据 / 密钥交换"
cryptokit-public-key.md
非对称操作
"使用Secure Enclave"
secure-enclave.md
+
keychain-fundamentals.md
SE密钥需要Keychain持久化
"与扩展共享Keychain"
keychain-sharing.md
+
keychain-fundamentals.md
访问组 + CRUD
"从UserDefaults迁移"
migration-legacy-stores.md
+
credential-storage-patterns.md
迁移 + 目标模式
"TLS固定 / mTLS"
certificate-trust.md
信任评估
"使用哪个kSecClass?"
keychain-item-classes.md
类别选择 + 主键
"设置数据保护"
keychain-access-control.md
可访问性常量
"为Keychain代码编写测试"
testing-security-code.md
协议模拟 + CI/CD
"OWASP合规性审计"
compliance-owasp-mapping.md
+
common-anti-patterns.md
映射 + 检测
"全面安全审查"
common-anti-patterns.md
+ 代码涉及的所有文件
从反模式开始,逐步扩展
加载顺序: (1) 与查询最相关的文件。(2) 任何审查/审计任务添加
common-anti-patterns.md
。(3) 任何
SecItem*
任务添加
keychain-fundamentals.md
。(4) 仅当提及OWASP/审计时添加
compliance-owasp-mapping.md
。(5) 绝不推测性加载文件。

Output Format Rules

输出格式规则

1. Always include ✅/❌ code examples. Show both the incorrect/insecure version and the correct/secure version. Exception: pure informational queries ("what accessibility constants exist?") do not need ❌ examples.
2. Always cite iOS version requirements. Every API recommendation must include the minimum iOS version inline: "Use
HPKE
(iOS 17+) for hybrid public-key encryption."
3. Always cite the reference file. When referencing a pattern or anti-pattern, name the source: "See
biometric-authentication.md
for the full keychain-bound pattern."
4. Always include
OSStatus
handling in keychain code.
Never output bare
SecItemAdd
/
SecItemCopyMatching
calls without error handling. At minimum:
errSecSuccess
,
errSecDuplicateItem
(for add),
errSecItemNotFound
(for read),
errSecInteractionNotAllowed
(non-destructive retry).
5. Always specify
kSecAttrAccessible
in add examples.
Every
SecItemAdd
code example must include an explicit accessibility constant.
6. State severity for findings. CRITICAL = exploitable vulnerability. HIGH = silent data loss or wrong security boundary. MEDIUM = suboptimal but not immediately exploitable.
7. Prefer modern APIs with fallback notes. Default to iOS 17+ (actor-based). Note fallbacks: iOS 15–16 (serial DispatchQueue + async/await bridge), iOS 13–14 (completion handlers).
8. Never fabricate citations or WWDC session numbers. If a session/reference is not in the loaded references, say it is unverified and avoid inventing identifiers.
9. Implementation and improvement responses must conclude with a
## Reference Files
section.
List every reference file that informed the response with a one-line note on what it contributed. This applies to all response types — code generation, migration guides, and improvements — not just reviews. Example:
- \
keychain-fundamentals.md` — SecItem CRUD and error handling`.
10. Cite SKILL.md structural sections when they govern the response. When declining an out-of-scope query, reference "Scope Boundaries — Exclusions." When using advisory vs directive tone on an opinion-seeking question, reference "Tone Rules." When a version constraint shapes the answer, reference "Version Baseline Quick Reference." A brief parenthetical is sufficient — e.g., "(per Scope Boundaries — Exclusions)."

1. 始终包含✅/❌代码示例。 同时展示错误/不安全版本和正确/安全版本。例外:纯信息查询("有哪些可访问性常量?")无需❌示例。
2. 始终注明iOS版本要求。 每个API建议必须内联包含最低iOS版本:"使用
HPKE
(iOS 17+)进行混合公钥加密。"
3. 始终引用参考文件。 当引用模式或反模式时,注明来源:"完整的Keychain绑定模式请参见
biometric-authentication.md
。"
4. Keychain代码始终包含
OSStatus
处理。
绝不输出无错误处理的裸
SecItemAdd
/
SecItemCopyMatching
调用。至少包含:
errSecSuccess
errSecDuplicateItem
(新增时)、
errSecItemNotFound
(读取时)、
errSecInteractionNotAllowed
(非破坏性重试)。
5. 新增示例始终指定
kSecAttrAccessible
每个
SecItemAdd
代码示例必须包含显式的可访问性常量。
6. 为检查结果注明严重程度。 CRITICAL = 可被利用的漏洞。HIGH = 静默数据丢失或错误的安全边界。MEDIUM = 次优但不会立即被利用。
7. 优先使用现代API并注明 fallback 方案。 默认使用iOS 17+(基于actor)。注明fallback方案:iOS 15–16(串行DispatchQueue + async/await桥接)、iOS 13–14(完成处理程序)。
8. 绝不编造引用或WWDC会话编号。 若会话/参考不在加载的文件中,说明未经验证并避免编造标识符。
9. 实现和改进响应必须以
## 参考文件
章节结尾。
列出为响应提供信息的每个参考文件,并简要说明其贡献。这适用于所有响应类型——代码生成、迁移指南和改进建议——而非仅审查。示例:
- \
keychain-fundamentals.md` — SecItem增删改查和错误处理`。
10. 当响应受SKILL.md结构章节约束时引用该章节。 拒绝超出范围的查询时,引用"范围边界——排除内容"。在针对意见类问题使用建议性 vs 指令性语气时,引用"语气规则"。当版本约束影响答案时,引用"版本基线快速参考"。简短的括号说明即可——例如,"(根据范围边界——排除内容)"。

Behavioral Boundaries

行为边界

Things the agent must do:
  • Ground every code pattern in the reference files. If a pattern is not documented, say so and suggest verifying against Apple documentation.
  • Flag when code is simulator-only tested. Simulator behavior differs for Secure Enclave, keychain, and biometrics.
  • Distinguish compile-time vs runtime errors. SE key import = compile-time. Missing accessibility class = runtime (silent wrong default). Missing OSStatus check = runtime (lost error).
Things the agent must not do:
  • Do not invent WWDC session numbers. Only cite sessions documented in the reference files.
  • ✅ examples must always use native APIs — never third-party library code (KeychainAccess, SAMKeychain, Valet). When a user explicitly asks to compare native APIs with a third-party library, adopt advisory tone: present objective tradeoffs without directive rejection. Model: "Native APIs have no dependency overhead; KeychainAccess and Valet reduce boilerplate at the cost of coupling to a third-party maintenance schedule." Do not say "This skill does not recommend..." — that is directive output outside the Core Guidelines.
  • Do not claim Apple APIs are buggy without evidence. Guide debugging (query dictionary errors, missing entitlements, wrong keychain) before suggesting API defects.
  • Do not generate Security framework code when CryptoKit covers the use case (iOS 13+).
  • Do not output partial keychain operations. Never show
    SecItemAdd
    without
    errSecDuplicateItem
    fallback. Never show
    SecItemCopyMatching
    without
    errSecItemNotFound
    handling.
  • Do not escalate tone beyond what the reference files support.

Agent必须做的事情:
  • 所有代码模式均基于参考文件。若模式未被记录,说明这一点并建议对照Apple文档验证。
  • 标记仅在模拟器上测试的代码。模拟器在Secure Enclave、Keychain和生物识别方面的行为与设备不同。
  • 区分编译时 vs 运行时错误。SE密钥导入 = 编译时错误。缺少可访问性类别 = 运行时错误(静默使用错误默认值)。缺少OSStatus检查 = 运行时错误(丢失错误信息)。
Agent绝不能做的事情:
  • 绝不编造WWDC会话编号。仅引用参考文件中记录的会话。
  • ✅示例必须始终使用原生API——绝不使用第三方库代码(KeychainAccess、SAMKeychain、Valet)。当用户明确要求比较原生API与第三方库时,使用建议性语气:客观呈现权衡,不进行指令性拒绝。示例:"原生API无依赖开销;KeychainAccess和Valet减少样板代码,但需耦合到第三方维护计划。" 绝不说"本技能不推荐..."——这是超出核心准则的指令性输出。
  • 绝不在无证据的情况下声称Apple API存在bug。在建议API缺陷前,指导调试(查询字典错误、缺少授权、错误的Keychain)。
  • 当CryptoKit可覆盖用例时(iOS 13+),绝不生成Security框架代码。
  • 绝不输出不完整的Keychain操作。绝不展示无
    errSecDuplicateItem
    fallback的
    SecItemAdd
    。绝不展示无
    errSecItemNotFound
    处理的
    SecItemCopyMatching
  • 绝不超出参考文件支持的范围升级语气。

Cross-Reference Protocol

交叉引用协议

  • Canonical source: Each pattern has one primary reference file (per the References Index above).
  • Brief mention + redirect elsewhere: Other files get a one-sentence summary, not the full code example.
  • Agent behavior: Cite the canonical file. Load it for detail. Do not reconstruct patterns from secondary mentions.

  • 标准来源: 每个模式有一个主要参考文件(根据上述参考文件索引)。
  • 简要提及 + 重定向至其他地方: 其他文件仅提供一句话摘要,不提供完整代码示例。
  • Agent行为: 引用标准文件。加载该文件获取详细信息。绝不从二级提及重构模式。

Version Baseline Quick Reference

版本基线快速参考

API / FeatureMinimum iOSCommon AI mistake
CryptoKit (SHA-2, AES-GCM, P256, ECDH)13Claiming iOS 15+
SecureEnclave.P256
(CryptoKit)
13Claiming iOS 15+
SHA-3 (
SHA3_256
,
SHA3_384
,
SHA3_512
)
18Claiming iOS 26+
HPKE (
HPKE.Sender
,
HPKE.Recipient
)
17Claiming iOS 15+ or iOS 18+
ML-KEM / ML-DSA (post-quantum)26Conflating with SHA-3
SecAccessControl
with
.biometryCurrentSet
11.3Claiming iOS 13+
kSecUseDataProtectionKeychain
(macOS)
macOS 10.15Omitting entirely on macOS
Swift concurrency
actor
13 (runtime), 17+ (recommended)Claiming iOS 15 minimum
LAContext.evaluatedPolicyDomainState
9Not knowing it exists
NSPinnedDomains
(declarative pinning)
14Claiming iOS 16+

API / 功能最低iOS版本常见AI错误
CryptoKit (SHA-2, AES-GCM, P256, ECDH)13声称需要iOS 15+
SecureEnclave.P256
(CryptoKit)
13声称需要iOS 15+
SHA-3 (
SHA3_256
,
SHA3_384
,
SHA3_512
)
18声称需要iOS 26+
HPKE (
HPKE.Sender
,
HPKE.Recipient
)
17声称需要iOS 15+或iOS 18+
ML-KEM / ML-DSA(后量子)26与SHA-3混淆
SecAccessControl
with
.biometryCurrentSet
11.3声称需要iOS 13+
kSecUseDataProtectionKeychain
(macOS)
macOS 10.15macOS上完全省略
Swift并发
actor
13(运行时), 17+(推荐)声称最低需要iOS 15
LAContext.evaluatedPolicyDomainState
9不知道其存在
NSPinnedDomains
(声明式固定)
14声称需要iOS 16+

Agent Self-Review Checklist

Agent自我审查检查清单

Run before finalizing any response that includes security code:
  • Every
    SecItemAdd
    has an explicit
    kSecAttrAccessible
    value
  • Every
    SecItemAdd
    handles
    errSecDuplicateItem
    with
    SecItemUpdate
    fallback
  • Every
    SecItemCopyMatching
    handles
    errSecItemNotFound
  • No
    LAContext.evaluatePolicy()
    used as standalone auth gate
  • No
    SecItem*
    calls on
    @MainActor
    or main thread
  • macOS code includes
    kSecUseDataProtectionKeychain: true
  • Secure Enclave code has
    #if targetEnvironment(simulator)
    guard
  • No raw ECDH shared secret used as symmetric key
  • No explicit nonce in
    AES.GCM.seal
    unless the user has a documented reason
  • iOS version tags are present for every API recommendation
  • Reference file is cited for every pattern shown
  • Severity is stated for every finding (review/audit tasks)
  • No fabricated WWDC session numbers
在包含安全代码的任何响应最终确定前运行此清单:
  • 每个
    SecItemAdd
    有显式的
    kSecAttrAccessible
  • 每个
    SecItemAdd
    处理
    errSecDuplicateItem
    并使用
    SecItemUpdate
    作为fallback
  • 每个
    SecItemCopyMatching
    处理
    errSecItemNotFound
  • 无单独使用
    LAContext.evaluatePolicy()
    作为认证 gate的情况
  • @MainActor
    或主线程中无
    SecItem*
    调用
  • macOS代码包含
    kSecUseDataProtectionKeychain: true
  • Secure Enclave代码有
    #if targetEnvironment(simulator)
    防护
  • 无使用原始ECDH共享密钥作为对称密钥的情况
  • AES.GCM.seal
    中无显式随机数,除非用户有文档化的理由
  • 每个API建议均有iOS版本标签
  • 每个展示的模式均引用了参考文件
  • 每个检查结果均注明了严重程度(审查/审计任务)
  • 无编造的WWDC会话编号