CryptoTokenKit
Use CryptoTokenKit for token-driver extensions, smart-card sessions,
token-backed Keychain items, certificate authentication, and iOS/iPadOS 26+
NFC smart-card access.
API presence is not an access guarantee: extension points, entitlements,
hardware, and runtime support all matter. The login/keychain-unlock token
extension flow is macOS-specific, TKSmartCardSlotManager.default is optional,
and NFC smart-card slot creation requires iOS/iPadOS 26+.
Contents
Choose the workflow
- For the macOS driver/token/session classes, extension Info.plist, PIN auth,
low-level APDU sessions, token-backed Keychain queries, NFC slot lifecycle,
and certificate requirements, read
Token and smart-card workflows.
- For PIV selection and signing, BER/compact TLV parsing, generic token drivers,
command chaining, large responses, secure PIN operations, configuration,
slot monitoring, and registration, read
CryptoTokenKit extended patterns.
Architecture and boundaries
CryptoTokenKit has three distinct modes:
- A macOS smart-card token extension exposes hardware-backed keys and
certificates to login and Keychain services.
- An app queries token-backed items through Security.framework while the token
is present.
- An iOS/iPadOS 26+ app creates a temporary NFC smart-card slot and communicates
through
TKSmartCard.
Own token/smart-card sessions, token-backed items, APDUs, PIN operations, and
smart-card certificate authentication here. Route passkeys/WebAuthn and account
sign-in to authentication; route CryptoKit primitives, Secure Enclave,
ordinary Keychain architecture, pinning, and trust policy to swift-security.
| Type |
Role |
Important constraint |
TKTokenDriver, TKToken, TKTokenSession |
Driver/token/session primitives |
Extension behavior depends on platform and extension point |
TKSmartCardTokenDriver |
Smart-card driver entry point |
System login integration is a macOS extension flow |
TKSmartCard, TKSmartCardSlotManager |
Reader discovery and APDU transport |
Default manager may be nil |
TKTokenWatcher |
Token insertion/removal |
Retain it for the monitoring lifetime |
TKSmartCardSlotNFCSession |
Temporary NFC-backed slot |
iOS/iPadOS 26+; always end the session |
TKSmartCardTokenRegistrationManager |
NFC token registration |
iOS/iPadOS 26+ |
Core invariants
- A token extension declares
com.apple.ctk-tokens and the exact
com.apple.ctk.driver-class; the host app is only its delivery vehicle.
- Populate
TKTokenKeychainContents with stable, matching object IDs.
TKTokenKeychainKey capabilities must reflect the hardware.
TKTokenSessionDelegate.supports returns true only for algorithms and
operations the token actually implements.
- Wrap structured
send calls in withSession; for raw transmit, pair
beginSession and endSession on every path.
- Check every APDU status word. Transport success does not mean command success.
- Verify token presence before queries. Persistent references become invalid
after removal and must handle
errSecItemNotFound.
- Configure
TKTokenSmartCardPINAuthOperation from the real card format and
APDU layout; never log or retain PIN bytes.
- End every
TKSmartCardSlotNFCSession, including error and cancellation paths.
Platform and capability checks
import CryptoTokenKit
guard let manager = TKSmartCardSlotManager.default else {
// Missing entitlement/access, unsupported runtime, or no smart-card service.
return
}
On iOS/iPadOS 26+, also require manager.isNFCSupported() before creating an
NFC slot. Keep macOS configuration and system-authentication guidance outside
iOS-only branches. Do not force unwrap a manager, slot, card, certificate, or
keychain item obtained from hardware.
Error handling
Handle TKError according to recovery semantics:
| Error |
Expected response |
.canceledByUser |
Stop quietly or restore prior UI state |
.authenticationFailed / .authenticationNeeded |
Present bounded retry or authentication UI |
.tokenNotFound / .objectNotFound |
Ask for reinsertion or refresh token contents |
.communicationError |
End the session and offer a fresh attempt |
.corruptedData |
Reject the response; do not parse or trust partial data |
.notImplemented |
Disable the unsupported operation |
Preserve smart-card-specific status information in app errors without exposing
secrets. Avoid blind retries of PIN or destructive card commands.
Common Mistakes
- Treating framework availability as proof that the manager, reader, or NFC
capability exists.
- Sending APDUs outside a managed session or ignoring status words.
- Returning blanket algorithm support from the token-session delegate.
- Querying stale token references without observing insertion/removal.
- Declaring signing/decryption/login capabilities not supported by hardware.
- Reusing macOS extension setup in an iOS app target.
Review Checklist
References
1---2name: cryptotokenkit3description: Builds CryptoTokenKit security-token and smart-card integrations. Use for token-driver extensions, token sessions, TKSmartCard communication, NFC smart-card sessions, token-backed Keychain queries, token watching, certificate authentication, APDU handling, or PIN workflows.4---56# CryptoTokenKit78Use CryptoTokenKit for token-driver extensions, smart-card sessions,9token-backed Keychain items, certificate authentication, and iOS/iPadOS 26+10NFC smart-card access.1112API presence is not an access guarantee: extension points, entitlements,13hardware, and runtime support all matter. The login/keychain-unlock token14extension flow is macOS-specific, `TKSmartCardSlotManager.default` is optional,15and NFC smart-card slot creation requires iOS/iPadOS 26+.1617## Contents1819- [Choose the workflow](#choose-the-workflow)20- [Architecture and boundaries](#architecture-and-boundaries)21- [Core invariants](#core-invariants)22- [Platform and capability checks](#platform-and-capability-checks)23- [Error handling](#error-handling)24- [Common mistakes](#common-mistakes)25- [Review checklist](#review-checklist)26- [References](#references)2728## Choose the workflow2930- For the macOS driver/token/session classes, extension Info.plist, PIN auth,31 low-level APDU sessions, token-backed Keychain queries, NFC slot lifecycle,32 and certificate requirements, read33 [Token and smart-card workflows](references/token-and-smart-card-workflows.md).34- For PIV selection and signing, BER/compact TLV parsing, generic token drivers,35 command chaining, large responses, secure PIN operations, configuration,36 slot monitoring, and registration, read37 [CryptoTokenKit extended patterns](references/cryptotokenkit-patterns.md).3839## Architecture and boundaries4041CryptoTokenKit has three distinct modes:42431. A macOS smart-card token extension exposes hardware-backed keys and44 certificates to login and Keychain services.452. An app queries token-backed items through Security.framework while the token46 is present.473. An iOS/iPadOS 26+ app creates a temporary NFC smart-card slot and communicates48 through `TKSmartCard`.4950Own token/smart-card sessions, token-backed items, APDUs, PIN operations, and51smart-card certificate authentication here. Route passkeys/WebAuthn and account52sign-in to `authentication`; route CryptoKit primitives, Secure Enclave,53ordinary Keychain architecture, pinning, and trust policy to `swift-security`.5455| Type | Role | Important constraint |56|---|---|---|57| `TKTokenDriver`, `TKToken`, `TKTokenSession` | Driver/token/session primitives | Extension behavior depends on platform and extension point |58| `TKSmartCardTokenDriver` | Smart-card driver entry point | System login integration is a macOS extension flow |59| `TKSmartCard`, `TKSmartCardSlotManager` | Reader discovery and APDU transport | Default manager may be `nil` |60| `TKTokenWatcher` | Token insertion/removal | Retain it for the monitoring lifetime |61| `TKSmartCardSlotNFCSession` | Temporary NFC-backed slot | iOS/iPadOS 26+; always end the session |62| `TKSmartCardTokenRegistrationManager` | NFC token registration | iOS/iPadOS 26+ |6364## Core invariants6566- A token extension declares `com.apple.ctk-tokens` and the exact67 `com.apple.ctk.driver-class`; the host app is only its delivery vehicle.68- Populate `TKTokenKeychainContents` with stable, matching object IDs.69 `TKTokenKeychainKey` capabilities must reflect the hardware.70- `TKTokenSessionDelegate.supports` returns `true` only for algorithms and71 operations the token actually implements.72- Wrap structured `send` calls in `withSession`; for raw `transmit`, pair73 `beginSession` and `endSession` on every path.74- Check every APDU status word. Transport success does not mean command success.75- Verify token presence before queries. Persistent references become invalid76 after removal and must handle `errSecItemNotFound`.77- Configure `TKTokenSmartCardPINAuthOperation` from the real card format and78 APDU layout; never log or retain PIN bytes.79- End every `TKSmartCardSlotNFCSession`, including error and cancellation paths.8081## Platform and capability checks8283```swift84import CryptoTokenKit8586guard let manager = TKSmartCardSlotManager.default else {87 // Missing entitlement/access, unsupported runtime, or no smart-card service.88 return89}90```9192On iOS/iPadOS 26+, also require `manager.isNFCSupported()` before creating an93NFC slot. Keep macOS configuration and system-authentication guidance outside94iOS-only branches. Do not force unwrap a manager, slot, card, certificate, or95keychain item obtained from hardware.9697## Error handling9899Handle `TKError` according to recovery semantics:100101| Error | Expected response |102|---|---|103| `.canceledByUser` | Stop quietly or restore prior UI state |104| `.authenticationFailed` / `.authenticationNeeded` | Present bounded retry or authentication UI |105| `.tokenNotFound` / `.objectNotFound` | Ask for reinsertion or refresh token contents |106| `.communicationError` | End the session and offer a fresh attempt |107| `.corruptedData` | Reject the response; do not parse or trust partial data |108| `.notImplemented` | Disable the unsupported operation |109110Preserve smart-card-specific status information in app errors without exposing111secrets. Avoid blind retries of PIN or destructive card commands.112113## Common Mistakes114115- Treating framework availability as proof that the manager, reader, or NFC116 capability exists.117- Sending APDUs outside a managed session or ignoring status words.118- Returning blanket algorithm support from the token-session delegate.119- Querying stale token references without observing insertion/removal.120- Declaring signing/decryption/login capabilities not supported by hardware.121- Reusing macOS extension setup in an iOS app target.122123## Review Checklist124125- [ ] Exact platform, extension point, entitlement, and hardware requirements are documented.126- [ ] Optional manager/slot/card objects are guarded.127- [ ] Extension point and driver class are correct for macOS token extensions.128- [ ] Object IDs and key capabilities match real token contents.129- [ ] Delegate support is algorithm-specific.130- [ ] Every APDU runs in a session and validates its status word.131- [ ] PIN flow uses the card's real format and has bounded retry behavior.132- [ ] Token watcher lifetime covers every query that depends on presence.133- [ ] Persistent-reference invalidation is handled.134- [ ] NFC support is checked and every NFC session ends.135136## References137138- [Token and smart-card workflows](references/token-and-smart-card-workflows.md)139- [CryptoTokenKit extended patterns](references/cryptotokenkit-patterns.md)140- [CryptoTokenKit documentation](https://sosumi.ai/documentation/cryptotokenkit)141- [Smart-card entitlement](https://sosumi.ai/documentation/bundleresources/entitlements/com.apple.security.smartcard)