Hello,
I am currently working on iOS application development using Swift, targeting iOS 17 and above, and need to implement mTLS for network connections.
In the registration API flow, the app generates a private key and CSR on the device, sends the CSR to the server (via the registration API), and receives back the signed client certificate (CRT) along with the intermediate/CA certificate. These certificates are then imported on the device.
The challenge I am facing is pairing the received CRT with the previously generated private key in order to create a SecIdentity.
Could you please suggest the correct approach to generate a SecIdentity in this scenario? If there are any sample code snippets, WWDC videos, or documentation references available, I would greatly appreciate it if you could share them.
Thank you for your guidance.
I’m presuming you want the resulting digital identity to be persistent, that is, to survive your app being terminated and relaunched. If so, you need to store the private key and the certificate somewhere, and the best place for storing credentials like this is the keychain.
Standard practice here is:
- Generate the private key in the keychain.
- Derive the public key from the private key.
- Export the public key bits and send that your certificate issuing infrastructure.
- Get back the certificate.
- Add that to your keychain.
- Get a digital identity from the keychain.
There are various APIs to support this:
- In step 1, use
SecKeyCreateRandomKey
. - In step 2, use
SecKeyCopyPublicKey
. - In step 3, use
SecKeyCopyExternalRepresentation
. - In step 4, if the server sends you back a PEM, you’ll need to decode that to get a DER. You can then import that using
SecCertificateCreateWithData
. - In step 5, use
SecItemAdd
. - In step 6, use
SecItemCopyMatching
.
We have a bunch of resources that can help with this. I recommend that you review the Security Resources pinned post. I specifically recommend:
- On Cryptographic Key Formats — This explains the format of the data you get back from
SecKeyCopyPublicKey
, which may not what you’re expecting )-: - SecItem Fundamentals and SecItem Pitfalls and Best Practices — The SecItem API can be confusing, and these posts should set you straight.
- Importing a PEM-based RSA Private Key and its Certificate — This describes a specific workflow. It doesn’t match your workflow exactly, but the second half — the bit about importing the certificate and getting the digital identity — should be of interest.
All of the above works for RSA or EC keys. If you’re only interested in EC keys, you can:
- Do some of these steps more easily using Apple CryptoKit.
- Protect the key with the Secure Enclave.
Let me know if that’s the case and I can point you at more resources.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"