Я пытался быстро зашифровать и расшифровать строку, используя обмен ключами Диффи-Хеллмана и шифрование по эллиптической кривой. Но после обмена ключами я не могу восстановить закрытый ключ из переменной CFData shared1 / shared2 для расшифровки. Все, что я получаю, это нулевое значение.
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")
}