Search code examples
objective-cmacoscocoakeychainx509

SecCertificateAddToKeychain - Unknown format in import


The funcion SecCertificateAddToKeychain() gives me an error with the certificate I created for testing.

The certificate - TestCert.p12:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365
openssl pkcs12 -export -inkey key.pem -in cert.pem -out TestCert.p12

The code:

NSData  *certData = [NSData dataWithContentsOfFile:path];
if (certData)  {
   SecCertificateRef  newCert = SecCertificateCreateWithData (NULL, (CFDataRef)certData);
   if (newCert)  {
      OSStatus  addResult = SecCertificateAddToKeychain (newCert, NULL);
      if (addResult)  {
         NSString  *errStr = SecCopyErrorMessageString (addResult, NULL);
         NSLog (@"Cannot add certificate to keychain: %@", errStr);
      }
   }
}

Output: Cannot add certificate to keychain: Unknown format in import. Any idea?


Solution

  • SecCertificateCreateWithData is only described for X.509 format, not PKCS#12.

    For P12 you want SecPkcs12Import (which will import to the default keychain by default) or SecItemImport (which will not import private keys unless you explicitly give it the keychain into which to import them -- e.g. SecKeychainCopyDefault).