iOS - how to perform sharedSecretFromKeyAgreement in iOS 12

959 Views Asked by At

Recently Apple with iOS 13 introduced CryptoKit which has a method sharedSecretFromKeyAgreement which generates a shared secret from key agreement between public and private keys. How can this be achieved in iOS 12 and below ?

iOS 13

import CryptoKit

let alicePrivateKey = P256.KeyAgreement.PrivateKey()
let alicePublicKey = alicePrivateKey.publicKey

let eileenPrivateKey = P256.KeyAgreement.PrivateKey()
let eileenPublicKey = eileenPrivateKey.publicKey

let shared1 = try alicePrivateKey.sharedSecretFromKeyAgreement(with: eileenPublicKey)
let shared2 = try eileenPrivateKey.sharedSecretFromKeyAgreement(with: alicePublicKey)

if shared1 == shared2 {
    print("shared keys are equal")
}
2

There are 2 best solutions below

0
On

I have used SecKeyCopyKeyExchangeResult from iOS which works fine without issues. only thing to make sure is ecSecPrivateKey and ecSecPrivateKey below used should be in Seckey format and should work fine.

 guard let derivedData = SecKeyCopyKeyExchangeResult(
                ecSecPrivateKey,
                SecKeyAlgorithm.ecdhKeyExchangeStandard,
                ecSecPublicKey,
                parameters as CFDictionary,
                &error)
                else {
                return
            }
1
On
import CryptoKit
import Foundation

let bobsPrivateKey = P521.KeyAgreement.PrivateKey()
let bobsPublicKey = bobsPrivateKey.publicKey

let alicesPrivateKey = P521.KeyAgreement.PrivateKey()
let alicesPublicKey = alicesPrivateKey.publicKey

let shared1 = try alicesPrivateKey.sharedSecretFromKeyAgreement(with: bobsPublicKey)
let shared2 = try bobsPrivateKey.sharedSecretFromKeyAgreement(with: alicesPublicKey)

if shared1 == shared2 {
    print("shared keys are equal")
}