【问题标题】:How can I install a certificate into the local machine store programmatically using c#?如何使用 c# 以编程方式将证书安装到本地机器存储中?
【发布时间】:2010-10-08 16:05:15
【问题描述】:

我有一个通过 MakeCert 生成的证书。我想使用 PeerTrust 将此证书用于 WCF 消息安全性。如何使用 c# 或 .NET 以编程方式将证书安装到“受信任的人”本地计算机证书存储中?

我有一个 CER 文件,但也可以创建一个 PFX。

【问题讨论】:

  • 顺便说一句 - 我知道 Makecert 和信任的细节。请,只是寻找有关使用编程 c# 或 installshield 安装证书的建议。谢谢!
  • 知道如何在 c 程序中执行此操作吗? Windows中有任何API吗??

标签: c# .net wcf certificate makecert


【解决方案1】:

我必须使用 X509KeyStorageFlags。PersistKeySet | X509KeyStorageFlags.MachineKeySet 标志来解决稍后尝试使用证书时发生的“密钥集不存在”错误:

X509Certificate2 certificate = new X509Certificate2(pfxPath, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
{
     store.Open(OpenFlags.ReadWrite);
     store.Add(certificate);
     store.Close();
}

感谢这篇文章:Private key of certificate in certificate-store not readable

【讨论】:

    【解决方案2】:

    我相信这是正确的:

    using (X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine)) 
    {
       store.Open(OpenFlags.ReadWrite);
       store.Add(cert); //where cert is an X509Certificate object
    }
    

    【讨论】:

    • 这成功安装了证书,但是当我在个人商店中打开私钥的管理私钥选项时,它给出了“找不到证书的密钥”错误。
    • 我猜这个答案现在无效,因为 X509Store 不是一次性的。
    • @mit 你找到解决“找不到此证书的私钥”的方法了吗?
    • @mit 你在看“CurrentUser”商店吗?那么您需要将StoreLocation 更改为StoreLocation.LocalMachine
    【解决方案3】:

    您可以将证书添加到“CurrentUser”(适用于我),而不是将证书安装到需要提升权限的 LocalMachine。

    X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadWrite);
    store.Add(cert); //where cert is an X509Certificate object
    store.Close();
    

    【讨论】:

    • 谢谢。这对我来说更可取,因为它将在运行时执行(多个实例)的自托管服务中运行。没有办法提供 UAC 提示。再次感谢!
    【解决方案4】:

    以下内容对我有用:

    private static void InstallCertificate(string cerFileName)
    {
        X509Certificate2 certificate = new X509Certificate2(cerFileName);
        X509Store store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
    
        store.Open(OpenFlags.ReadWrite);
        store.Add(certificate);
        store.Close();
    }
    

    【讨论】:

    • Personnel节点中存储证书,选择枚举值为StorName.My。要将证书存储在Trusted Root Certification Authorities节点中,请选择枚举值为StorName.Root
    猜你喜欢
    • 2013-06-21
    • 2010-09-23
    • 2010-11-28
    • 1970-01-01
    • 2020-06-12
    • 2011-09-11
    • 2011-07-02
    • 2010-12-01
    • 2012-09-29
    相关资源
    最近更新 更多