在C#中的Windows的本地用户证书存储安装证书 [英] Install certificates in to the Windows Local user certificate store in C#

查看:332
本文介绍了在C#中的Windows的本地用户证书存储安装证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个Windows服务,为需要在证书存储多个证书来连接到第三方Web服务。

I'm writing a Windows service that needs several certificates in the certificate store in order to connect to a third party web service.

在我安装我称之为一个小应用程序(C#)创建一个用户来运行服务为。

On my installer I call a small application (C#) that creates a user to run the service as.

它工作正常。

我现在需要安装约10证书(不要问!)到用户的证书存储,但无法找到任何简洁编程的方式这样做。

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.

任何提示?还是我将不得不使用 COM互操作 ...

Any hints? Or am I going to have to use COM interop...

推荐答案

原来你首先需要模拟用户。

Turns out you first need to impersonate the user.

使用的 一个小的C#类所描述的非常漂亮的图书馆模拟用户 的,你可以做到以下几点:

Using the very nice library described in A small C# Class for impersonating a User, you can do the following:

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开放对效率的持续时间。

Please add your own exception handling. If you're adding multiple certificates keep the X509Store open for the duration for efficiency.

这篇关于在C#中的Windows的本地用户证书存储安装证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆