10

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

Zohar Etzioni
  • 611
  • 5
  • 13
  • Have you had a look at `SecKeyCopyKeyExchangeResult`? – Mats Sep 19 '17 at 14:56
  • @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 Sep 21 '17 at 05:40
  • The `SecKey.h` header file may have some additional info that is not in the online documentation. – Mats Sep 21 '17 at 08:23
  • @Mats I got it. Finally. Thanks for your help. – Zohar Etzioni Sep 21 '17 at 08:29
  • 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 Sep 21 '17 at 09:32

3 Answers3

27

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

Zohar Etzioni
  • 611
  • 5
  • 13
  • 2
    Is there any way to compute public and private for specific domain parameter ('p', 'b' and 'a') – Hamed Nov 18 '18 at 06:15
  • How can i crypt and decrypt messages using the shared key data? The function `SecKeyCreateEncryptedData` asks a SecKey as parameter...but i get data – Fabiosoft Apr 07 '20 at 22:25
  • @Zohar Etzioni can I use SecKeyCopyKeyExchangeResult for public JWK keys ? and if so is there any example code ? – Max May 28 '20 at 13:52
1

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

OutOnAWeekend
  • 1,298
  • 1
  • 17
  • 34
1

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")
       }
virtplay
  • 340
  • 3
  • 15