我在我的电脑上安装了一个证书,当我想查看它时,会看到消息“您有与此证书相对应的私钥”,但是当我在代码中尝试访问该私钥时,它是空的。我使用以下代码来获取我的证书:
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的值为null。我做错了什么?我需要这个值来签署SAML2请求。
注:我知道我的代码有些抽象,但我的意思是我已经检索到证书(它被找到了),但私钥却是null。如果还有任何阻止回答问题的抽象信息,请告诉我,我可以提供更多细节。