在Powershell中使用RSACryptoServiceProvider解密文件

问题描述

我在Debian机器上使用以下命令使用私钥对文件加密:

openssl rsautl -encrypt -inkey private.pem -in test.txt -out test.txt.ssl 

我还使用python脚本将我的公钥从pem转换为xml:https://github.com/MisterDaneel/PemToXml

我正在尝试解密Windows计算机上的test.txt.ssl文件,但无法安装任何软件。所以我只需要使用RSACryptoServiceProvider。我的powershell脚本如下所示:

$InputFileLocation = (Get-Location).tostring() + "\public.pem.xml"
$InputFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($InputFileLocation)
$pemRawStr = (Get-Content $InputFile) -join ''

$rsa = New-Object -TypeName System.Security.Cryptography.RSACryptoServiceProvider
$key = $rsa.FromXmlString($pemRawStr)
$rsa.ExportParameters($false)
[byte[]]$str = Get-Content "test.ssl" -Encoding Byte
$DecryptedStr = $rsa.Decrypt($str,$false);  
Write-Host "File content : " $DecryptedStr

但是它不起作用。我有这个错误

Exception calling "Decrypt" with "2" argument(s): "Key doesn't esist.
"
At C:\Users\RICHARDAN\Documents\Dev - Git\protectmi_analysis_processing-master\windows\test.ps1:9 char:1
+ $DecryptedStr = $rsa.Decrypt($str,$false);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [],MethodInvocationException
    + FullyQualifiedErrorId : CryptographicException

解决方法

Jeroen Mostert comments一样,这里的问题是Decrypt()期望[byte[]],而不是[string]

要解决此问题,请使用Get-Content -Encoding Byte并分配给具有[byte[]]类型约束的变量:

[byte[]]$str = Get-Content "test.ssl" -Encoding Byte
$DecryptedStr = $rsa.Decrypt($str,$false);  
Write-Host "File content : " $DecryptedStr