Can't Generate Valid SecKey RSA Keys

Hey all! I'm hoping to get some help with an issue I'm having when trying to generate RSA keys using the Security framework on iOS.

I'm using the following code to generate my keys:

let attributes: [String: Any] = [
       kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
       kSecAttrKeySizeInBits as String: 4096,
]

let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, nil)!
let publicKey = SecKeyCopyPublicKey(self)!

From there, I create a data representation of my public key, and convert it into a string. My use case requires the OpenSSH format, so I insert "ssh-rsa" to the beginning of the string.

let publicKeyData = SecKeyCopyExternalRepresentation(self, nil)! as Data
let keyString = "ssh-rsa \(publicKeyData.base64Encoded)"

When I attempt to use this though, I get an error message from my SSH client. I'm using the NMSSH package, but I'm very confident my issue is with SecKey, not the package, for two reasons.

  1. Creating a textile with my generated key using ssh-keygen -l -f results in a "Not a public key file message"
  2. When I use a public key string generated from my Mac in my code, it works.

So, unless I'm missing something, my issue is related to the SecKey generation code, not the formatting or NMSSH package. I've looked at the Apple docs as well as dozens of other posts here, but can't seem to figure out what I'm doing wrong. Thank you for any help!

Can't Generate Valid SecKey RSA Keys
 
 
Q