这是AES加密PowerShell较大文件的正确方法吗?
我首先尝试将文件内容加载到某些变量中,并使用[io.file] :: ReadAllBytes
,
但这需要大量RAM,并且痛苦慢。
所以这就是我得到的:
ErrorActionPreference = "Stop"
$AES = [System.Security.Cryptography.AES]::Create()
$AES.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7
$AES.Mode = [System.Security.Cryptography.CipherMode]::CBC
$AES.BlockSize = 128
$AES.KeySize = 256
$AES.GenerateKey()
$AES.GenerateIV()
$Encryptor = $AES.CreateEncryptor()
$File = Get-Item -Path "C:\Myfile.exe"
$InputStream = New-Object System.IO.FileStream($File, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
$OutputStream = New-Object System.IO.FileStream((($File.FullName) + ".AES"), [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write)
$CryptoStream = New-Object System.Security.Cryptography.CryptoStream($OutputStream, $Encryptor, [System.Security.Cryptography.CryptoStreamMode]::Write)
$InputStream.CopyTo($CryptoStream)
$CryptoStream.Dispose()
$AES.Dispose()
它有效。但是,我想知道这是否应该如何做。我不需要将IV预先置于文件的开头,还是使用加密器自动发生?
感谢提前的任何回复。
I've tried first by loading the file content into some variable with [IO.File]::ReadAllBytes
But that takes a lot of RAM and it's painfully slow.
So here's what I've got:
ErrorActionPreference = "Stop"
$AES = [System.Security.Cryptography.AES]::Create()
$AES.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7
$AES.Mode = [System.Security.Cryptography.CipherMode]::CBC
$AES.BlockSize = 128
$AES.KeySize = 256
$AES.GenerateKey()
$AES.GenerateIV()
$Encryptor = $AES.CreateEncryptor()
$File = Get-Item -Path "C:\Myfile.exe"
$InputStream = New-Object System.IO.FileStream($File, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
$OutputStream = New-Object System.IO.FileStream((($File.FullName) + ".AES"), [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write)
$CryptoStream = New-Object System.Security.Cryptography.CryptoStream($OutputStream, $Encryptor, [System.Security.Cryptography.CryptoStreamMode]::Write)
$InputStream.CopyTo($CryptoStream)
$CryptoStream.Dispose()
$AES.Dispose()
It works. However I was wondering if this is how it's supposed to be done. Do I not need to prepend IV to the beginning of the file, or does it happen automatically with the Encryptor?
Thanks for any responses in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,使用流和
copyto
。是的,您可能应该前缀IV,不,它不会自动执行此操作。请注意,您提供机密性,但没有真实性 /完整性。不过,这可能是可以加密文件的。
您已经使用了
aes.create()
,并指示了确切的操作模式&填充,这是应该的。请注意,这不是安全审查。不考虑原始文件的破坏或用于加密可执行文件的用例。
Yes, use streams and
CopyTo
. Yes, you should probably prefix the IV, no it doesn't do this automatically.Note that you provide confidentiality, but no authenticity / integrity. This could be fine for encrypting files though.
You have used
Aes.Create()
and indicated the exact mode of operation & padding, which is as it should be.Note that this is not a security review. The destruction of the original file or the use case for encrypting an executable is not considered.