title: Encrypt and Decrypt C# Rijndael Managed out of memory
body: <p>I am currently programing a little software like WinRAR. When I encrypt or decrypt a array of bytes corresponding to my file, I have a large memory leak (or a high RAM consumption) and sometimes when I want to encrypt a file of 500MB it throws an <code>OutOfMemoryException</code>.</p>
  
  <p>There is my code:</p>
  
  <pre><code>internal static class ResourceSecurity
  {
      #region STATIC FIELDS
  
      private static readonly String PASSWORD_HASH = "ceýº–h­Þ6Ü+rdÚ‡AÃÎ^oð#Èh";
  
      private static readonly String SALT_KEY = "žÀÚÔceýº–h­•e:÷KÚ‡AÃÎ^oð#ÈhÀÍÄ";
  
      private static readonly String IV_KEY = "ª&lt;±kéÞ6Ü+\f¥Ÿ„’²";
  
      #endregion
  
      #region STATIC METHODS
  
      private static RijndaelManaged CreateAlgo()
      {
          Byte[] _keyBytes = new Rfc2898DeriveBytes(PASSWORD_HASH, Encoding.ASCII.GetBytes(SALT_KEY)).GetBytes(256 / 8);
          RijndaelManaged _rijndael = new RijndaelManaged();
  
          _rijndael.Mode = CipherMode.CBC;
          _rijndael.Padding = PaddingMode.Zeros;
          _rijndael.Key = _keyBytes;
          _rijndael.IV = Encoding.ASCII.GetBytes(IV_KEY);
  
          return _rijndael;
      }
  
  
      private static Byte[] ConvertBuffer(Byte[] buffer, ICryptoTransform transformation)
      {
          Byte[] _newBuffer = null;
          MemoryStream _memoryStream = new MemoryStream();
  
          using (CryptoStream _crypto = new CryptoStream(_memoryStream, transformation, CryptoStreamMode.Write))
          {
              _crypto.Write(buffer, 0, buffer.Length);
              _newBuffer = _memoryStream.ToArray();
          }
  
          return _newBuffer;
      }
  
      internal static Byte[] Encrypt(Byte[] bufferToEncrypt)
      {
          return ConvertBuffer(bufferToEncrypt, CreateAlgo().CreateEncryptor());
      }
  
      internal static Byte[] Decrypt(Byte[] encryptedBuffer)
      {
          return ConvertBuffer(encryptedBuffer, CreateAlgo().CreateDecryptor());
      }
  
      #endregion
  }
  </code></pre>
  
  <p>Thank you!</p>