2013-03-08 215 views
4

我們有一些嵌入PFX證書的單元測試。這些證書在測試執行期間被讀取並且變爲X509Certificate2對象。不幸的是,當非特權用戶身份運行,我們得到Access Denied例外:創建X509Certificate2對象時,爲什麼會出現Access Denied錯誤?

using (var s = EmbeddedResourceUtilities.GetEmbeddedResourceAsStream(typeThatContainsEmbeddedResource, certFileName)) 
{ 
    if (s == null) 
    { 

     throw new ApplicationException(String.Format("Embedded certificate {0} for type {1} not found.", certFileName, typeThatContainsEmbeddedResource.FullName)); 
    } 

    try 
    { 
     var bytes = new byte[s.Length]; 
     s.Read(bytes, 0, (int)s.Length); 
     return new X509Certificate2(bytes); 
    } 
    catch (Exception ex) 
    { 
     throw new ApplicationException(String.Format("Error loading embedded certificate {0} for type {1}.", certFileName, typeThatContainsEmbeddedResource.FullName), ex); 
    } 
} 

這裏的例外:

System.Security.Cryptography.CryptographicException:拒絕訪問。
在System.Security.Cryptography.CryptographicException.ThrowCryptographicException(的Int32小時)
在System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(字節[] RAWDATA,IntPtr的密碼,UInt32的dwFlags中,布爾persistKeySet,SafeCertContextHandle & pCertCtx)
在System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(字節[] RAWDATA,對象密碼,X509KeyStorageFlags keyStorageFlags)
在System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(字節[] RAWDATA)

我試過了modif穎構造函數使用空密碼和密鑰集的明確標誌,但不解決它:

// this doesn't work, either 
return new X509Certificate2(bytes, String.Empty, X509KeyStorageFlags.MachineKeySet); 

我在其他地方看,我應該給我的特權用戶爲MachineKeys目錄增加權限,但我不願意這樣做,因爲它允許生產代碼假設這些權限在測試環境以外的目錄中可用。

有沒有辦法允許非特權用戶從文件中加載X509Certificate?

回答

4

這是我對發生了什麼事情的最好猜測。

X509Certificate2構造函數在機器密鑰目錄(我相信通過Windows本地安全機構)中創建臨時公鑰/私鑰對象。由於我們的非特權用戶無權訪問這些密鑰或計算機密鑰目錄,因此測試失敗。

我們的解決方案是更新我們的環境設置腳本以提前安裝這些測試證書,授予他們無特權的用戶權限,並重新編寫測試以從相應的證書存儲區加載證書。

+2

我有同樣的問題。你能提供一個例子嗎?謝謝 – 2014-11-24 17:46:40

相關問題