Bri*_*man 11 c# asp.net certificate x509certificate2 x509certificate
我在我的计算机上安装了证书,当我去查看它时,我看到消息"你有一个与此证书对应的私钥"但是,当我尝试在代码中访问该私钥时,它为空.我使用以下代码获取我的证书:
var x509Certificate = GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=SomeCert");
Run Code Online (Sandbox Code Playgroud)
哪里:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
和:
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;
}
Run Code Online (Sandbox Code Playgroud)
我将证书恢复正常,但是当我尝试访问私钥时,执行以下操作:
x509Certificate.PrivateKey
Run Code Online (Sandbox Code Playgroud)
PrivateKey的值为null.我究竟做错了什么?我需要此值来签署SAML2请求.
注意:我知道我有一些抽象,但关键是我得到了证书(它已找到),但私钥是null.如果有关于我的抽象的更多信息阻止了问题的回答,我可以提供更多细节.
正如它在这里 描述的.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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7668 次 |
| 最近记录: |