title: Convert a .PEM certificate to .PFX programmatically using OpenSSL
body: <p>I've got a <a href="http://en.wikipedia.org/wiki/X.509#Certificate_filename_extensions" rel="nofollow noreferrer">.PEM file</a> that I want to convert to a PKCS12 file (PFX), and I know I can easily accomplish this using the following <code>openssl</code> command:</p>
  
  <blockquote>
  <pre><code>Create a PKCS#12 file:
  
   openssl pkcs12 -export -in file.pem -out file.p12 -name "My Certificate"
  </code></pre>
  </blockquote>
  
  <p>Which is great, but I'd like to do this programmatically using <a href="http://en.wikipedia.org/wiki/OpenSSL" rel="nofollow noreferrer">OpenSSL</a> calls. Unfortunately, documentation for OpenSSL is less than ideal.</p>
  
  <p>I've looked into doing this using other libraries:</p>
  
  <p>Using .NET: I can create a X509Certificate2 object from a PEM file, but this only grabs the first certificate and ignores any intermediate CA's in the PEM file.</p>
  
  <p>Using <a href="http://mentalis.org" rel="nofollow noreferrer">Mentalis.org</a> Security Library: I can create a Certificate object from a PEM file, but I see the following in the documentation:</p>
  
  <blockquote>
    <p>Remarks 
    This implementation only reads
    certificates from PEM files. It does
    not read the private key from the
    certificate file, if one is present.</p>
  </blockquote>
  
  <p>So, that doesn't help me. I need that private key too.</p>
  
  <p>I basically need to recreate the OpenSSL command line tool operation for going PEM>PFX, but in code.</p>
  
  <p>Is there an easier way to do this?</p>