10
votes

Does iOS expose API for key generation, and secret key derivation using ECDH?

From what I see, apple are using it (and specifically x25519) internally but I don't see it exposed as public API by common crypto or otherwise.

Thanks,

Z

3
Have you had a look at SecKeyCopyKeyExchangeResult? - Mats
@Mats thanks - I did, and it seems relevant, but unfortunately the documentation is so poor and cryptic that it's hard to tell how to use it and if it does what I want it to do. - Zohar Etzioni
The SecKey.h header file may have some additional info that is not in the online documentation. - Mats
@Mats I got it. Finally. Thanks for your help. - Zohar Etzioni
If you have the time, please consider writing a more elaborate answer to your question. It could be a small code example demonstrating how you use the API. - Mats

3 Answers

28
votes

Done in playground with Xcode 8.3.3, generates a private/public key using EC for Alice, Bob, then calculating the shared secret for Alice using Alice's private and Bob's public, and share secret for Bob using Bob's private and Alice's public and finally asserting that they're equal.

import Security
import UIKit

let attributes: [String: Any] =
    [kSecAttrKeySizeInBits as String:      256,
     kSecAttrKeyType as String: kSecAttrKeyTypeEC,
     kSecPrivateKeyAttrs as String:
        [kSecAttrIsPermanent as String:    false]
]

var error: Unmanaged<CFError>?
if #available(iOS 10.0, *) {
    // generate a key for alice
    guard let privateKey1 = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
        throw error!.takeRetainedValue() as Error
    }
    let publicKey1 = SecKeyCopyPublicKey(privateKey1)

    // generate a key for bob
    guard let privateKey2 = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
        throw error!.takeRetainedValue() as Error
    }
    let publicKey2 = SecKeyCopyPublicKey(privateKey2)

    let dict: [String: Any] = [:]

    // alice is calculating the shared secret
    guard let shared1 = SecKeyCopyKeyExchangeResult(privateKey1, SecKeyAlgorithm.ecdhKeyExchangeStandardX963SHA256, publicKey2!, dict as     CFDictionary, &error) else {
        throw error!.takeRetainedValue() as Error
    }

    // bob is calculating the shared secret
    guard let shared2 = SecKeyCopyKeyExchangeResult(privateKey2, SecKeyAlgorithm.ecdhKeyExchangeStandardX963SHA256, publicKey1!, dict as CFDictionary, &error) else {
        throw error!.takeRetainedValue() as Error
    }

    print(shared1==shared2)


} else {
    // Fallback on earlier versions
    print("unsupported")
}

Thanks @Mats for sending me in the right direction..3

1
votes

Circa - 2020 and iOS13. In Zohar's code snippet below, also specify a key size in the dictionary before attempting to get the shared secrets.

let dict: [String: Any] = [SecKeyKeyExchangeParameter.requestedSize.rawValue as String: 32]

Or there would be an error saying this.

kSecKeyKeyExchangeParameterRequestedSize is missing

1
votes

Here is the latest code with swift 5 and changes in parameters.

var error: Unmanaged<CFError>?
  
       let keyPairAttr:[String : Any] = [kSecAttrKeySizeInBits as String: 256,
                                         SecKeyKeyExchangeParameter.requestedSize.rawValue as String: 32,
                                         kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
                                         kSecPrivateKeyAttrs as String: [kSecAttrIsPermanent as String: false],
                                         kSecPublicKeyAttrs as String:[kSecAttrIsPermanent as String: false]]
       let algorithm:SecKeyAlgorithm = SecKeyAlgorithm.ecdhKeyExchangeStandardX963SHA256//ecdhKeyExchangeStandardX963SHA256
       
       do {
           guard let privateKey = SecKeyCreateRandomKey(keyPairAttr as CFDictionary, &error) else {
               throw error!.takeRetainedValue() as Error
           }
           let publicKey = SecKeyCopyPublicKey(privateKey)
           print("public ky1: \(String(describing: publicKey)),\n private key: \(privateKey)")
           
        
           
           guard let privateKey2 = SecKeyCreateRandomKey(keyPairAttr as CFDictionary, &error) else {
               throw error!.takeRetainedValue() as Error
           }
           let publicKey2 = SecKeyCopyPublicKey(privateKey2)
           print("public ky2: \(String(describing: publicKey2)),\n private key2: \(privateKey2)")

           
           
           let shared:CFData? = SecKeyCopyKeyExchangeResult(privateKey, algorithm, publicKey2!, keyPairAttr as CFDictionary, &error)
           let sharedData:Data = shared! as Data
           print("shared Secret key: \(sharedData.hexEncodedString())")

           let shared2:CFData? = SecKeyCopyKeyExchangeResult(privateKey2, algorithm, publicKey!, keyPairAttr as CFDictionary, &error)
           let sharedData2:Data = shared2! as Data
           print("shared Secret key 2: \(sharedData2.hexEncodedString())")
           
           // shared secret key and shared secret key 2 should be same
       
       } catch let error as NSError {
           print("error: \(error)")
       } catch  {
           print("unknown error")
       }