我已经使用必需的属性创建了私钥和公钥对。密钥对生成并保存在 Mac keychain 中。我使用 KeyChain 访问检查了私钥和公钥。但是当我尝试检索它时,它会通过说找不到密钥来抛出错误。
我在下面分享了检索密钥的代码片段
func retrievePrivateKey(_ algorithm: KeyAlgorithm, keySize: Int, tagPrivate: String) throws -> SecKey {
let getQuery: [String: Any] = [kSecClass as String: kSecClassKey,
kSecAttrApplicationTag as String: tagPrivate,
kSecAttrKeyType as String: algorithm.secKeyAttrType,
kSecReturnRef as String: true]
var item: CFTypeRef?
let status = SecItemCopyMatching(getQuery as CFDictionary,&item)
var error: Unmanaged<CFError>?
guard status == errSecSuccess else {throw error!.takeRetainedValue() as Error}
let privateKey = item as! SecKey
return privateKey;
}
func generateKeyPair(_ algorithm: KeyAlgorithm, keySize: Int, tagPrivate: String, tagPublic: String) {
let publicKeyParameters: [String : AnyObject] = [
String(kSecAttrIsPermanent): kCFBooleanTrue,
String(kSecAttrApplicationTag): tagPublic as AnyObject,
String(kSecAttrAccessible): kSecAttrAccessibleAfterFirstUnlock,
]
let privateKeyParameters: [String: AnyObject] = [
String(kSecAttrIsPermanent) : kCFBooleanTrue,
String(kSecAttrApplicationTag) : tagPrivate as AnyObject,
String(kSecAttrAccessible): kSecAttrAccessibleAfterFirstUnlock,
]
let parameters : [String: AnyObject] = [
String(kSecAttrKeyType): algorithm.secKeyAttrType,
String(kSecAttrKeySizeInBits): keySize as AnyObject,
String(kSecReturnRef): kCFBooleanTrue,
kSecPublicKeyAttrs as String: publicKeyParameters as AnyObject,
kSecPrivateKeyAttrs as String: privateKeyParameters as AnyObject,
]
var error: Unmanaged<CFError>?
let privateKey = SecKeyCreateRandomKey(parameters as CFDictionary, &error)
if privateKey == nil {
print("Error creating keys occured: \(error!.takeRetainedValue() as Error), keys were not created")
//return(nil,nil)
}
}
在 Main 中,我使用以下代码片段调用它们
var handler = Handler()
let tagPrivate = "com.csr.private.rsa2048sha256"
let tagPublic = "com.csr.public.rsa2048sha256"
let keyAlgorithm = KeyAlgorithm.rsa(signatureType: .sha256)
let sizeOfKey = keyAlgorithm.availableKeySizes[2]
handler.generateKeyPair(keyAlgorithm, keySize: sizeOfKey, tagPrivate: tagPrivate, tagPublic: tagPublic)
handler.retrievePrivateKey(keyAlgorithm, keySize:sizeOfKey, tagPrivate:tagPrivate)