RSA public/private key generates with swift5 does not work on Java platforms

Hello. Here is my Swift code to generate RSA public / private key

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

static func printRSAPublicKey(_ publicKey: SecKey) {
    guard let publicKeyData = SecKeyCopyExternalRepresentation(publicKey, nil) as Data? else {
        print("Failed to get public key data.")
        return
    }
    
    print("RSA Public Key:")
    print(publicKeyData.base64EncodedString())
}

I got public key but it does not work I got stuck there.

but it does not work

That’s not a lot to go on. What exactly doesn’t work? The code you posted? If so, what error does it yield? Or are you saying that the key doesn’t work with your third-party tooling?

My experience is that most folks who run into problems like this are confused about key formats:

  • SecKeyCopyExternalRepresentation returns a ‘raw’ key, that is, a DER-encoded RSAPublicKey structure.

  • Most third-party tooling expects this to be wrapped in a SubjectPublicKeyInfo structure.

See On Cryptographic Key Formats for all the gory details.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

RSA public/private key generates with swift5 does not work on Java platforms
 
 
Q