2012-02-02 60 views
0

如何在本地計算機密鑰庫中編程導入私鑰?如何在本地機器密鑰庫中編程導入私鑰?

實際上我測試這個代碼:

private static void InstallCertificate(string certificatePath, string certificatePassword, StoreName store) { 
     try { 
      var serviceRuntimeUserCertificateStore = new X509Store(store, StoreLocation.LocalMachine); 
      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); 
     } 
    } 

所有試圖獲得在NetworkService令牌失敗呢。代碼here不適用於管理員權限。

上面的代碼將私鑰導入本地計算機的currient用戶instat。我該怎麼辦?

回答

1

MSDN有一個solution。簡單地添加一個標誌X509KeyStorageFlags.MachineKeySet,它運行良好:

cert = new X509Certificate2(certificatePath, 
          certificatePassword, 
          X509KeyStorageFlags.MachineKeySet);