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
}