无法读取X509Certificate2上的私钥

本文关键字:私钥 X509Certificate2 读取 | 更新日期: 2023-09-27 17:51:05

Win 8.1 64位。Powershell 4.0。(虽然我认为这个问题一般与。net有关,而不是特定于Powershell。)

我生成一个自签名证书,如下所示:
New-SelfSignedCertificate -DnsName 'TheIncredibleHulk' -CertStoreLocation Cert:'CurrentUser'My

然后我检索证书:

$Cert = Get-Item Cert:'CurrentUser'My'9E5A8322B890DA1247BD98BDAB288CA9D11CF99E

证书有一个私钥:

$Cert.HasPrivateKey
True

是吗?

$Cert.PrivateKey
(null)

为什么PrivateKey成员为空?我如何检索私钥?

无法读取X509Certificate2上的私钥

对于其他遇到这种情况的人,我怀疑这个问题与New-SelfSignedCertificate使用的存储提供者有关(参见http://blogs.technet.com/b/vishalagarwal/archive/2010/03/30/verifying-the-private-key-property-for-a-certificate-in-the-store.aspx,其中讨论了Microsoft软件密钥存储提供者和. net类的问题)。technet上有一个powershell脚本可以创建自签名证书,默认使用不同的存储提供商。

这个答案让我想到了一个变通方法。这个问题是由默认的提供者引起的,但是在Win10版本New-SelfSignedCertificate中,你可以指定提供者,如下所示。

New-SelfSignedCertificate -DnsName HulkSmash -CertStoreLocation Cert:'LocalMachine'My  -KeyAlgorithm RSA -KeyLength 2048 -KeyExportPolicy Exportable -KeyProtection None -Provider 'Microsoft Enhanced RSA and AES Cryptographic Provider'