For a clinical dictation app I built, a correct password and a correct six-digit code are not enough to sign in. The request also has to come from a handset the clinic has approved. Sign-in is three server calls: password, second factor, then a proof that this device holds a specific private key. The clinician sees two screens. The third leg has no UI at all.
There are three encoding details in that third leg, and each one fails silently if it is wrong: nothing on the client errors, the server just refuses the proof. This post covers the key, those three details, and the flow around them.
The key
Each handset gets one P-256 key pair. It lives in the keychain, so it survives deleting and reinstalling the app. On a real device the private key is generated inside the Secure Enclave and never leaves it; the app only ever holds a reference.
func makeDeviceKey(tag: Data) throws -> SecKey {
var error: Unmanaged<CFError>?
guard let access = SecAccessControlCreateWithFlags(
nil,
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
.privateKeyUsage,
&error
) else { throw DeviceKeyError.accessControl }
var attributes: [CFString: Any] = [
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
kSecAttrKeySizeInBits: 256,
kSecPrivateKeyAttrs: [
kSecAttrIsPermanent: true,
kSecAttrApplicationTag: tag,
kSecAttrAccessControl: access
] as CFDictionary
]
#if !targetEnvironment(simulator)
attributes[kSecAttrTokenID] = kSecAttrTokenIDSecureEnclave
#endif
guard let key = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
throw DeviceKeyError.generation
}
return key
}
Three choices in there are worth explaining.
No biometry flag on the key. The access control is .privateKeyUsage only. The proof runs silently inside sign-in, and I did not want a Face ID prompt between typing a code and landing in the app. App lock is a separate decision.
After first unlock, this device only. The key is usable in the background once the phone has been unlocked, and it is never carried to another device.
The Simulator has no Secure Enclave. Asking for one fails outright, so simulator builds fall back to an ordinary keychain key with the same curve and wire format. Devices always get the Enclave.
Lookup is load-or-create behind a lock, so two concurrent callers cannot generate two keys. There is deliberately no method to delete or rotate the key. It is the handset's permanent identity. A revoked device is restored by an admin re-approving the same device, never by the app minting a new one. A deliberate sign-out keeps it too, so the same clinician signing back in does not re-enter the approval queue.
Exporting the public key
SecKeyCopyExternalRepresentation returns the public key as raw X9.63: a 04 byte followed by X and Y, 65 bytes. The server wanted SubjectPublicKeyInfo. For P-256 the difference is a fixed 26-byte DER header, so I prepend it by hand.
let spkiHeader = Data([
0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01,
0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00
])
func publicKeySPKI(_ privateKey: SecKey) throws -> String {
guard let publicKey = SecKeyCopyPublicKey(privateKey),
let raw = SecKeyCopyExternalRepresentation(publicKey, nil) as Data?
else { throw DeviceKeyError.export }
return (spkiHeader + raw).base64EncodedString()
}
The result is 91 bytes, 124 base64 characters. That length is a useful sanity check in a log.
Signing the nonce
After the second factor passes, the server returns a challenge token and a nonce. The app signs the nonce and posts the signature with the token; the response is the session.
func sign(nonceHex: String, with key: SecKey) throws -> String {
guard let nonce = Data(hexEncoded: nonceHex), !nonce.isEmpty else {
throw DeviceKeyError.badNonce
}
var error: Unmanaged<CFError>?
guard let signature = SecKeyCreateSignature(
key, .ecdsaSignatureMessageX962SHA256, nonce as CFData, &error
) as Data? else { throw DeviceKeyError.signing }
return signature.base64EncodedString()
}
The details that fail silently:
- The nonce is hex. Sign the bytes it decodes to, not the UTF-8 of the string. Signing the string produces a perfectly valid signature of the wrong message.
- Do not pre-hash. The
Messagevariant of the algorithm does the SHA-256 itself. Hash first and you have signed a hash of a hash. - The signature is DER. That algorithm already emits X9.62 DER, which is what the server verifies. No conversion is needed.
Together with the SPKI export, none of these raises an error on the device. I checked the client's output against a small server-side script that performs the same signature before trusting it.
The nonce is single-use and lives for 60 seconds. That allows one useful bit of resilience: if the proof request fails on transport, the nonce never reached the server, so the app retries once. The clinician does not re-enter a code they already spent.
The second factor
The middle leg accepts one of three methods: a TOTP code from an authenticator app, a recovery code, or a code sent by email. The login challenge is single-use and lasts five minutes. The server allows five wrong codes per challenge and then invalidates it.
Two client behaviours came from those limits. The app treats a challenge as stale at four minutes, not five, because the user still has to type after the screen appears; a stale challenge is replaced by a fresh sign-in instead of being submitted to fail. And when the server reports the challenge dead after five wrong codes, the app restarts the leg and says why, instead of showing a dead end.
Enrolment is a separate chain: redeem an invitation code, set a password, add the authenticator, confirm with a first code. Confirmation returns ten recovery codes, shown exactly once. No endpoint reads them back. If the app is closed on that screen, it remembers that the codes were never acknowledged and says so on the next sign-in form. Enrolment ends without a session; the user then signs in normally.
Admin approval
The public key is sent with the password in the first leg, along with the platform, OS version, app version, model and the handset's system name. The device name is taken from the system so the clinic sees something recognisable in its queue and the clinician is never asked to name anything.
A new key is not trusted. The server answers with a pending-approval code, which the app treats as a destination, not an error: a waiting screen with no red on it, remembered across relaunches.
That screen polls a status endpoint every 30 seconds while it is open. The endpoint takes only the public key, which is what makes the wait pollable at all, since the app holds no TOTP secret and cannot repeat the second factor by itself. It answers one of three things:
| Status | Meaning | App does |
|---|---|---|
| pending | still in the queue | keep waiting |
| approved | queue cleared | offer sign-in again |
| not approved | rejected, revoked, or unknown key | stop polling |
"Approved" is not a session. The clinician still signs in with both factors. "Not approved" deliberately covers a key the server has never seen, so the endpoint cannot be used to find out which keys exist. A failed poll is not news: a 5xx does not raise an alert, the next tick tries again. An unrecognised status string is treated as "keep waiting", because waiting longer costs less than ejecting someone from a queue they are still in.
Revocation uses the same endpoint. When a request comes back with a revoked session, the app clears the token and asks for the device's status. If the device is no longer approved, it wipes the account identifiers and saved biometric login and lands on an "access removed" screen without asking for a password, since the handset may be stolen. If the device is still approved, the session was ended for another reason, and the user is simply asked to sign in again. In both cases the key pair stays.
Takeaways
- Write the three encoding rules (hex nonce, DER signature, SPKI public key) at the top of the file, with the command that verifies them. All three fail the same way and none is discoverable from the error.
- Keep user presence off a key that signs silently. Mixing the device proof with Face ID would have put a prompt in the middle of every sign-in.
- Treat the device key as identity, not a credential. Not being able to rotate it removed a whole class of states: there is no "which key is current" question on either side.
- A status endpoint that takes only a public key must answer the same for "rejected" and "never seen".
- What I would look at next: attestation. The client sends a public key and nothing that proves it was generated in an Enclave. Admin approval covers that gap today, by a person recognising the device.