RSA Key Generating use Security, SecKeyCreateRandomKey

i want make RSA pair key to 512bit

i find SecKeyCreateRandomKey, CrytoKit, another open lib.. I decided to use Security

I have to give the server developer the string value of the rsa file I created I sent you an rsa string but server developer answered that the format was wrong I wonder what is wrong with my code. Or I want to be helped to generate an rsa key and chage type into a string

this is my code

first - make private key using SecKeyCreateRandomKey

func createPrivateKey()-> SecKey?{
     
    let privateKeyParams: [String: Any] = [
      kSecAttrIsPermanent as String: true,
      kSecAttrApplicationTag as String: tagName
    ]
     
    let parameters: [String: Any] = [
      kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
      kSecAttrKeySizeInBits as String: 512,
      kSecPrivateKeyAttrs as String: privateKeyParams
    ]
     
    var error: Unmanaged<CFError>?
     
    guard let privateKey = SecKeyCreateRandomKey(parameters as CFDictionary, &error) else
    {
      NSLog("\tError generating keypair. %@", "\(error!.takeRetainedValue().localizedDescription)")
      return nil
    }
    return privateKey
  }

second - get public key using private key of Seckey

func getPublicKey(key: SecKey) -> SecKey?{
    return SecKeyCopyPublicKey(key)
  }

third - get public key Data using public key seckey

func getPublicData(key: SecKey) -> CFData?{
    return SecKeyCopyExternalRepresentation(key, nil)
  }

fouth - string of public key using public key of Data

  public func exportPublicKey(_ rawPublicKeyBytes: Data, base64EncodingOptions: Data.Base64EncodingOptions = []) -> String?
  {
   Log.debug("exportPublicKey", rawPublicKeyBytes.base64EncodedString(options: base64EncodingOptions))
    return rawPublicKeyBytes.base64EncodedString(options: base64EncodingOptions)
  }

last i send result of exportPublicKey() rsa string like this

MEgCQQDCmgOuSGbG/Mtq2NnHlBQU5rsGnNf17h4NZy+2lyrjKGgaVpD66QHmx2Na+/QQaamEhUgkFAkj0UlkMTRWGKO5AgMBBBE=

or

-----BEGIN PUBLIC KEY-----
MEgCQQDCmgOuSGbG/Mtq2NnHlBQU5rsGnNf17h4NZy+2lyrjKGgaVpD66QHmx2Na+/QQaamEhUgkFAkj0UlkMTRWGKO5AgMBBBE=
-----END PUBLIC KEY-----

Replies

I put up the question and found a problem. After converting to string, the length of the string must be 128 But my code has a length of 101 How do I extract the length of 128?

I think the missing piece here is the PEM representation of the public key. When SecKeyCopyExternalRepresentation is used the public key is exported to Data that is DER encoded. It is not wrapped in a PEM. For the entire story here, take a look at Quinn's post here that explains this in detail. If you get stuck, open a TSI and either Quinn or myself can help out.

Matt Eaton
DTS Engineering, CoreOS
meaton3@apple.com