我一直在尝试使用Security swift库加密带有椭圆曲线加密的字符串,我在使用SecKeyCreateEncryptedData(...)
的行上收到错误:
线程1:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)。
我猜数据的长度和格式不符合所选择的算法,但我在文档中找不到任何关于它的信息。
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 str = "Hello"
let byteStr: [UInt8] = Array(str.utf8)
let cfData = CFDataCreate(nil, byteStr, byteStr.count)
guard let encrypted = SecKeyCreateEncryptedData(shared1 as! SecKey, SecKeyAlgorithm.eciesEncryptionStandardX963SHA256AESGCM, cfData!, &error) else {return}
guard let decrypted = SecKeyCreateDecryptedData(shared2 as! SecKey, SecKeyAlgorithm.eciesEncryptionStandardX963SHA256AESGCM, encrypted, &error) else {return}
print(decrypted)
} else {
print("unsupported")
}
答案 0 :(得分:1)
使用
行SecKeyCreateEncryptedData(shared1 as! SecKey, SecKeyAlgorithm.eciesEncryptionStandardX963SHA256AESGCM, cfData!, &error)
您强制shared1
强制转换为SecKey
类型。强制转换(通常)是一个坏主意,在你的情况下它会导致崩溃,因为shared1
不是SecKey
类型,而是CFData?
类型 - 因为那是{{1返回。来自文档:
SecKeyCopyKeyExchangeResult
您可以清楚地看到此函数返回func SecKeyCopyKeyExchangeResult(_ privateKey: SecKey,
_ algorithm: SecKeyAlgorithm,
_ publicKey: SecKey,
_ parameters: CFDictionary,
_ error: UnsafeMutablePointer<Unmanaged<CFError>?>?) -> CFData?