c# - 通过代码访问时私钥为空,为什么?

标签 c# asp.net certificate x509certificate x509certificate2

我的机器上安装了一个证书,当我去查看它时,我看到消息“您有一个与该证书相对应的私钥”但是,当我尝试在代码中访问该私钥时,它是无效的。我使用以下代码获取我的证书:

var x509Certificate = GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=SomeCert");

地点:

public X509Certificate2 GetCertificate(string storeName, string storeLocation, string subjectName)
{
     var store = new X509Store(getStoreName(storeName), getStoreLocation(storeLocation));
     X509Certificate2Collection certificates = null;
     store.Open(OpenFlags.ReadOnly);

     try
     {
          X509Certificate2 result = null;
          certificates = store.Certificates;
          return getCertificateResult(certificates, subjectName, result);
     }
     finally
     {
          if (certificates != null)
          {
               foreach (var cert in certificates)
               {
                    cert.Reset();
               }
          }
          store.Close();
     }
}

和:

private static X509Certificate2 getCertificateResult(IEnumerable certificates, string subjectName, X509Certificate2 result)
{
     foreach (var cert in certificates.Cast<X509Certificate2>().Where(cert => cert.SubjectName.Name != null && cert.SubjectName.Name.ToLower() == subjectName.ToLower()))
     {
          if (result != null)
          {
             throw new ApplicationException(string.Format("There is more than one certificate found for subject Name {0}", subjectName));
          }
          result = new X509Certificate2(cert);
     }

     if (result == null)
     {
          throw new ApplicationException(string.Format("No certificate was found for subject Name {0}", subjectName));
     }
     return result;
}

我的证书恢复正常,但是当我尝试访问私钥时,执行以下操作:

x509Certificate.PrivateKey

PrivateKey 的值为空。我究竟做错了什么?我需要这个值来签署 SAML2 请求。

注意:我知道我在那里有一些抽象,但关键是我取回了证书(已找到),但私钥为空。如果有关于我的抽象的更多信息阻止问题得到回答,我可以提供更多详细信息。

最佳答案

正如描述的那样here .cer 文件(我猜它也适用于所有证书格式)不能包含私钥。从安全的角度来看,它看起来是正确的,因为这个文件是公开的。
但是 X509Certificate2 不仅仅是一个证书,它还是证书本身和其他一些东西的容器。这就是它具有属性 PrivateKey 的原因。如果您在代码中需要此信息并且您有私钥文件 (.pvk) 和密码 - 您可以使用 .pfx 文件而不是 .cer。它可以使用 pvk2pfx 实用程序创建:

> MakeCert -r -pe -ss SampleStoreName -n "CN=Sample" Sample.cer -sky exchange -sv Sample.pvk
> pvk2pfx -pvk Sample.pvk -pi SamplePassword -spc Sample.cer -pfx Sample.pfx -f

关于c# - 通过代码访问时私钥为空,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14754609/

相关文章:

c# - Windows、.NET 读取鼠标光标下的文本

c# - 遍历 sql(SQL 或 Asp.net C#)的最佳方法是什么?

python - SimpleITK 的 sudo easy_install 没那么容易

java - 从基于 Glassfish 的 Web-AP 访问 HTTPS Web 服务

c# - 在 ListArray C# 中搜索

c# - C# 中是否有命名参数的样式指南?

c# - MapControllerRoute ,值不能为 null

c# - 尝试将我的 Web 应用程序从 VS Enterprise 2015 update 1 发布到 azure 时出错 :

c# - 使用 "using"时的意外行为

c# - 证书问题c#