I have a file (.p12) that contains 3 certificates (chained together) password-protected, that i have installed on my store. I'm trying to load them to my code. The way I load them from the file is like this:
 var clientCert = new X509Certificate2(@"myfile.p12", "mypassword");
How can i achieve the same result while loading them from the store?
I've tried:
var computerCaStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine); 
computerCaStore.Open(OpenFlags.ReadOnly); 
var certificates = computerCaStore.Certificates.OfType<X509Certificate2>().ToList(); 
var certFromStore = certificates.Single(c => c.Thumbprint == thumbprintMerchant);
var newCert = new X509Certificate2(certFromStore.RawData, "mypassword");
certFromStore should be equivalent to clientCert, the last line is what's breaking you.
The RawData property on X509Certificate2 returns the DER-encoded value for the certificate, not the original file bytes.  A certificate does not have a private key, so the last line strips it away.  Your question had previously mentioned a TLS exception, and that is because your cert no longer has a private key.
If certFromStore.HasPrivateKey is false, then whatever you did to put the certificate into the store didn't work the way you think it did.  It's pretty unusual for a certificate with a private key to be in the Root store.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With