Swift: creating shared secret using public and private keys using swift

I am trying to convert an ephemeralKey which is a series of bytes to an Elliptic Curve public key and then use it to create a shared key using my private key. I know how to do this in python (code below). But I cannot find a way to do this in Swift. My swift code is also copied below but it is not correct. Do you see the problem with my swift code?

My python code:

from cryptography.hazmat.primitives.asymmetric import ec

devicePublicKey = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), ephemeralKey)
sharedKey = privateKey.exchange(ec.ECDH(), devicePublicKey)

My swift code:

let attributes: [String:Any] =
        [
            kSecAttrKeyClass as String: kSecAttrKeyClassPublic,
            kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
            kSecAttrKeySizeInBits as String: 256,
        ]
let devicePublicKey = SecKeyCreateWithData(ephemeralKey as CFData, attributes as CFDictionary, nil)!
let sharedKey = ecdhSecretCalculation(publicKey: devicePublicKey, privateKey: privateKey) 

func ecdhSecretCalculation(publicKey: SecKey, privateKey: SecKey) -> Data? {
        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 = .ecdhKeyExchangeStandardX963SHA256
        
        let shared = SecKeyCopyKeyExchangeResult(privateKey, algorithm, publicKey, keyPairAttr as CFDictionary, &error) as Data?
        
        return shared
}

I am trying to convert an ephemeralKey which is a series of bytes

It’s hard to offer advice without know more about how your key is formatted. I have a long post, On Cryptographic Key Formats, that discusses this in detail. There’s also a companion post, Importing Cryptographic Keys, that shows how to import the common formats.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Swift: creating shared secret using public and private keys using swift
 
 
Q