我正在使用下面的代码安装一个 pfx 文件(密码和 certPath 被传递到方法中):
X509Certificate2 cert = password != string.Empty ? new X509Certificate2(certPath, password) : new X509Certificate2(certPath);
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
store.Close();
这在某些机器上可行,但在其他环境中每次都会失败。没有抛出异常,但是当我加载 mmc.exe 并添加证书管理单元时,证书似乎没有正确安装。它显示在正确的商店下,但是当我右键单击证书并进入“所有任务”>“管理私钥”下时,它会加载一个对话框,提示“找不到对象”。事件查看器中没有任何记录,单步执行似乎已正确执行的代码。
FindPrivateKey.exe 也找不到 key 。
什么可能导致此证书无法在某些看起来与其工作环境相同的机器上运行?
从证书管理单元中删除 key 并重新导入它是有效的,但我需要它在 C# 代码中可靠地工作。
编辑 - 我应该补充一点,失败的证书有一个密码,这意味着第一行代码实际上是:
X509Certificate2 cert = new X509Certificate2(certPath, password);
最佳答案
您是否尝试过添加 X509KeyStorageFlags?
new X509Certificate2(certPath, password, X509KeyStorageFlags.PersistKeySet);
编辑:问题的实际答案可以在这篇知识库文章中找到:http://support.microsoft.com/kb/950090
When the certificate is installed using the X509Certificate or X509Certificate2 class, X509Certificate/X509Certificate2 by default creates a temporary container to import the private key. The private key is deleted when there is no longer a reference to the private key.
关于c# - 从 C# 代码安装 X509Certificate2 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16276213/