PublicKey.Key.Encrypt 错误您不能在空值表达式上调用方法

PublicKey.Key.Encrypt error You cannot call a method on a null-valued expression

我一直在这个脚本上收到空值错误:

$key = $cert.PrivateKey.Decrypt($object.Key, $true)

它取自 powershell 示例,所以我不知道为什么它不起作用。有什么线索吗?使用指纹正确找到证书,密钥就在其中。

这是 运行 Windows 2012 R2 with powershell v4

try
{
    $object = Import-Clixml -Path c:\temp\encryptionTest.xml

    $thumbprint = '58E3080C84336ECFBBF9EFFCFF98788880F0BA5F'

    $cert = Get-Item -Path Cert:\LocalMachine\My$thumbprint -ErrorAction Stop

    $key = $cert.PrivateKey.Decrypt($object.Key, $true)
    $cert.PrivateKey
    $secureString = $object.Payload | ConvertTo-SecureString -Key $key
    $secureString
}
finally
{
    if ($null -ne $key) { [array]::Clear($key, 0, $key.Length) }
}

更新:我联系了脚本作者,他提到问题是 .NET 开箱即用的 CNG(下一代加密货币)证书不能很好地运行,这些证书被标识为版本 3(这正是版本我们使用)他提供了一个与这些一起使用的新功能。

我联系了脚本作者,他提到问题是 .NET 开箱即用的 CNG(下一代加密货币)证书不能很好地运行,这些证书被标识为版本 3(这正是我们使用的版本) 他提供了一个与这些一起工作的新函数。

https://github.com/dlwyatt/ProtectedData

我遇到了同样的问题,但我没有从 Cert:\LocalMachine\My 获取证书,而是将其更改为

$cert = Get-Item -Path Cert:\CurrentUser\My$thumbprint -ErrorAction Stop

而且效果很好。