【问题标题】:Install certificates in to the Windows Local user certificate store in C#在 C# 中将证书安装到 Windows 本地用户证书存储中
【发布时间】:2010-09-23 10:33:53
【问题描述】:

我正在编写一个 Windows 服务,它需要证书存储中的多个证书才能连接到第三方 Web 服务。

在我的安装程序中,我调用了一个小型应用程序 (C#),它创建了一个用户来运行服务。

效果很好。

我现在需要将大约 10 个证书(不要问!)安装到用户证书存储中,但找不到任何简洁的编程方式。

有什么提示吗?还是我必须使用COM interop...

【问题讨论】:

    标签: c# windows certificate certificate-store


    【解决方案1】:

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

    使用 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);
        }
    }
    

    请添加您自己的异常处理。如果您要添加多个证书,请保持 X509Store 保持打开状态以提高效率。

    【讨论】:

    • 您认为您必须冒充用户的原因是因为您需要读取私钥的权限吗?如果是这样,如果您绝对需要,您可能可以稍后添加权限。
    猜你喜欢
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 2014-01-27
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    相关资源
    最近更新 更多