2008-11-21 44 views
7

我正在写一个Windows服务,它需要证书存储中的多个证书才能连接到第三方Web服务。将证书安装到C#中的Windows本地用户证书存储区中

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

它工作正常。

我现在需要在用户证书库中安装10个左右的证书(不要问!),但是找不到任何简洁的编程方式。

任何提示?或者我将不得不使用COM interop ...

回答

12

原来你首先需要冒充用户。

使用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在效率期间保持打开状态。

+0

您是否认为您必须模拟用户的原因是您需要阅读私钥的权限?如果是这样的话,那么如果你绝对必须的话,你可以稍后添加权限 – 2012-11-02 19:39:59

相关问题