【问题标题】:PrivateKey is missing when importing a certificate导入证书时缺少 PrivateKey
【发布时间】:2021-05-15 08:21:28
【问题描述】:

我一直在使用以下 cdmlet 将 PFX 证书导入 Windows Docker 容器:

Import-PfxCertificate -FilePath $CertificatePath -CertStoreLocation $location -Password $securePassword

直到 2 天前(可能与 CVE-2021-1731 相关)之前,这一切正常,当时一些测试开始失败并出现以下错误:

System.Security.Cryptography.CryptographicException : 密钥在指定状态下无效。

运行 Get-ChildItem Cert:\ -Recurse | Format-List * 我能够发现 Docker 映像的先前版本和最新版本之间的一些差异。

在以前的(工作版本)中:

 HasPrivateKey            : True
 PrivateKey               : System.Security.Cryptography.RSACryptoServiceProvider

在最新(失败的版本)中:

 HasPrivateKey            : True
 PrivateKey               : 

我正在尝试在LocalMachineCurrentUser 商店中安装证书。基于其他 SO 帖子,并提出了这个作为 Import-PfxCertificate ... 的替代方案:

$CertificatePath = "..." 
$securePassword = "..."

$StoreLocations=@()
$StoreLocations += 'Cert:\LocalMachine\My'
$StoreLocations += 'Cert:\LocalMachine\Root'
$StoreLocations += 'Cert:\CurrentUser\My'
$StoreLocations += 'Cert:\CurrentUser\Root'

foreach($location in $StoreLocations){
    $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
    $certificate.Import($CertificatePath, $securePassword, "PersistKeySet,MachineKeySet")

    $storeLocation = $location.Split("\")[1] # e.g. LocalMachine
    $storeName = $location.Split("\")[2] # e.g. My
    $store = New-object System.Security.Cryptography.X509Certificates.X509Store($storeName, $storeLocation)
    $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::"ReadWrite")
    $store.Add($certificate)
    $store.Close() 
}

这似乎适用于 LocalMachine 商店,但对于 CurrentUser 却失败了(拒绝访问)。

我还尝试根据商店设置不同的值,但没有成功:

if($location -Match "CurrentUser"){
    $certificate.Import($CertificatePath, $securePassword, "PersistKeySet,UserKeySet")
}
elseif($location -Match "LocalMachine"){
    $certificate.Import($CertificatePath, $securePassword, "PersistKeySet,MachineKeySet")
}

我有什么遗漏的吗?

【问题讨论】:

    标签: c# .net powershell certificate x509certificate


    【解决方案1】:

    一切看起来都不错。 HasPrivateKey 返回$true,所以私钥就在那里。 PrivateKey 属性为空的事实意味着密钥存储在密钥存储提供程序而不是传统 CSP 中。事实上,X509Certificate2.PrivateKey 属性自 .NET 4.6 以来已过时。

    【讨论】:

    • 但是什么可以解释证书的变化呢?这些可能是错误的原因:System.Security.Cryptography.CryptographicException : Key not valid for use in specified state.
    • 你从哪里得到这个异常?
    • 运行 .NET 测试。这些证书安装到我们用作 Azure DevOps 构建代理的 Docker 映像中。
    • 它仍然没有回答我之前的问题——在哪里?能否提供代码 sn-p 并指向导致异常的行?
    • 您可能需要针对此异常问题提出一个新问题。
    猜你喜欢
    • 2015-11-22
    • 2015-10-24
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多