Retrieve SecKey from Keychain

∥☆過路亽.° 提交于 2019-12-11 00:06:06

问题


I am trying to upgrade the code that I got from this answer for generating CSR, from Swift 2 to Swift 3.

I have most of the code upgraded, but the following code in the Utility block of the original answer failed with the error:

'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.

The error occurs at the line:

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?


回答1:


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!
    }
}


来源:https://stackoverflow.com/questions/41733166/retrieve-seckey-from-keychain

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!