Issue with adding a certificate to a certificate store
I'm running into a really strange issue where if I don't dump the certificate I am trying to add to the store, the next time I try to use the certificate I will receive an error "Keyset does not exist". Once I use the Dump method on newCertificate the private key appears in the store as expected. If I dump the newCertificate.PrivateKey instead of newCertificate I see the private key but, once it is added to the store the private key will be missing again.
Is the Dump method doing something special to certificates when it dumps them that might explain this? In this particular case I am pulling the certificate bytes from Azure Key Vault and creating a certificate from them.
Is the Dump method doing something special to certificates when it dumps them that might explain this? In this particular case I am pulling the certificate bytes from Azure Key Vault and creating a certificate from them.
var newCertificate = new X509Certificate2(Convert.FromBase64String(keyVaultSecret.Value));
newCertificate.Dump(); //If you don't dump the certificate before adding it to the store it will be missing the private key.
if (!newCertificate.Verify())
Console.WriteLine("Unable to verify certificate.");
Console.WriteLine($"Retrieved certificate with Thumbprint: {newCertificate.Thumbprint}");
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
store.Add(newCertificate);
if (store.Certificates.Find(X509FindType.FindByThumbprint, newCertificate.Thumbprint, false).Count == 0)
Console.WriteLine("Certificate NOT added to the store.");
else
Console.WriteLine("Certificate added to the store.");
store.Close();
Comments
var newCertificate = new X509Certificate2(Convert.FromBase64String(keyVaultSecret.Value), string.Empty, X509KeyStorageFlags.PersistKeySet);
Would still be interesting to know how and why Dump is somehow adding this flag to the object when writing it to the results window.