Install certificates in to the Windows Local user certificate store in C#

后端 未结 1 742
礼貌的吻别
礼貌的吻别 2020-12-05 09:14

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

On my installer I call a sm

相关标签:
1条回答
  • 2020-12-05 09:33

    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:

    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.

    0 讨论(0)
提交回复
热议问题