title: How can I convert a .p12 to a .pem containing an unencrypted PKCS#1 private key block?
body: <p>I have a <code>Certificates.p12</code> file that I wish to convert to a <code>certificates.pem</code> containing an unencrypted private key in PKCS#1 format. I have previously been able to do this by running:</p>
  <pre><code>openssl pkcs12 -in Certificates.p12 -out certificates.pem -nodes -clcerts
  </code></pre>
  <p>The resulting <code>certificates.pem</code> file has a <code>PRIVATE KEY</code> PEM block, as expected. However, <a href="https://github.com/sideshow/apns2/blob/master/certificate/certificate.go#L80" rel="nofollow noreferrer">the library I'm using</a> does not understand this PEM block, because it expects it to be a PKCS#1 private key. The ASN.1 structure of a PKCS#1 private key is defined by <a href="https://www.rfc-editor.org/rfc/rfc3447#appendix-A.1.2" rel="nofollow noreferrer">RFC 3447</a> as:</p>
  <pre><code>RSAPrivateKey ::= SEQUENCE {
      version           Version,
      modulus           INTEGER,  -- n
      publicExponent    INTEGER,  -- e
      privateExponent   INTEGER,  -- d
      prime1            INTEGER,  -- p
      prime2            INTEGER,  -- q
      exponent1         INTEGER,  -- d mod (p-1)
      exponent2         INTEGER,  -- d mod (q-1)
      coefficient       INTEGER,  -- (inverse of q) mod p
      otherPrimeInfos   OtherPrimeInfos OPTIONAL
  }
  </code></pre>
  <p>The bad private key block in my <code>certificates.pem</code> does not have this PKCS#1 structure! Instead, its ASN.1 structure looks like this:</p>
  <pre><code>$ openssl asn1parse -i -in badprivatekey.pem
      0:d=0  hl=4 l=1212 cons: SEQUENCE
      4:d=1  hl=2 l=   1 prim:  INTEGER           :00
      7:d=1  hl=2 l=  13 cons:  SEQUENCE
      9:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
     20:d=2  hl=2 l=   0 prim:   NULL
     22:d=1  hl=4 l=1190 prim:  OCTET STRING      [HEX DUMP]:308204A...very long hex...
  </code></pre>
  <p>What is the above format? <a href="https://wiki.openssl.org/index.php/Manual:Pkcs12(1)" rel="nofollow noreferrer">The documentation for <code>openssl pkcs12</code></a> only vaguely says that its output is &quot;written in PEM format.&quot; I need a stronger guarantee that the private key PEM block is in PKCS#1 format.</p>
  <p>The strange thing is that <code>openssl rsa</code> understands the strange format of the &quot;bad&quot; private key, and can convert it to the right PKCS#1 structure with:</p>
  <pre><code>openssl rsa -in badprivatekey.pem -out goodprivatekey.pem
  </code></pre>
  <p>Although <code>openssl rsa</code> understands the input file, the tool seems unable to tell me <em>why</em>, i.e. what the format of the input file is.</p>
  <p>What is the output format of <code>openssl pkcs12</code>? Specifically what is the format of its private key block? How do I make <code>openssl pkcs12</code> output a correct PKCS#1 private key?</p>