powershell - 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
最终结果是明显损坏的文件。
解决方案
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)
推荐阅读
- c# - IWpfTextViewCreationListener.TextViewCreated 未触发
- java - 如何做一个没有重复元素的下拉列表?
- android - 如何从我的 ListView 中删除选定的 TextView
- matplotlib - matplotlib - plt.coutourf - 将轮廓扩展到边界点
- .net - 带有令牌示例的 .NET FHIR 客户端
- twitter-bootstrap - 如何向 ionic 4 应用程序添加和使用引导程序?
- javascript - 如何在“聚焦”事件中排除特定的 div
- android - 加载资源失败:服务器响应状态为 400 () Ionic 3 android
- css - 单击时设置 css 样式并在单击时删除它们
- java - 春季数据更新并发读取