如何使用 c# 以编程方式将证书安装到本地机器存储中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/566570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:27:04  来源:igfitidea点击:

How can I install a certificate into the local machine store programmatically using c#?

c#.netwcfcertificatemakecert

提问by J Davis

I have a certificate generated via MakeCert. I want to use this certificate for WCF message security using PeerTrust. How can I programmatically install the certificate into the "trusted people" local machine certificate store using c# or .NET?

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

I have a CER file, but can also create a PFX.

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

采纳答案by Demi

I believe that this is correct:

我相信这是正确的:

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

回答by Demi

The following works good for me:

以下对我有用:

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

回答by user1799563

Instead of installing the certificate to LocalMachine which requires elevated privileges you can add it to "CurrentUser" (works for me).

您可以将证书添加到“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();

回答by Dmitry

I had to use X509KeyStorageFlags.PersistKeySet| X509KeyStorageFlags.MachineKeySetflags to resolve "Keyset does not exist"error that occurred later on attempt to use the certificate:

我不得不使用 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();
}

Thanks to this article: Private key of certificate in certificate-store not readable

感谢这篇文章:证书存储中证书的私钥不可读