簡體   English   中英

無法從證書中獲取私鑰

[英]Cant get private key from certificate

因此,我無法從證書中獲取私鑰。 這是我第一次使用證書,我試圖找到解決方案,但我無法工作。 它是一個控制台應用程序,需要密鑰來簽署 SOAP 消息/請求。

這是一個代碼示例; (如果您還需要什么,請告訴我)

    public static X509Certificate2 FindCertificate(string issuedBy)
    {
        var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadOnly);

        //We gets the certificate from store
        var certificate = store.Certificates.Cast<X509Certificate2>().FirstOrDefault(c => c.Issuer.Contains($"CN={issuedBy}"));
        if (certificate.HasPrivateKey) // Result: True
        {
            //PrivateKey throws error: Keyset dosent exist
            var key = certificate.PrivateKey;

        }

        if (certificate == null)
        {
            throw new ArgumentException($"Could not find certificate issued by: '{issuedBy}'", nameof(issuedBy));
        }

        var expireDate = DateTime.Parse(certificate.GetExpirationDateString());

        if (expireDate < DateTime.Now)
        {
            throw new Exception($"Certificate has already expired: '{expireDate}'");
        }

      

        return certificate;
    }

我現在只需在管理員模式下啟動 Visual Studio 就可以讓它工作。

您自己的解決方案的替代方案(因此您不必在管理員模式下運行 VS 是授予您自己的用戶讀取私鑰的權限。

  1. 打開機器證書的證書管理器(在 Windows 主菜單搜索中輸入“證書”並選擇“管理計算機證書”
  2. 找到證書並右鍵單擊->“所有任務”->“管理私鑰...” 在此處輸入圖片說明
  3. 點擊“添加...”
  4. 輸入您的用戶名(然后單擊“檢查名稱”以查看您是否輸入正確) 在此處輸入圖片說明
  5. 單擊“確定”和“確定”

現在您應該能夠正常運行您的應用程序(和 VS)並訪問私鑰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM