CryptoTokenKit
Use CryptoTokenKit for token driver extensions, smart-card communication, token sessions, token-backed keychain integration, and certificate-based authentication in Swift 6.3 apps.
Platform availability: CryptoTokenKit classes are available across Apple
platforms, but capability depends on extension point, entitlement, hardware, and
OS version. The smart-card app extension flow for login/keychain unlock is macOS.
TKSmartCardSlotManager.default is optional and returns nil unless smart-card
access is enabled. iOS/iPadOS 26+ add NFC smart-card slots and registration.
Contents
- Architecture Overview
- Token Extensions
- Token Sessions
- Smart Card Communication
- Keychain Integration
- Certificate Authentication
- Token Watching
- Error Handling
- Common Mistakes
- Review Checklist
- References
Architecture Overview
CryptoTokenKit bridges hardware security tokens (smart cards, USB tokens) with authentication and keychain services. The framework has three main usage modes:
Smart-card token extensions -- macOS app extensions that make a hardware token's cryptographic items available to system login and keychain unlock. The driver handles token lifecycle, session management, and cryptographic operations.
Client-side token access -- Apps query the keychain for items backed by tokens. CryptoTokenKit exposes token items as standard keychain entries when a token is present.
NFC smart-card access -- iOS/iPadOS 26+ apps create a temporary NFC smart
card slot and communicate with the presented contactless card through
TKSmartCard.
Boundary routing: Own token/smart-card sessions, token-backed keychain
items, and certificate-based smart-card auth. Route passkeys/WebAuthn and
account sign-in to authentication; route Secure Enclave, CryptoKit primitives,
keychain architecture, certificate pinning, and trust policy to swift-security.
Key Types
Token Extensions
For system login and keychain unlock on macOS, a token driver is an app extension that makes a hardware token's cryptographic capabilities available to the system. The host app exists only as a delivery mechanism for the extension.
A smart card token extension has three core classes:
- TokenDriver (subclass of
TKSmartCardTokenDriver) -- entry point - Token (subclass of
TKSmartCardToken) -- represents the token - TokenSession (subclass of
TKSmartCardTokenSession) -- handles operations
Driver Class
Token Class
The token reads certificates and keys from hardware and populates its keychain contents:
Info.plist and Registration
The extension's Info.plist must name the driver class:
Register the extension once by launching the host app as _securityagent:
Token Sessions
TKTokenSession manages authentication state and performs cryptographic
operations via its delegate.
PIN Authentication
Return a TKTokenAuthOperation from beginAuthFor: to prompt the user
for PIN entry before cryptographic operations:
Smart Card Communication
TKSmartCard provides low-level APDU communication with smart cards.
TKSmartCardSlotManager.default is optional; treat nil as unavailable
hardware, missing entitlement/access, or unsupported runtime capability.
Discovering Card Readers
Sending APDU Commands
Use send(ins:p1:p2:data:le:) for structured APDU communication.
Always wrap calls in withSession:
For raw APDU bytes or non-standard formats, use transmit(_:reply:) with
manual beginSession/endSession lifecycle management.
NFC Smart Card Sessions (iOS/iPadOS 26+)
On iOS/iPadOS 26+, guard isNFCSupported() before calling
createNFCSlot(message:completion:) to communicate with contactless cards:
Keychain Integration
When a token is present, CryptoTokenKit exposes its items as standard
keychain entries. Query them using the kSecAttrTokenID attribute:
Use kSecReturnPersistentRef instead of kSecReturnRef to obtain a
persistent reference that survives across app launches. The reference
becomes invalid when the token is removed -- handle errSecItemNotFound
by prompting the user to reinsert the token.
Query certificates the same way with kSecClass: kSecClassCertificate.
Certificate Authentication
Token Key Requirements
For user login, the token must contain at least one key capable of signing with: EC signature digest X962, RSA signature digest PSS, or RSA signature digest PKCS1v15.
For keychain unlock, the token needs:
- 256-bit EC key (
kSecAttrKeyTypeECSECPrimeRandom) supportingecdhKeyExchangeStandard, or - 2048/3072/4096-bit RSA key (
kSecAttrKeyTypeRSA) supportingrsaEncryptionOAEPSHA256decryption
Smart Card Authentication Preferences (macOS)
Configure in the com.apple.security.smartcard domain (MDM or systemwide):
Trust levels: 0 = trust all, 1 = validity + issuer, 2 = + soft
revocation, 3 = + hard revocation.
Token Watching
TKTokenWatcher monitors token insertion and removal. Available on iOS 10+
and macOS 10.12+. Enumerate tokenIDs, install an insertion handler, then add a
removal handler for each observed token. Keep the watcher alive for as long as
monitoring is required. For slot-level reader state, use
Smart Card Slot Monitoring [blocked].
Error Handling
CryptoTokenKit operations throw TKError. Key error codes:
Common Mistakes
DON'T: Query token keychain items without checking token presence
DON'T: Treat API availability as an access guarantee
DON'T: Skip session management for card communication
DON'T: Ignore status words in APDU responses
DON'T: Hard-code blanket algorithm support
The supports delegate method must reflect what the hardware actually
implements. Returning true unconditionally causes runtime failures when
the system attempts unsupported operations.
Review Checklist
- Platform availability verified for the exact capability (
TKTokenWatcheriOS 10+, NFC smart-card sessions iOS/iPadOS 26+) -
TKSmartCardSlotManager.defaultguarded for missing entitlement, hardware, or runtime support - macOS token extension target uses
NSExtensionPointIdentifier=com.apple.ctk-tokens -
com.apple.ctk.driver-classset to the correct driver class in Info.plist - Extension registered via
_securityagentlaunch during installation -
TKTokenSessionDelegatechecks specific algorithms, not blankettrue - Smart card sessions opened and closed (
withSessionorbeginSession/endSession) - APDU status words checked after every
sendcall - Token presence verified via
TKTokenWatcherbefore keychain queries -
TKErrorcases handled with appropriate user feedback - Keychain contents populated with correct
objectIDvalues -
TKTokenKeychainKeycapabilities (canSign,canDecrypt) match hardware - Certificate trust level configured appropriately for deployment environment
-
errSecItemNotFoundhandled for persistent references when token is removed - iOS 26+ NFC sessions ended with
TKSmartCardSlotNFCSession.end()
References
- Extended patterns (PIV commands, TLV parsing, generic token drivers, APDU helpers, secure PIN): references/cryptotokenkit-patterns.md [blocked]
- TKTokenDriver
- TKToken
- TKTokenSession
- TKSmartCard
- TKSmartCardSlotManager
- com.apple.security.smartcard entitlement
- TKSmartCardSlotNFCSession
- TKSmartCardTokenRegistrationManager
- TKTokenWatcher
- Authenticating Users with a Cryptographic Token
- Using Cryptographic Assets Stored on a Smart Card
- Configuring Smart Card Authentication


