我如何使用Diffie-Hellman密钥交换来加密和解密消息?
我能够生成共享密钥(用于bob和alice),但是SecKeyCopyKeyExchangeResult
向我返回了一个数据...我怎样才能使SecKey与SecKeyCreateDecryptedData
和SecKeyCreateEncryptedData
一起使用?
所以我认为我应该以某种方式从共享数据中提取SecKey,以便可以进行对称加密/解密。
到目前为止的代码是:
let bob_shared_secret: NSData = generateSharedKey_ecdh(publicKey: alicePublicKey, privateKey: bobPrivateKey)!
let alice_shared_secret: NSData = generateSharedKey_ecdh(publicKey: bobPublicKey, privateKey: alicePrivateKey)!
print("equals? \(bob_shared_secret == alice_shared_secret)!") //true
let clearText = "Hello From Alice"
let algorithm: SecKeyAlgorithm = .eciesEncryptionCofactorVariableIVX963SHA256AESGCM
let cipherTextData: Data? = SecKeyCreateEncryptedData(alicePublicKey, algorithm,
clearTextData as CFData,
&error) as Data?
let clearTextData = SecKeyCreateDecryptedData(???? as SecKey, //what to put here??
algorithm,
cipherTextData as CFData,
&error) as Data?
private func generateSharedKey_ecdh(publicKey: SecKey, privateKey: SecKey) -> NSData?
{
var error: Unmanaged<CFError>?
let keyPairAttr:[String : Any] = [
kSecAttrKeySizeInBits as String: 256, //retro compatibility
kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, //Elliptic curve algorithm.
kSecPrivateKeyAttrs as String: [kSecAttrIsPermanent as String: false],
kSecPublicKeyAttrs as String:[kSecAttrIsPermanent as String: false],
SecKeyKeyExchangeParameter.requestedSize.rawValue as String: 256
]
let algorithm:SecKeyAlgorithm = SecKeyAlgorithm.ecdhKeyExchangeStandardX963SHA256
let shared:CFData? = SecKeyCopyKeyExchangeResult(privateKey, algorithm, publicKey, keyPairAttr as CFDictionary, &error)
return shared
}
密钥对生成...密钥对,这是我创建的包含密钥的类
class KeyPair {
var publicKey: SecKey
var privateKey: SecKey
init(publicKey: SecKey, privateKey: SecKey) {
self.publicKey = publicKey
self.privateKey = privateKey
}
}
private func generateKeyPair() -> KeyPair? {
let attributes: [String: Any] = [kSecAttrKeySizeInBits as String: 256,
kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
kSecPrivateKeyAttrs as String: [kSecAttrIsPermanent as String: false],
kSecPublicKeyAttrs as String:[kSecAttrIsPermanent as String: false]]
var error: Unmanaged<CFError>?
if let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error),
let publicKey = SecKeyCopyPublicKey(privateKey){
return KeyPair(publicKey: publicKey, privateKey: privateKey)
}
return nil
}
[SecKeyCreateEncryptedData和SecKeyCreateDecryptedData用于不对称加密(使用ECIES或RSA)
要执行对称加密/解密操作,您应该使用通用加密或像加密快速(https://github.com/krzyzanowskim/CryptoSwift)和AES算法一样对其进行封装