我一直在尝试使用Diffie Hellman密钥交换和椭圆曲线加密来加密和解密Swift中的字符串。但是,在密钥交换之后,我无法从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")
}
SecKeyCreateRandomKey
。我认为在安全框架中不能显式地创建对称密钥,您必须使用SecKeyCreateEncryptedData
,它会创建对称密钥,使用该密钥加密数据,然后使用您提供的公钥加密密钥本身。详细解释请参见此处。 - AdmiralAnk