【问题标题】:iOS - how to perform sharedSecretFromKeyAgreement in iOS 12iOS - 如何在 iOS 12 中执行 sharedSecretFromKeyAgreement
【发布时间】:2020-05-30 13:53:01
【问题描述】:
最近,Apple 在 iOS 13 中引入了 CryptoKit,它有一个方法 sharedSecretFromKeyAgreement,它根据公钥和私钥之间的密钥协议生成共享密钥。这如何在 iOS 12 及更低版本中实现?
iOS 13
import CryptoKit
let alicePrivateKey = P256.KeyAgreement.PrivateKey()
let alicePublicKey = alicePrivateKey.publicKey
let eileenPrivateKey = P256.KeyAgreement.PrivateKey()
let eileenPublicKey = eileenPrivateKey.publicKey
let shared1 = try alicePrivateKey.sharedSecretFromKeyAgreement(with: eileenPublicKey)
let shared2 = try eileenPrivateKey.sharedSecretFromKeyAgreement(with: alicePublicKey)
if shared1 == shared2 {
print("shared keys are equal")
}
【问题讨论】:
标签:
ios
swift
cryptography
apple-cryptokit
【解决方案1】:
import CryptoKit
import Foundation
let bobsPrivateKey = P521.KeyAgreement.PrivateKey()
let bobsPublicKey = bobsPrivateKey.publicKey
let alicesPrivateKey = P521.KeyAgreement.PrivateKey()
let alicesPublicKey = alicesPrivateKey.publicKey
let shared1 = try alicesPrivateKey.sharedSecretFromKeyAgreement(with: bobsPublicKey)
let shared2 = try bobsPrivateKey.sharedSecretFromKeyAgreement(with: alicesPublicKey)
if shared1 == shared2 {
print("shared keys are equal")
}
【解决方案2】:
我使用了 iOS 的 SecKeyCopyKeyExchangeResult,它运行良好,没有问题。
唯一需要确定的是,下面使用的 ecSecPrivateKey 和 ecSecPrivateKey 应该是 Seckey 格式并且应该可以正常工作。
guard let derivedData = SecKeyCopyKeyExchangeResult(
ecSecPrivateKey,
SecKeyAlgorithm.ecdhKeyExchangeStandard,
ecSecPublicKey,
parameters as CFDictionary,
&error)
else {
return
}