应用程序关闭时,证书将从计算机密钥集中删除

时间:2012-10-18 14:58:14

标签: iis-6 keystore x509certificate2

我正在尝试将证书部署到windows-my store中,以便在IIS6.0中将其用于SSL。 当应用程序运行时,我没有看到SSLDiag输出中的任何错误,一切都运行正常,但一旦我关闭应用程序SSLDiag显示错误:

#WARNING: You have a private key that corresponds to this certificate 
but CryptAcquireCertificatePrivateKey failed

我检查了机器密钥集,发现在我关闭应用程序后,它会删除带有创建密钥的文件。这是我检查的位置:

C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys 

如何在机器密钥集中保留创建密钥文件?

以下是我正在使用的代码:

        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();
            }
        }

我尝试了X509KeyStorageFlags的不同变体,但是一旦我关闭应用程序,该文件仍然从机器密钥集中删除。为什么删除文件以及如何防止它?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:

certificate.PrivateKey.PersistKeyInCsp = true;

这使私钥保留在机器密钥集中。 我想当X509Certificate2对象释放其资源时,密钥已被删除。