从钥匙串中检索SecKey [英] Retrieve SecKey from Keychain
问题描述
我正尝试将我从此答案生成的代码升级为生成CSR,从Swift 2升级到Swift 3
I am trying to upgrade the code that I got from this answer for generating CSR, from Swift 2 to Swift 3.
我已经升级了大多数代码,但是原始答案的Utility块中的以下代码失败,并显示以下错误:
I have most of the code upgraded, but the following code in the Utility block of the original answer failed with the error:
'init'不可用:使用'withMemoryRebound(to:capacity:_)'临时将内存视为另一种与布局兼容的类型.
'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.
该错误发生在以下行:
let status: OSStatus = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as NSDictionary, UnsafeMutablePointer($0)) }
func loadKeySecKeyFromKeyChain(key: String) -> SecKey{
let query: Dictionary<String, AnyObject> = [
String(kSecAttrKeyType): kSecAttrKeyTypeRSA,
String(kSecAttrKeySizeInBits): KEY_SIZE as AnyObject,
String(kSecClass): kSecClassKey,
String(kSecAttrApplicationTag): key as AnyObject,
kSecReturnRef as String : kCFBooleanTrue ]
var dataTypeRef: Unmanaged<AnyObject>? = nil
var resultData: SecKey? = nil
let status: OSStatus = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as NSDictionary, UnsafeMutablePointer($0)) }
NSLog("SecItemCopyMatching: " + status.description)
if status == errSecSuccess {
NSLog("private or public debug description is: " + dataTypeRef.debugDescription)
resultData = (dataTypeRef!.takeRetainedValue() as! SecKey)
NSLog("SecItemCopyMatching returns SecKey: " + resultData.debugDescription)
return resultData!
} else {
return resultData!
}
}
我已经坚持了整整一天,对于如何解决此错误有什么建议吗?
I have been stuck on this for a whole day, is there any suggestions for how to resolve this error?
推荐答案
只需使用SecItemCopyMatching
.我能够将其转换为Swift 3并成功生成CSR.
Just use SecItemCopyMatching
. I was able to convert it to Swift 3 and successfully generate CSR.
// Finds the SecKeyRef corresponding to the parameter key and returns it
func loadKeySecKeyFromKeyChain(key: String) -> SecKey {
let query: Dictionary<String, AnyObject> = [
String(kSecAttrKeyType): kSecAttrKeyTypeRSA,
String(kSecAttrKeySizeInBits): KEY_SIZE as AnyObject,
String(kSecClass): kSecClassKey,
String(kSecAttrApplicationTag): key as AnyObject,
kSecReturnRef as String : kCFBooleanTrue ]
var dataTypeRef: Unmanaged<AnyObject>? = nil
var resultData: SecKey? = nil
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
if status == errSecSuccess {
resultData = result as! SecKey
return resultData!
} else {
return resultData!
}
}
这篇关于从钥匙串中检索SecKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!