Task is to encrypt part of the file using aes encryption algorithm. I didpublic static byte[] AES_(int len, byte[] passwordBytes, byte[] saltBytes, FileStream fSin){    byte[] encryptedBytes = null;    byte[] encryptedBytesAndIV = null;    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())    {        using (AesCryptoServiceProvider AES = new AesCryptoServiceProvider())        {            AES.KeySize = 256;            AES.BlockSize = 128;            var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 100);            AES.Key = key.GetBytes(AES.KeySize / 8);            AES.IV = generateIV();            AES.Mode = CipherMode.CBC;            using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))            {                byte[] buffer = new byte[1048576];                int read,read2=0;                while (read2 < len)                {                    read = fSin.Read(buffer, 0, buffer.Length);                    cs.Write(buffer, 0, read);                    read2 += read;                }                cs.Close();            }            encryptedBytes = ms.ToArray();            encryptedBytesAndIV = new byte[encryptedBytes.Length + AES.IV.Length];            AES.IV.CopyTo(encryptedBytesAndIV, 0);            encryptedBytes.CopyTo(encryptedBytesAndIV, IV_LENGTH);        }    }    return encryptedBytesAndIV;}private static byte[] generateIV(){    using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())    {        byte[] nonce = new byte[IV_LENGTH];        rng.GetBytes(nonce);        return nonce;    }}call function  FileStream fsIn = new FileStream(path, FileMode.Open);len = Convert.ToInt32(fsIn.Length) / 3; var resultb = AES_(len, passwordBytes, saltBytes, fsIn);    fsIn.Seek(0, SeekOrigin.Begin);    fsIn.Write(resultb, 0, resultb.Length);    fsIn.Seek(fsIn.Length, SeekOrigin.Begin);    fsIn.Write(saltBytes, 0, saltBytes.Length);using (var writer = new BinaryWriter(fsIn)){    writer.Seek(Convert.ToInt32(fsIn.Length), SeekOrigin.Begin);    writer.Write(resultb.Length);}The problem is that when a large file consumes a lot of memory and the computer freezes.Is it possible to alter this code so that the memory consumption of the PC was the minimum ?As I understand it, that is the memory write bytes to the MemoryStream, but how different ? I need to overwrite the bytes in the same file if the same record byte immediately into a new file, it will have to write all the remaining bytes, and it is a waste of time and also memory
Partial file encryption with AES
c#;memory management;memory optimization;aes