How to generate RSA public and private keys using Swift 3?

You need to convert public/private key pair for external representation using SecKeyCopyExternalRepresentation method and then convert your Data into base64 encoded string which is just PEM format, using base64EncodedString(options: ) method. Refer the code here


Please try this :

let publicKeyAttr: [NSObject: NSObject] = [
            kSecAttrIsPermanent:true as NSObject,
            kSecAttrApplicationTag:"com.xeoscript.app.RsaFromScrach.public".data(using: String.Encoding.utf8)! as NSObject,
            kSecClass: kSecClassKey, // added this value
            kSecReturnData: kCFBooleanTrue] // added this value
let privateKeyAttr: [NSObject: NSObject] = [
            kSecAttrIsPermanent:true as NSObject,
            kSecAttrApplicationTag:"com.xeoscript.app.RsaFromScrach.private".data(using: String.Encoding.utf8)! as NSObject,
            kSecClass: kSecClassKey, // added this value
            kSecReturnData: kCFBooleanTrue] // added this value

var keyPairAttr = [NSObject: NSObject]()
keyPairAttr[kSecAttrKeyType] = kSecAttrKeyTypeRSA
keyPairAttr[kSecAttrKeySizeInBits] = 2048 as NSObject
keyPairAttr[kSecPublicKeyAttrs] = publicKeyAttr as NSObject
keyPairAttr[kSecPrivateKeyAttrs] = privateKeyAttr as NSObject

var publicKey : SecKey?
var privateKey : SecKey?;

let statusCode = SecKeyGeneratePair(keyPairAttr as CFDictionary, &publicKey, &privateKey)

if statusCode == noErr && publicKey != nil && privateKey != nil {
    print("Key pair generated OK")
    var resultPublicKey: AnyObject?
    var resultPrivateKey: AnyObject?
    let statusPublicKey = SecItemCopyMatching(publicKeyAttr as CFDictionary, &resultPublicKey)
    let statusPrivateKey = SecItemCopyMatching(privateKeyAttr as CFDictionary, &resultPrivateKey)

    if statusPublicKey == noErr {
        if let publicKey = resultPublicKey as? Data {
            print("Public Key: \((publicKey.base64EncodedString()))")
        }
    }

    if statusPrivateKey == noErr {
        if let privateKey = resultPrivateKey as? Data {
            print("Private Key: \((privateKey.base64EncodedString()))")
        }
    }
} else {
    print("Error generating key pair: \(String(describing: statusCode))")
}