3
votes

I am working on an application where I will retrieve a public key for a user from our server. Once I have it, I need to do a RSA encryption using the public key. The public key obtained from the server is Base64 encoded.

How do I load the public key into the iOS KeyChain so that I can perform RSA cryptographic functions with it? Certificate loading seems to be trivial, but raw public keys don't.

3

3 Answers

4
votes

This is not supported because it is the "wrong" way.

The "right" way is to use a certificate.

To quote "Quinn The Eskimo!".

This is surprisingly easy. You don't need to add the certificate to the keychain to handle this case. Rather, just load the certificate data (that is, the contents of a .cer file) in your application (you can either get this from your bundle or off the network) and then create a certificate ref using SecCertificateCreateWithData. From there you can extract a public key ref using a SecTrust object (SecTrustCreateWithCertificates, SecTrustEvaluate -- you can choose to ignore the resulting SecTrustResultType -- and SecTrustCopyPublicKey). And from there you can encrypt and verify using the SecKey APIs (SecKeyEncrypt, SecKeyRawVerify).

A tutorial on how to create a self-signed certificate is here.

The basic steps are:

#Make the -----RSA PRIVATE KEY----- file in PEM format
openssl genrsa -out privKey.pem 2048

#Make the -----CERTIFICATE REQUEST-----
openssl req -new -key privKey.pem -out certReq.pem

#Make the actual -----CERTIFICATE-----
openssl x509 -req -days 30 -in certReq.pem -signkey privKey.pem -out certificate.pem

#Make the DER certificate.crt file from the certificate.pem
openssl x509 -outform der -in certificate.pem -out certificate.cer

If you double click that .cer on a Mac machine, it will offer to import it into keychain.

Resources:

1
votes

The usual way of transporting a public key -is- inside a certificate, signed by some CA to prove that it is authentic.

Or maybe you are talking about a ssh public key? in that case you would need a special ssh capable app to use it, these keys are usually not stored in the iOS keychain.

0
votes

I found the necessary code on the Apple Site describing how to strip the ASN.1 header from the Public Key and load it into the KeyChain.