4

我一直在尝试使用 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")
}
4

1 回答 1

2

随着线

SecKeyCreateEncryptedData(shared1 as! SecKey, SecKeyAlgorithm.eciesEncryptionStandardX963SHA256AESGCM, cfData!, &error)

你是强制转换shared1类型SecKey。强制转换(通常)是一个坏主意,在你的情况下它会产生崩溃,因为shared1不是SecKey类型,而是CFData?类型 - 因为这是SecKeyCopyKeyExchangeResult返回的。从文档:

func SecKeyCopyKeyExchangeResult(_ privateKey: SecKey, 
                           _ algorithm: SecKeyAlgorithm, 
                           _ publicKey: SecKey, 
                           _ parameters: CFDictionary, 
                           _ error: UnsafeMutablePointer<Unmanaged<CFError>?>?) -> CFData?

你可以清楚地看到这个函数返回CFData?

于 2018-04-25T10:11:53.917 回答