Using StreamWriter to write in a Stream (for large Stream encryption)
See the question and my original answer on StackOverflowHere are some sample function to encrypt and decrypt from and to streams (replace the algo by the one you prefer):
public static void Decrypt(Stream input, Stream output, byte[] key, byte[] iv)
{
using (SymmetricAlgorithm algo = SymmetricAlgorithm.Create()) // Creates the default implementation, which is RijndaelManaged.
{
using (CryptoStream stream = new CryptoStream(input, algo.CreateDecryptor(key, iv), CryptoStreamMode.Read))
{
byte[] bytes = new byte[16];
int read;
do
{
read = stream.Read(bytes, 0, bytes.Length);
output.Write(bytes, 0, read);
}
while (read > 0);
}
}
}
public static void Encrypt(Stream input, Stream output, byte[] key, byte[] iv)
{
using (SymmetricAlgorithm algo = SymmetricAlgorithm.Create()) //Creates the default implementation, which is RijndaelManaged.
{
using (CryptoStream stream = new CryptoStream(output, algo.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
byte[] bytes = new byte[16];
int read;
do
{
read = input.Read(bytes, 0, bytes.Length);
stream.Write(bytes, 0, read);
}
while (read > 0);
}
}
}
You can use them with any output stream. If you want to write to a large output stream, you can use that output stream directly (for example a FileStream or ASP.NET Response.OutputStream, etc.), you should not use an intermediary MemoryStream which will consume memory for no real purpose.
That being said, if you really want to use a MemoryStream, you would do it like this:
MemoryStream output = new MemoryStream();
Encrypt(input, output, key, iv);
output.Position = 0; // rewind the stream, so you can use it from the beginning