c# - 从 C# 代码安装 X509Certificate2 的问题

标签 c# x509certificate2

我正在使用下面的代码安装一个 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/

相关文章:

c# - 如何禁用对用于验证消息签名的 x509 证书的验证?

asp.net - 缓解 Web 服务器上的 RsaCryptoServiceProvider 线程安全问题

c# - Linq:返回具有给定类型的第一个实例的方法

c# - 角色问题

c# - 将大数据集加载到 c# GridView 中的性能问题

c# - X509 证书预期用途和 SSL

c# - 创建继承类的实例时出现 NullReferenceException

c# - "dynamic"XSLT 提供网络浏览器控件?

Azure - 在 Azure Function 中从 base64 构造 X509Certificate2 会导致错误 : The specified network password is not correct

java - 如何获取java的X509Certificate中的策略标识符和基本约束的主体类型