VB.Net Encryption File İncrease byte array x7

i can ecnrypt files 100 mb or smaller but i transport file bytes to array memory usage increase x7 and program pass 2 gb memory limit

Example Test.rar size 100 mb

After Encryption

Program use 700 mb ram and if passed 300 mb or higher result 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
Jon Skeet
people
quotationmark

Well yes, you're reading the whole file into memory and then encrypting the whole thing in one go. You don't need to do that - you can do the whole thing in a streaming approach.

You need three streams:

  • One stream to read input from
  • One stream to write to disk
  • A crypto stream wrapping that second stream

Then just use Stream.CopyTo to copy from the input stream to the crypto stream.

In C# it would look like this:

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);
}

Hopefully you can convert that to VB easily enough.

people

See more on this question at Stackoverflow