Captain Rib
Captain Rib

Reputation: 295

Retrieve SecKey from Keychain

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?

Upvotes: 2

Views: 2845

Answers (1)

Mike Mikina
Mike Mikina

Reputation: 496

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

Upvotes: 2

Related Questions