我可以加密100 MB或更小的文件,但我将文件字节传输到数组内存使用量增加x7,程序传递2 GB内存限制
示例Test.rar尺寸100 mb
加密后
程序使用700 mb ram并且如果传递300 mb或更高结果SystemOutOfMemory Exception
' AesCryptoServiceProvider
Dim aes As New AesCryptoServiceProvider()
aes.BlockSize = 128
aes.KeySize = 256
aes.Key = Encoding.UTF8.GetBytes("12K2K2K2K2K2K2K212K2K2K2K2K2K2K2")
aes.IV = Encoding.UTF8.GetBytes("12K2K2K2K2K2K2K2")
aes.Mode = CipherMode.CBC
aes.Padding = PaddingMode.PKCS7
' Convert string to byte array
Dim src As Byte() = My.Computer.FileSystem.ReadAllBytes("C:\TestFolder\Test.rar")
' encryption
Using enc As ICryptoTransform = aes.CreateEncryptor()
Dim dest As Byte() = enc.TransformFinalBlock(src, 0, src.Length)
Dim ms As New MemoryStream 'Create New Memory Space
Dim cs As New CryptoStream(ms, aes.CreateEncryptor, mode:=CryptoStreamMode.Write) 'Write İn Ms
cs.Write(dest, 0, dest.Length)
cs.Close()
Dim ss() As Byte = ms.ToArray
My.Computer.FileSystem.WriteAllBytes("C:\TestFolder\TestCopy.rar", ss, True)
ms.Dispose()
cs.Dispose()
src = Nothing
ss = Nothing
dest = Nothing
答案 0 :(得分:2)
是的,你正在将整个文件读入内存,然后一次性加密整个文件。你不需要这样做 - 你可以通过流媒体方式完成整个事情。
您需要三个流:
然后只需使用Stream.CopyTo
从输入流复制到加密流。
在C#中,它看起来像这样:
using (var input = File.OpenRead(@"C:\TestFolder\Test.rar"))
using (var output = File.Create(@"C:\TestFolder\Test.rar.encrypted"))
using (var crypto = New CryptoStream(output, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
input.CopyTo(crypto);
}
希望你能够轻松地将它转换为VB。