Я пытался зашифровать строку с помощью шифрования эллиптической кривой, используя библиотеку 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")
}