Reputation: 349
I've been trying to encrypt and decrypt a string in swift using a Diffie Hellman key exchange and an elliptic curve encryption. But after the key exchange I can't restore a private key from a CFData shared1/shared2 variable for decryption. All i get is nil value.
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, *) {
guard let privateKey1 = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {return}
let publicKey1 = SecKeyCopyPublicKey(privateKey1)
guard let privateKey2 = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {return}
let publicKey2 = SecKeyCopyPublicKey(privateKey2)
let dict: [String: Any] = [:]
guard let shared1 = SecKeyCopyKeyExchangeResult(privateKey1, SecKeyAlgorithm.ecdhKeyExchangeStandardX963SHA256, publicKey2!, dict as CFDictionary, &error) else {return}
guard let shared2 = SecKeyCopyKeyExchangeResult(privateKey2, SecKeyAlgorithm.ecdhKeyExchangeStandardX963SHA256, publicKey1!, dict as CFDictionary, &error) else {return}
print(shared1==shared2)
let options: [String: Any] = [kSecAttrKeyType as String: kSecAttrKeyTypeEC,
kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
kSecAttrKeySizeInBits as String : 256]
guard let key = SecKeyCreateWithData(shared1 as CFData,
options as CFDictionary,
&error) else {return}
print(key)
let str = "Hello"
let byteStr: [UInt8] = Array(str.utf8)
let cfData = CFDataCreate(nil, byteStr, byteStr.count)
guard let encrypted = SecKeyCreateEncryptedData(publicKey1!,
SecKeyAlgorithm.eciesEncryptionStandardX963SHA256AESGCM,
cfData!,
&error) else {return}
guard let decrypted = SecKeyCreateDecryptedData(key,
SecKeyAlgorithm.eciesEncryptionStandardX963SHA256AESGCM,
encrypted,
&error) else {return}
print(decrypted)
} else {
print("unsupported")
}
Upvotes: 3
Views: 1407
Reputation: 53
SecKeyFromData
Restores a key from an external representation of that key. The value you're passing to it is not an external representation of a key, it's a shared secret(CFData) just some bytes. You have to derive a key using some KDF on the shared secret then you can use it for encryption and decryption.
And the keys you're using for encryption and decryption are wrong, you have to choose if you want to do asymmetric or symmetric encryption.
SecKeyFromData: https://developer.apple.com/documentation/security/1643701-seckeycreatewithdata
Upvotes: 2