I'm trying to deploy a certificate into a windows-my store in order to use it for SSL in IIS6.0. When the application is running I don't see any errors in SSLDiag output and everything works perfectly, but once I close the application SSLDiag shows an error:
#WARNING: You have a private key that corresponds to this certificate
but CryptAcquireCertificatePrivateKey failed
I checked the machine keyset and noticed that after I close my application it removes the file with a key which was created. Here is the location I checked:
C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys
How can I preserve the create key file in a machine keyset?
Here is the code I'm using:
using(var openFileDialog = new OpenFileDialog())
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
var password = "password";
var certificate = new X509Certificate2(openFileDialog.FileName, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
var keystore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
keystore.Open(OpenFlags.MaxAllowed);
keystore.Add(certificate);
keystore.Close();
}
}
I tried different variations of X509KeyStorageFlags, but the file is still removed from machine keyset once I close the app. Why the file is removed and how can I prevent it?
I found the solution:
certificate.PrivateKey.PersistKeyInCsp = true;
This lets the private key to remain in the machine key set. I suppose the key was removed when the X509Certificate2 object was freeing its resources.