title: iOS: How to create PKCS12 (P12) keystore from private key and x509certificate in application programmatically?
body: <p>This question was apparently similar but had no answers of any kind: <a href="https://stackoverflow.com/questions/24683786/programmatically-create-a-x509-certificate-for-iphone-without-using-openssl">Programmatically create a x509 certificate for iPhone without using OpenSSL</a></p>
  
  <p>In our application (server, client), we are implementing client authentication (SSL based on X509Certificate). We already have a way to generate a <code>keypair</code>, create a <code>PKCS10 Certificate Signing Request</code>, have this signed by the <code>self-signed CA</code> and create a <code>X509Certificate</code>, send this back. However, to use this certificate in SSL requests, the <code>private key</code> and the <code>X509Certificate</code> have to be exported to a <code>PKCS12</code> (P12) <code>keystore</code>.</p>
  
  <p>Does anyone know anything about how to do this, or even if it's possible? The client <strong>has</strong> to generate the P12 file (we don't want to give out the private key), and the client is running iOS, and is a mobile device. The solution worked for Android using BouncyCastle (SpongyCastle), but we found nothing for iOS.</p>
  
  <p>EDIT: In Java, this export is done by the following:</p>
  
  <pre><code>    ByteArrayOutputStream bos = new ByteArrayOutputStream();
      KeyStore ks = KeyStore.getInstance("PKCS12", BouncyCastleProvider.PROVIDER_NAME);
      ks.load(null);
      ks.setKeyEntry("key-alias", (Key) key, password.toCharArray(),
              new java.security.cert.Certificate[] { x509Certificate });
      ks.store(bos, password.toCharArray());
      bos.close();
      return bos.toByteArray();
  </code></pre>