Encrypt and decrypt a MemoryStream
<p>I need to crypt and later decrypt a MemoryStream (original large PDF file). I tried the following code:</p>

<pre><code>    public static string GenerateKey()
    {
        var desCrypto = (DESCryptoServiceProvider)DES.Create();

        return Encoding.ASCII.GetString(desCrypto.Key);
    }

    public static MemoryStream Encrypt(Stream fsInput,string sKey)
    {
        var fsEncrypted=new MemoryStream();

        var des = new DESCryptoServiceProvider
        {
            Key = Encoding.ASCII.GetBytes(sKey),
            IV = Encoding.ASCII.GetBytes(sKey)
        };
        var desencrypt = des.CreateEncryptor();
        var cryptostream = new CryptoStream(fsEncrypted,desencrypt,CryptoStreamMode.Write);

        var bytearrayinput = new byte[fsInput.Length];
        fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
        cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
        fsInput.Close();

        fsEncrypted.Flush();
        fsEncrypted.Position = 0;
        return fsEncrypted;
    }

    public static MemoryStream Decrypt(Stream fsread,string sKey)
    {
        var des = new DESCryptoServiceProvider
        {
            Key = Encoding.ASCII.GetBytes(sKey),
            IV = Encoding.ASCII.GetBytes(sKey)
        };

        var sOutputFilename = new MemoryStream();
        var desdecrypt = des.CreateDecryptor();
        var cryptostreamDecr = new CryptoStream(fsread,desdecrypt,CryptoStreamMode.Read);

        var fsDecrypted = new StreamWriter(sOutputFilename);
        fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
        fsDecrypted.Flush();
        fsDecrypted.Close();
        sOutputFilename.Position = 0;

        return sOutputFilename;
    }
</code></pre>

<p>Call example:</p>

<pre><code>    var sSecretKey = FileHelper.GenerateKey();
    var encyptedPdfContent = FileHelper.Encrypt(httpPostedFile.InputStream, sSecretKey);

    var decryptedPdfContent = FileHelper.Decrypt(encyptedPdfContent, sSecretKey);
</code></pre>

<p>Encrypt seems to work as expected but when I try to decrypt</p>

<pre><code>fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
</code></pre>

<p>returns me <code>Bad Data</code> Exception.</p>

<p>What's wrong in my code?</p>

<p>I saw other posts and all of them are related to the string encoding (Encoding.Unicode). I don't have a string. I have a memorystream that is not encoded at all!</p>