title: Converting between Windows CryptoAPI and OpenSSL x509 formats
body: <p>I have a <a href="http://msdn.microsoft.com/en-us/library/aa377189%28VS.85%29.aspx" rel="nofollow">CERT_CONTEXT</a> structure which I've extracted from a smart card on Windows via the CryptoAPI. I need to convert this structure into a DER encoded byte array which is consistent with OpenSSL. The closest match I've got so far is via <a href="http://msdn.microsoft.com/en-us/library/aa379921%28v=vs.85%29.aspx" rel="nofollow">CryptEncodeObject</a> using X509_ASN_ENCODING and the X509_CERT_TO_BE_SIGNED modifier which takes the <a href="http://msdn.microsoft.com/en-us/library/aa377200%28v=vs.85%29.aspx" rel="nofollow">CERT_INFO</a> structure as input.</p>
  
  <p>The problem is that it doesn't match with the output produced by the OpenSSL <a href="http://www.openssl.org/docs/crypto/d2i_X509.html" rel="nofollow">i2d_X509</a> function. Using a 2048 bit x509 certificate as input, OpenSSL produces 1789 bytes of encoded output whilst the Windows CryptoAPI produces 1638 bytes of encoded output.</p>
  
  <p>The only option left that I can see is to create an X509 cert on the fly using the values from the <a href="http://msdn.microsoft.com/en-us/library/aa377189%28VS.85%29.aspx" rel="nofollow">CERT_CONTEXT</a> structure and the encode the resulting object directly with the <a href="http://www.openssl.org/docs/crypto/d2i_X509.html" rel="nofollow">i2d_X509</a> function. The only problem with this is that I can't extract the private key from the smart card, so this may cause problems with the x509 cert creation routines. </p>
  
  <p>If anyone can provide any insight/advice/tips into these matters, I'd be much obliged.</p>