Generating a Key Pair with iOS’s Secure Enclave in Swift

I found it impossible to find a segment of code which showed how to generate a secure key pair in the enclave with swift for iOS 9. So… here it is!


    // private key parameters
    let privateKeyParams: [String: AnyObject] = [
        kSecAttrLabel as String: "privateLabel",
        kSecAttrIsPermanent as String: true,
        kSecAttrApplicationTag as String: "applicationTag"
    ]        
    // public key parameters
    let publicKeyParams: [String: AnyObject] = [
        kSecAttrLabel as String: "publicLabel",
        kSecAttrIsPermanent as String: false,
        kSecAttrApplicationTag as String: "applicationTag"
    ]

    // global parameters
    let parameters: [String: AnyObject] = [
        kSecAttrKeyType as String: kSecAttrKeyTypeEC,
        kSecAttrKeySizeInBits as String: 256,
        kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave,
        kSecPublicKeyAttrs as String: publicKeyParams,
        kSecPrivateKeyAttrs as String: privateKeyParams
    ]        

    var pubKey, privKey: SecKeyRef?
    let status = SecKeyGeneratePair(parameters, &pubKey, &privKey)

Note the addition of the TokenID attribute in the global parameters which specifies we are generating the key pair in the enclave. Also note that the public key is not set to be stored permanently. Instead, the public key must be added to the keychain after performing the generation. Finally, at the time of writing, only elliptic curve keys with a 256 bit length are supported.

11 thoughts on “Generating a Key Pair with iOS’s Secure Enclave in Swift

  1. Thanks for this tutorial. Do you happened to make a valid SecKeyRawSign call with the generate private key after the generation? Keep getting an error after this… (-25293). Thanks.

    Like

    1. Really good question and I was faced with this when starting out. One way we did this was to make sure that the code worked on a real device but not in a simulator as the simulators don’t support use of the secure enclave. You can also try to pull the key out of the keychain – this should fail.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s