5

Currently I am generating a RSAKeyPair with the iOS security framework

statusCode = SecKeyGeneratePair(keyPairAttributes as CFDictionary, &newPublicKey, &newPrivateKey)

I then want to export these keys to a PEM format with PKCS8. The standard method apple provides to export keys is this:

let cfData = SecKeyCopyExternalRepresentation(self, &error)

but this data gives me the key in the PKCS1 format. Is there a way to convert the PKCS1 format to PKCS8?

So far all my research left me clueless on what to actually do to convert these formats.

  • I can say that 1. PKCS#8 *contains* the PKCS#1 key and 2. that there seem to be ASN.1 encoding utilities that could be used to wrap the PKCS#1 key with the relevant structures. However, with the current Apple documentation (which is getting worse, CCCrypt was a disgrace but this is *way* worse) I cannot see any example of creating any ASN.1 structure. – Maarten Bodewes Mar 25 '18 at 15:00
  • Do you find any way to convert to pkcs8? – Mahdi Moqadasi Jan 16 '22 at 10:30

1 Answers1

0

I can't translate into Swift, but here's the nearly-Objective-C:

SecItemImportExportKeyParameters keyParams = {};
keyParams.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
keyParams.passphrase = you_need_a_cfstringref_here;

SecExternalFormat dataFormat = kSecFormatWrappedPKCS8;
OSStatus status = SecItemExport(privateKey, dataFormat, 0, &keyParams, &cfData);
bartonjs
  • 30,352
  • 2
  • 71
  • 111