[英]Install certificates in to the Windows Local user certificate store in C#
我正在編寫一個Windows服務,它需要證書存儲區中的多個證書才能連接到第三方Web服務。
在我的安裝程序中,我調用一個小應用程序(C#)創建一個用戶來運行服務。
它工作正常。
我現在需要在用戶證書存儲中安裝大約10個證書(不要問!),但是找不到任何簡潔的編程方法。
任何提示? 或者我將不得不使用COM互操作...
事實證明,您首先需要冒充用戶。
使用小型C#類中描述的非常好的庫來模擬用戶 ,您可以執行以下操作:
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);
}
}
請添加您自己的異常處理。 如果您要添加多個證書,請保持X509Store在效率期間保持打開狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.