0

I'm trying to generate and get keypair information for a Swift iOS app and am having issues setting the UnsafeMutablePointer with the following error:

Cannot convert value of type 'UnsafeMutablePointer<_>' to expected argument type 'UnsafeMutablePointer<CFTypeRef?>?' (aka 'Optional<UnsafeMutablePointer<Optional<AnyObject>>>')

I'm attempting to utilize the following StackOverflow discussion to get this working: Generate a CSR in iOS Library?

My question is how do I explicitly set the value to correct this error?

Below is the following code I'm attempting to use:

//Locates the SecKeyRef to the key passed in and returns secKeyRef

func readSecKeyRefFromKeychain(searchKey: String) -> SecKey
{
    let keyQuery: Dictionary<String, AnyObject> = [
        String(kSecAttrKeyType):kSecAttrKeyTypeRSA,
        String(kSecAttrKeySizeInBits):KEY_SIZE as AnyObject,
        String(kSecClass):kSecClassKey,
        String(kSecAttrApplicationTag):searchKey as AnyObject,
        kSecReturnRef as String : kCFBooleanTrue
    ]

    var dataTypeReference: Unmanaged<AnyObject>? = nil
    var dataResult: SecKey? = nil

    let status: OSStatus = withUnsafeMutablePointer(to:&dataTypeReference)
    {
        SecItemCopyMatching(keyQuery as NSDictionary, UnsafeMutablePointer($0))
    }
    NSLog("readSecKeyRefFromKeychain: SecItemCopyMatching: " + status.description)

    if status == errSecSuccess{
        NSLog("key debug description is: " + dataTypeReference.debugDescription)
        dataResult = (dataTypeReference!.takeRetainedValue() as! SecKey)
        NSLog("public or private secKeyRef is: " + dataResult.debugDescription)
        return dataResult!
    }else{
        return dataResult!
    }
}
TylerP
  • 9,600
  • 4
  • 39
  • 43

1 Answers1

0

This?

//Locates the SecKeyRef to the key passed in and returns secKeyRef

func readSecKeyRefFromKeychain(searchKey: String) -> SecKey {
    let keyQuery: Dictionary<String, AnyObject> = [
        String(kSecAttrKeyType):kSecAttrKeyTypeRSA,
        String(kSecAttrKeySizeInBits):KEY_SIZE as AnyObject,
        String(kSecClass):kSecClassKey,
        String(kSecAttrApplicationTag):searchKey as AnyObject,
        kSecReturnRef as String : kCFBooleanTrue
    ]

    var dataTypeReference: Unmanaged<AnyObject>? = nil
    var dataResult: SecKey? = nil

    let status: OSStatus = withUnsafeMutablePointer(to:&dataTypeReference) {
        SecItemCopyMatching(query as NSDictionary, ($0 as CFTypeRef) as? UnsafeMutablePointer<CFTypeRef?>)
    }

    NSLog("readSecKeyRefFromKeychain: SecItemCopyMatching: " + status.description)

    if status == errSecSuccess {
        NSLog("key debug description is: " + dataTypeReference.debugDescription)
        dataResult = (dataTypeReference!.takeRetainedValue() as! SecKey)
        NSLog("public or private secKeyRef is: " + dataResult.debugDescription)
        return dataResult!
    } else {
        return dataResult!
    }
}