我的机器上安装了一个证书,当我去查看它时,我看到消息“您有一个与此证书对应的私钥”但是,当我尝试在代码中访问该私钥时,它为空。我使用以下代码获取我的证书:
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 请求。
注意:我知道我在那里有一些抽象,但重点是我取回了证书(已找到),但私钥为空。如果有更多关于我的抽象的信息阻止问题得到回答,我可以提供更多细节。