在 C# 中将证书安装到 Windows 本地用户证书存储中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/308554/
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
Install certificates in to the Windows Local user certificate store in C#
提问by DavidWhitney
I'm writing a Windows service that needs several certificates in the certificate store in order to connect to a third party web service.
我正在编写一个 Windows 服务,它需要证书存储中的多个证书才能连接到第三方 Web 服务。
On my installer I call a small application (C#) that creates a user to run the service as.
在我的安装程序上,我调用一个小应用程序 (C#),它创建一个用户来运行服务。
It works fine.
它工作正常。
I now need to install about 10 certificates (don't ask!) into the users certificate store, but can't find any succinct programmatic way to do so.
我现在需要将大约 10 个证书(不要问!)安装到用户证书存储中,但找不到任何简洁的编程方式来这样做。
Any hints? Or am I going to have to use COMinterop...
任何提示?还是我将不得不使用COM互操作...
采纳答案by DavidWhitney
Turns out you first need to impersonate the user.
事实证明,您首先需要模拟用户。
Using the very nice library described in A small C# Class for impersonating a User, you can do the following:
使用A small C# Class for impersonating a User 中描述的非常好的库,您可以执行以下操作:
using (new Impersonator("username", "", "password"))
{
try
{
X509Store serviceRuntimeUserCertificateStore = new X509Store(StoreName.My);
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string certPath = Path.Combine(baseDir, certificateFolder);
string certificateFile = "c:\file.cert";
string certificatePassword = "somePassword";
string certificateLocation = certPath + "\" + certificateFile;
InstallCertificate(certificateLocation, certificatePassword);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private static void InstallCertificate(string certificatePath, string certificatePassword)
{
try
{
var serviceRuntimeUserCertificateStore = new X509Store(StoreName.My);
serviceRuntimeUserCertificateStore.Open(OpenFlags.ReadWrite);
X509Certificate2 cert;
try
{
cert = new X509Certificate2(certificatePath, certificatePassword);
}
catch(Exception ex)
{
Console.WriteLine("Failed to load certificate " + certificatePath);
throw new DataException("Certificate appeared to load successfully but also seems to be null.", ex);
}
serviceRuntimeUserCertificateStore.Add(cert);
serviceRuntimeUserCertificateStore.Close();
}
catch(Exception)
{
Console.WriteLine("Failed to install {0}. Check the certificate index entry and verify the certificate file exists.", certificatePath);
}
}
Please add your own exception handling. If you're adding multiple certificates keep the X509Store open for the duration for efficiency.
请添加您自己的异常处理。如果您要添加多个证书,请在此期间保持 X509Store 打开以提高效率。