Reputation: 2642
I am working in a project in swift, involving RSA Encryption, and I am stuck with a pointer problem as follows:
I have a global var publicKey: SecKey?
optional value, and I need to get the UnsafeMutablePointer<Unmanaged<SecKey>?>
pointer to it, that is the data type required in the SecKeyGeneratePair
function.
I am trying to define the pointer as:
var keyPointer = UnsafeMutablePointer<Unmanaged<SecKey>?>(publicKey!)
But the compiler complains with a Cannot invoke 'init' with an argument of type @lvalue SecKey error
According to the Using Swift with Cocoa and Objective-C book, In the Core Foundation and Unmanaged Objects section, it states that the Unmanaged<T>
structure provides 2 methods takeUnretainedValue()
and takeRetainedValue()
. but trying to implement them, gives the following error
var keyPointer = UnsafeMutablePointer<Unmanaged<SecKey>?>(publicKey!.takeRetainedValue())
'SecKey' does not have a member named 'takeRetainedValue'
Any help to work this out will be appreciated
Upvotes: 1
Views: 1573
Reputation: 11
for Swift 2.1 it isn't working with Unmanaged, the right version is:
var publicKey: SecKey?
var privateKey: SecKey?
let dic:[String:String] = [kSecAttrKeyType:kSecAttrKeyTypeRSA, kSecAttrKeySizeInBits:"2048"]
SecKeyGeneratePair(dic, &publicKey, &privateKey)
Upvotes: 1
Reputation: 51911
Try this:
var publicKey: SecKey?
var privateKey: SecKey?
var publicKeyUnManaged:Unmanaged<SecKey>?
var privateKeyUnManaged:Unmanaged<SecKey>?
let dic:[String:String] = [kSecAttrKeyType:kSecAttrKeyTypeRSA, kSecAttrKeySizeInBits:"2048"]
SecKeyGeneratePair(dic, &publicKeyUnManaged, &privateKeyUnManaged)
publicKey = publicKeyUnManaged?.takeRetainedValue()
privateKey = privateKeyUnManaged?.takeRetainedValue()
You don't have to create UnsafeMutablePointer<Unmanaged<SecKey>?>
manually. As mentioned in this document,
When a function is declared as taking an UnsafeMutablePointer argument, it can accept any of the following:
- nil, which is passed as a null pointer
- An UnsafeMutablePointer value
- An in-out expression whose operand is a stored lvalue of type Type, which is passed as the address of the lvalue
- An in-out [Type] value, which is passed as a pointer to the start of the array, and lifetime-extended for the duration of the call
In this case, we can use 3rd "in-out" expression.
Upvotes: 5