Whats the best way to generate a RSA key pair in iOS and get them as String. I have seen couple of libs which can generate but i can't get the Private Key as String. Does anyone know a lib or way to get the Private key in String?
Currently i generate the Key pair this way
var statusCode: OSStatus
var publicKey: SecKey?
var privateKey: SecKey?
let publicKeyAttr: [NSObject: NSObject] = [kSecAttrIsPermanent:true as NSObject, kSecAttrApplicationTag:"publicTag" as NSObject]
let privateKeyAttr: [NSObject: NSObject] = [kSecAttrIsPermanent:true as NSObject, kSecAttrApplicationTag:"privateTag" as NSObject]
var keyPairAttr = [NSObject: NSObject]()
keyPairAttr[kSecAttrKeyType] = kSecAttrKeyTypeRSA
keyPairAttr[kSecAttrKeySizeInBits] = 2048 as NSObject?
keyPairAttr[kSecPublicKeyAttrs] = publicKeyAttr as NSObject?
keyPairAttr[kSecPrivateKeyAttrs] = privateKeyAttr as NSObject?
statusCode = SecKeyGeneratePair(keyPairAttr as CFDictionary, &publicKey, &privateKey)
if statusCode == noErr && publicKey != nil && privateKey != nil {
print(publicKey!)
print(privateKey!)
} else {
print("Error generating key pair: \(statusCode)")
}
Its in SecKey. How to convert them to String? or is there another way to do it ?
Here's the code using
SecItemCopyMatching:privateKeyDataseems to contain ASN.1 encoded information. The final result is Base64 encoded.