Loading...
Loading...
Access security tokens and smart cards using CryptoTokenKit. Use when building token driver extensions with TKTokenDriver and TKToken, communicating with smart cards via TKSmartCard, implementing certificate-based authentication, managing token sessions, or integrating hardware security tokens with the system keychain.
npx skill4agent add dpearson2699/swift-ios-skills cryptotokenkitTKSmartCardTKSmartCardSlotManagerTKTokenDriverTKTokenTKTokenSessionTKTokenWatcherkSecAttrTokenID| Type | Role | Platform |
|---|---|---|
| Base class for token driver extensions | macOS |
| Represents a hardware cryptographic token | macOS |
| Manages authentication state for a token | macOS |
| Entry point for smart card extensions | macOS |
| Low-level smart card communication | macOS |
| Discovers and manages card reader slots | macOS |
| Observes token insertion and removal | macOS, iOS 14+ |
| A key stored on a token | macOS |
| A certificate stored on a token | macOS |
TKSmartCardTokenDriverTKSmartCardTokenTKSmartCardTokenSessionimport CryptoTokenKit
final class TokenDriver: TKSmartCardTokenDriver, TKSmartCardTokenDriverDelegate {
func tokenDriver(
_ driver: TKSmartCardTokenDriver,
createTokenFor smartCard: TKSmartCard,
aid: Data?
) throws -> TKSmartCardToken {
return try Token(
smartCard: smartCard,
aid: aid,
instanceID: "com.example.token:\(smartCard.slot.name)",
tokenDriver: driver
)
}
}final class Token: TKSmartCardToken, TKTokenDelegate {
init(
smartCard: TKSmartCard, aid: Data?,
instanceID: String, tokenDriver: TKSmartCardTokenDriver
) throws {
try super.init(
smartCard: smartCard, aid: aid,
instanceID: instanceID, tokenDriver: tokenDriver
)
self.delegate = self
let certData = try readCertificate(from: smartCard)
guard let cert = SecCertificateCreateWithData(nil, certData as CFData) else {
throw TKError(.corruptedData)
}
let certItem = TKTokenKeychainCertificate(certificate: cert, objectID: "cert-auth")
let keyItem = TKTokenKeychainKey(certificate: cert, objectID: "key-auth")
keyItem?.canSign = true
keyItem?.canDecrypt = false
keyItem?.isSuitableForLogin = true
self.keychainContents?.fill(with: [certItem!, keyItem!])
}
func createSession(_ token: TKToken) throws -> TKTokenSession {
TokenSession(token: token)
}
}Info.plistNSExtension
NSExtensionAttributes
com.apple.ctk.driver-class = $(PRODUCT_MODULE_NAME).TokenDriver
NSExtensionPointIdentifier = com.apple.ctk-tokens_securityagentsudo -u _securityagent /Applications/TokenHost.app/Contents/MacOS/TokenHostTKTokenSessionfinal class TokenSession: TKSmartCardTokenSession, TKTokenSessionDelegate {
func tokenSession(
_ session: TKTokenSession,
supports operation: TKTokenOperation,
keyObjectID: TKToken.ObjectID,
algorithm: TKTokenKeyAlgorithm
) -> Bool {
switch operation {
case .signData:
return algorithm.isAlgorithm(.rsaSignatureDigestPKCS1v15SHA256)
|| algorithm.isAlgorithm(.ecdsaSignatureDigestX962SHA256)
case .decryptData:
return algorithm.isAlgorithm(.rsaEncryptionOAEPSHA256)
case .performKeyExchange:
return algorithm.isAlgorithm(.ecdhKeyExchangeStandard)
default:
return false
}
}
func tokenSession(
_ session: TKTokenSession,
sign dataToSign: Data,
keyObjectID: TKToken.ObjectID,
algorithm: TKTokenKeyAlgorithm
) throws -> Data {
let smartCard = try getSmartCard()
return try smartCard.withSession {
try performCardSign(smartCard: smartCard, data: dataToSign, keyID: keyObjectID)
}
}
func tokenSession(
_ session: TKTokenSession,
decrypt ciphertext: Data,
keyObjectID: TKToken.ObjectID,
algorithm: TKTokenKeyAlgorithm
) throws -> Data {
let smartCard = try getSmartCard()
return try smartCard.withSession {
try performCardDecrypt(smartCard: smartCard, data: ciphertext, keyID: keyObjectID)
}
}
}TKTokenAuthOperationbeginAuthFor:func tokenSession(
_ session: TKTokenSession,
beginAuthFor operation: TKTokenOperation,
constraint: Any
) throws -> TKTokenAuthOperation {
let pinAuth = TKTokenSmartCardPINAuthOperation()
pinAuth.pinFormat.charset = .numeric
pinAuth.pinFormat.minPINLength = 4
pinAuth.pinFormat.maxPINLength = 8
pinAuth.smartCard = (session as? TKSmartCardTokenSession)?.smartCard
pinAuth.apduTemplate = buildVerifyAPDU()
pinAuth.pinByteOffset = 5
return pinAuth
}TKSmartCardimport CryptoTokenKit
func discoverSmartCards() {
guard let slotManager = TKSmartCardSlotManager.default else {
print("Smart card services unavailable")
return
}
for slotName in slotManager.slotNames {
slotManager.getSlot(withName: slotName) { slot in
guard let slot else { return }
if slot.state == .validCard, let card = slot.makeSmartCard() {
communicateWith(card: card)
}
}
}
}send(ins:p1:p2:data:le:)withSessionfunc selectApplication(card: TKSmartCard, aid: Data) throws {
try card.withSession {
let (sw, response) = try card.send(
ins: 0xA4, p1: 0x04, p2: 0x00, data: aid, le: nil
)
guard sw == 0x9000 else {
throw TKError(.communicationError)
}
}
}transmit(_:reply:)beginSessionendSessionfunc readNFCSmartCard() {
guard let slotManager = TKSmartCardSlotManager.default,
slotManager.isNFCSupported() else { return }
slotManager.createNFCSlot(message: "Hold card near iPhone") { session, error in
guard let session else { return }
defer { session.end() }
guard let slotName = session.slotName,
let slot = slotManager.slotNamed(slotName),
let card = slot.makeSmartCard() else { return }
// Communicate with the NFC card using card.send(...)
}
}kSecAttrTokenIDimport Security
func findTokenKey(tokenID: String) throws -> SecKey {
let query: [String: Any] = [
kSecClass as String: kSecClassKey,
kSecAttrTokenID as String: tokenID,
kSecReturnRef as String: true
]
var result: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &result)
guard status == errSecSuccess, let key = result else {
throw TKError(.objectNotFound)
}
return key as! SecKey
}kSecReturnPersistentRefkSecReturnReferrSecItemNotFoundkSecClass: kSecClassCertificatekSecAttrKeyTypeECSECPrimeRandomecdhKeyExchangeStandardkSecAttrKeyTypeRSArsaEncryptionOAEPSHA256com.apple.security.smartcard| Key | Default | Description |
|---|---|---|
| | Enable smart card authentication |
| | Certificate trust level (0-3) |
| | Pair a single smart card to an account |
| | Require smart card for login |
0123TKTokenWatcherimport CryptoTokenKit
final class TokenMonitor {
private let watcher = TKTokenWatcher()
func startMonitoring() {
for tokenID in watcher.tokenIDs {
print("Token present: \(tokenID)")
if let info = watcher.tokenInfo(forTokenID: tokenID) {
print(" Driver: \(info.driverName ?? "unknown")")
print(" Slot: \(info.slotName ?? "unknown")")
}
}
watcher.setInsertionHandler { [weak self] tokenID in
print("Token inserted: \(tokenID)")
self?.watcher.addRemovalHandler({ removedTokenID in
print("Token removed: \(removedTokenID)")
}, forTokenID: tokenID)
}
}
}TKError| Code | Meaning |
|---|---|
| Operation not supported by this token |
| Communication with token failed |
| Data from token is corrupted |
| User canceled the operation |
| PIN or password incorrect |
| Requested key or certificate not found |
| Token is no longer present |
| Authentication required before operation |
// WRONG -- query may fail if token was removed
let key = try findTokenKey(tokenID: savedTokenID)
// CORRECT -- verify the token is still present first
let watcher = TKTokenWatcher()
guard watcher.tokenIDs.contains(savedTokenID) else {
promptUserToInsertToken()
return
}
let key = try findTokenKey(tokenID: savedTokenID)// WRONG -- TKSmartCardSlotManager.default is nil on iOS
let manager = TKSmartCardSlotManager.default! // Crashes on iOS
// CORRECT -- guard availability
guard let manager = TKSmartCardSlotManager.default else {
print("Smart card services unavailable on this platform")
return
}// WRONG -- sending commands without a session
card.transmit(apdu) { response, error in /* may fail */ }
// CORRECT -- use withSession or beginSession/endSession
try card.withSession {
let (sw, response) = try card.send(
ins: 0xCA, p1: 0x00, p2: 0x6E, data: nil, le: 0
)
}// WRONG -- assuming success
let (_, response) = try card.send(ins: 0xA4, p1: 0x04, p2: 0x00, data: aid, le: nil)
// CORRECT -- check status word
let (sw, response) = try card.send(ins: 0xA4, p1: 0x04, p2: 0x00, data: aid, le: nil)
guard sw == 0x9000 else {
throw SmartCardError.commandFailed(statusWord: sw)
}supportstrueTKSmartCardTKTokenWatcherNSExtensionPointIdentifiercom.apple.ctk-tokenscom.apple.ctk.driver-class_securityagentTKTokenSessionDelegatetruewithSessionbeginSessionendSessionsendTKTokenWatcherTKErrorobjectIDTKTokenKeychainKeycanSigncanDecrypterrSecItemNotFound