Create RSA public key in iOS and send to a Java backend.

Hi, I want to create a RSA public key and send to Java backend for encryption. However, Java returns error invalid key.

I have created keys using SecKeyCreateRandomKey and convert publicKey into string using base64encoding.

I have had some research : Using third party : https://stackoverflow.com/questions/53906275/rsa-public-key-created-in-ios-swift-and-exported-as-base64-not-recognized-in-jav .

Another deep analyze : https://stackoverflow.com/questions/74574369/ios-creating-publickey-in-pkcs-format-instead-of-asn-1-format

However, are any more "native way" (which means using only Apple API) supporting this ?

Did you debug the Java side to see the details of the error?

It kinda depends on what your Java back end is expecting. I suspect that you’re dealing with the difference between the RSAPublicKey structure, which is what Security framework generates, and the SubjectPublicKeyInfo structure, which is what a lot of third-party security toolkits expect. See On Cryptographic Key Formats for the details.

The easiest way to resolve this is on the back end, where you have access to a full-featured crypto toolkit. I can’t help you with the details though.

If you can’t change the server then you can do this an iOS but it’s a bit of a pain. There are two basic strategies:

  • Add a hard-code prefix that represents the SubjectPublicKeyInfo wrapper (A)

  • Do the right thing with a ASN.1 encoder (B)

The main drawback with A is that it only works for a specific key type and size. If you can live with that, it’s an easy option.

The problem with B, at least historically, is that iOS has no generic ASN.1 APIs and all the third-party ASN.1 coders out there are super complex. These days we have SwiftASN1, and that’s what I’d use if I decided to pursue B.


Finally, this problem goes away if you switch to EC because CryptoKit has great support for exporting EC public keys. And there are good reasons to switch to EC anyway. If you control the server, just change it to support EC. If not, discuss this with the folks who do control it, because RSA is long past its prime.

Share and Enjoy

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

Create RSA public key in iOS and send to a Java backend.
 
 
Q