首页 > 解决方案 > docx和pdf文件的AES加密/解密不起作用

问题描述

我有一段 Powershell 脚本可以成功加密和解密文本文件,但它似乎不适用于 .docx 或 .pdf 文件,甚至无法处理重要的 jpeg。

$newcert="cert-test"
New-SelfSignedCertificate -DnsName $newcert -CertStoreLocation "Cert:\CurrentUser\My" -KeyUsage KeyEncipherment,DataEncipherment,KeyAgreement -Type DocumentEncryptionCert -NotAfter (Get-Date).AddDays(30)  -FriendlyName $newcert
$cert=Get-ChildItem -Path Cert:\CurrentUser\My\ | Where-Object subject -like "*$newcert*"
$thumb=$cert.thumbprint
$file = "d:\target\test\Test.pdf"
# protect
Get-Content $file | Protect-CmsMessage -To $thumb -OutFile $file

#unprotect
Unprotect-cmsmessage -LiteralPath $file -To $thumb 

最终结果是明显损坏的文件。

标签: powershellencryptionaespfx

解决方案


Protect-CmsMessage只能加密文本。预计其他文件类型会损坏。

一种可能的解决方法是在加密之前对文件进行 Base64 编码。

$File = [System.IO.File]::ReadAllBytes('C:\Windows\System32\calc.exe')
$Base64 = [System.Convert]::ToBase64String($File)
$Base64 | Protect-CmsMessage -To $thumb | Out-File -FilePath $env:TEMP\encrypted.txt

请记住,接收器必须解码 Base64 字符串。

$Base64 = Get-Content -Path $env:TEMP\encrypted.txt | Unprotect-CmsMessage -To $thumb
$ByteStream = [System.Convert]::FromBase64String($Base64)
[System.IO.File]::WriteAllBytes("$env:TEMP\calc.exe", $ByteStream)

推荐阅读