I am following the MSDN Example of Rijndael Encryption, only that I would like to encrypt and return a stream.
The following does not work.
It throws no exception but after stepping through the code, the return value has no data.
public static Stream EncryptStream(Stream plainStream, byte[] Key, byte[] IV)
{
var encrypted = new MemoryStream()
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainStream);
}
msEncrypt.CopyTo(encrypted);
}
}
}
return encrypted;
}
I looked at the documentation for the Stream.Writer class, thinking that it has something to do with it not supporting writing to a Stream.
I noticed that there is an 'object' type parameter, so I am assuming it would work... Is that correct? If not, how do I do it?
I pass a FileStream to it, by the way. Stepping through the code, plainStream does contain data.