【发布时间】:2013-01-23 03:48:34
【问题描述】:
我的机器上安装了一个证书,当我去查看它时,我看到消息“您有一个与此证书对应的私钥”但是,当我尝试在代码中访问该私钥时,它是空值。我使用以下代码来获取我的证书:
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 请求。
注意:我知道我在其中有一些抽象,但重点是我取回了证书(已找到)但私钥为空。如果有任何关于我的抽象的更多信息导致问题无法回答,我可以提供更多细节。
【问题讨论】:
-
您的应用程序是否在您的登录用户下运行?可能是权限问题?虽然我认为这会引发异常,而不仅仅是给出一个空值。
-
在“管理私钥”下,运行应用程序池的用户列出了完全控制权。是这个意思吗?
-
你确定你周围没有任何例外吗?
-
没有抛出异常,只是一个 null PrivateKey
标签: c# asp.net certificate x509certificate x509certificate2