Search code examples
iosswiftxcodesecurityseckeyref

Generate a P12 file Xcode?


I know there is a function called SecPKCS12Import that allows you to import data from a p12 file. However, I want to go the reverse route. I have a SecCertificateRef and a public/private SecKeyRef, which I want to use to create a P12 file. Does anyone know how to do this on iPhone?

Thanks


Solution

  • Unfortunately, there CommonCrypto does not provide any means to export PKCS12 containers let alone any other export functionality (even though its OSX counterpart can do that). There are ways to extract the SecKeyRef raw data from the key chain but then you still need to write all the PKCS12 wrapping yourself.

    We were facing a similar issue and went with OpenSSL.

    Compiling OpenSSL for iOS

    Integrating OpenSSL requires a bit of work as you need to compile and link the OpenSSL sources yourself. Fortunately, there are some build scripts available so you do not have to do that yourself, e.g, https://github.com/x2on/OpenSSL-for-iPhone . I suggest you use them as you need to patch some of the Makefiles which is a bit of a hazel. Those build scripts generate static linked libraries for both iOS and tvOS. You just need to link them against your project and set the Header and Library Search Path accordingly.

    CocoaPods

    You can also use the official OpenSSL CocoaPod . That saves you the trouble of configuring your project.

    Exporting PKCS12

    As you might know, OpenSSL is a C library. That means you might want to encapsulate all the C functions into a Objective-C or Swift wrapper. There are some open source wrappers that support im- and exporting PKCS12 containers but I have not found a single one with good documentation. You should be able to derive the relevant snippets from some of the sources though.

    https://github.com/microsec/MscX509Common/blob/master/src/MscPKCS12.m

    You can have a look at this example as well http://fm4dd.com/openssl/pkcs12test.htm .

    Hope that helps!