title: How can I add a private key to a certificate in the windows trust store in c++?
body: <p>I have a file with a certificate in it, and I have a file with a private key file in it.</p>
  
  <p>if I run this command</p>
  
  <p>certutil –MergePFX certfile.cer certfile.pfx</p>
  
  <p>I get a pfx file that if I run with explorer, it runs the windows certificate import wizard. If I run through the wizard, I end up with the cert with the key in the windows trust store. Exactly what I need.</p>
  
  <p>I'm trying to do this programatically.</p>
  
  <p>The problem seems to be in the CertAddCertificateContextToStore function.
  In the remarks it says: </p>
  
  <blockquote>
    <p>The certificate context is not duplicated using CertDuplicateCertificateContext. Instead, the function creates a new copy of the context and adds it to the store. In addition to the encoded certificate, CertDuplicateCertificateContext also copies the context's properties, with the exception of the CERT_KEY_PROV_HANDLE_PROP_ID and CERT_KEY_CONTEXT_PROP_ID properties.</p>
  </blockquote>
  
  <p>So certduplicatecertificatecontext very specifically will not copy the private key, and it seems that CertAddCertificateContextToStore doesn't either.</p>
  
  <p>I have a HCRYPTPROV struct with my private key and I use CERT_KEY_CONTEXT_PROP_ID and CERT_KEY_PROV_HANDLE_PROP_ID (I tried them both) to CertSetCertificateContextProperty my certificate context, and then I store it in the windows trust store with CertAddCertificateContextToStore. And no matter what I try, the certificate goes in without the private key.</p>
  
  <p>I'm verifying this with the certmgr tool that shows if a private key is attached, and I can also see it not work when I use that client certificate in a curl request I'm making.</p>
  
  <p>Another thing I tried was this:</p>
  
  <p>The last parameter to CertAddCertificateContextToStore is the handle to the copy of the context that is made. I figure the original context is the one I created where I read the certificate in from disk. This new certificate is the one tied to the actual on-disk store that certmgr reads.</p>
  
  <p>So after I call CertAddCertificateContextToStore, I take the new cert and I add the private key, again via CertSetCertificateContextProperty, and then for good measure, I call CertControlStore to push the in-memory version of the context to disk. Still no effect. Every function call succeeds, but the private key never makes it to the windows trust store.</p>
  
  <p>So in short, my question is what is the windows certificate import tool doing that I am not that will allow me to store a private key along with the certificate in the windows trust store?</p>
  
  <p>I've found a handful of other questions and program examples and message boards dating back to 2002 and none are very explicit, and none of the code examples do exactly what I need, but I know I have all the pieces, they just don't yield the result.</p>