Arthur Sahakyan
Arthur Sahakyan

Reputation: 41

How can I use a PKCS8 RSA DER Private Key in Swift or Objective C

I found something like this question but that didn't work for me

How can I use a PKCS8 RSA DER Private Key in iOS?

Upvotes: 0

Views: 3870

Answers (2)

Alex Skalozub
Alex Skalozub

Reputation: 2576

Have a look at this GitHub repo. It demonstrates the usage of SecItemImport to load keys for signing and verification.

You should also carefully look at SecExternalFormat enum which has (among others) kSecFormatWrappedPKCS8. This is probably what you're looking for.

Upvotes: 0

Carl Lindberg
Carl Lindberg

Reputation: 2947

Not easily. Apple would prefer that you use a cert (public key) or identity (.p12 file, public/private key pair), and makes storing raw keys difficult. That especially goes for private keys -- you generally would rather not have unencrypted private keys in your memory space if you can avoid it. On OSX, SecItemImport() works, but not on iOS, though I haven't checked for a couple of OS versions now.

You can force it if you really want, but it needs to be PKCS#1 DER data -- so you have to extract the PKCS#1 key from the PKCS#8 data, which means you have to parse DER by hand.

This is an older example for public key PKCS#8 data:

http://blog.flirble.org/2011/01/05/rsa-public-key-openssl-ios/

Using that code, you can get a SecKeyRef for a public key; private keys are a little different DER structure but similar idea.

The best bet though is to get a .p12 file and use SecPKCS12Import(). That will get you a SecIdentityRef, and from there you can use SecIdentityCopyPrivateKey() to get the private key SecKeyRef.

Upvotes: 2

Related Questions