代码之家  ›  专栏  ›  技术社区  ›  DavidWhitney

将证书安装到C中的Windows本地用户证书存储中#

  •  7
  • DavidWhitney  · 技术社区  · 18 年前

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

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

    它很好用。

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

    有什么暗示吗?还是我要用 COM 互操作…

    1 回复  |  直到 10 年前
        1
  •  12
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

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

    使用中描述的非常好的库 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打开。