[英]X509Certificate2.Export fails with “Keyset does not exist” in console application
[英]X509Certificate - Keyset does not exist
我有一個使用 WCF 的WinForms應用程序,並將證書作為參數傳遞給函數:
mySvcClient.SendDocument(cert.Export(X509ContentType.SerializedCert, "password"));
...
在 WCF 服務中,我從字節數組重新創建了證書:
public void SendDocument (byte[] binaryCert)
{
X509Certificate2 cert = new X509Certificate2(binaryCert, "password");
...
但是當使用證書對 xml 進行簽名時,出現錯誤“Keyset 不存在”:
if (cert.HasPrivateKey) // WORKS!!!
{
signedXml.SigningKey = cert.PrivateKey; // THROW "keyset does not exist" EXCEPTION
...
在我的電腦上,應用程序 100% 運行! 但是在 WebServer 中,我得到了這個錯誤!
問題是:即使 X509Certificate2 從字節數組重新創建,我需要一些特殊權限才能訪問私鑰?
謝謝!
如果您使用的是 windows server 2008 或 windows 7,那么您需要讀取私鑰的權限。
FindPrivateKey My LocalMachine -n "CN=MyCert" –a
它返回路徑:C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys[File Name]
轉到該路徑並打開文件屬性
轉到安全選項卡
點擊“編輯”,然后點擊“添加”
在打開的對話框中寫入:IIS AppPool\[您的應用程序池名稱],然后單擊確定
現在您的應用程序池有權讀取此私鑰。
我遇到了這個問題,我的證書有私鑰但我收到了這個錯誤(“密鑰集不存在”)
原因:您的網站在“網絡服務”帳戶下運行或權限較低。
解決方案:將應用程序池標識更改為“本地系統”,重置 IIS並再次檢查。 如果它開始工作,那就是權限/較少權限問題,您也可以模擬然后使用其他帳戶。
我遇到了同樣的問題,我不知道如何(我感到羞恥),但它奏效了:
var certificate = new X509Certificate2(filePath, password,
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
certificate.PrivateKey; // before: error "KeySet does not exist"!
using (certificate.GetRSAPrivateKey()) { } // pure black magic
certificate.PrivateKey; // after: just works! lol
我希望有人能解答這個謎。
Vano Maisuradze 回答有效。 如果您正在尋找 FindPrivateKey 工具,它包含在 .NET Framework 4 的 Windows Communication Foundation (WCF) 和 Windows Workflow Foundation (WF) 示例中,可在此處找到:http: //www.microsoft.com/en-我們/下載/confirmation.aspx?id=21459
下載並解壓后,在 Visual Studio 中打開項目:WF_WCF_Samples\WCF\Setup\FindPrivateKey\CS 並進行編譯。 然后打開命令提示符並導航到:WF_WCF_Samples\WCF\Setup\FindPrivateKey\CS\bin
然后繼續 Vano Maisuradze 回答
我認為問題在於您需要將密鑰添加到機器的證書存儲中。
默認情況下,應用程序池身份帳戶無權訪問證書存儲。
您要么更改為 Vaibhav.Inspired 指出的Network Services
帳戶,要么授予對證書的訪問權限。
要允許訪問,請執行以下命令:
WinHttpCertCfg.exe -g -c LOCAL_MACHINE\MY -s "IssuedToName" -a "AccountName"
筆記:
- The tool may need to be installed first. The setup will place the tool at `C:\Program Files (x86)\Windows Resource Kits\Tools\WinHttpCertCfg.exe`.
- `IssuedName` is the issuer property of the certificate that the application will attempt to access
- The command must be run from command prompt with elevated privileges
參考:https: //support.microsoft.com/en-us/help/901183/how-to-call-a-web-service-by-using-a-client-certificate-for-authentica步驟 2
此外,您還需要在安裝證書時啟用Mark this key as exportable
選項。
幾個故障排除步驟:
如果您能夠調試應用程序,請嘗試在管理員模式下運行 IDE。您還可以從 MMC 添加新用戶。
我在 c# 控制台應用程序上遇到了同樣的問題,在這里閱讀答案后,我認為問題出在權限上。 然后我以管理員身份運行 Visual Studio ,它工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.