Question

I got this (i also tried crStream.CopyTo(ms)):

 var cryptic = new DESCryptoServiceProvider();
 cryptic.Key = ASCIIEncoding.ASCII.GetBytes(passKey);
 cryptic.IV = ASCIIEncoding.ASCII.GetBytes(passKey);
 Stream crStream = new CryptoStream(data, cryptic.CreateEncryptor(), CryptoStreamMode.Write);

 Stream ms = new MemoryStream();

 var buffer = new byte[0x10000];
 int n;
 while ((n = crStream.Read(buffer, 0, buffer.Length)) != 0)  // Exception occurs here         
     ms.Write(buffer, 0, n);            
 crStream.Close();

Data = Stream and contains a binary serialized class

The following exception occurs when i run it: "Stream does not support reading."

What i am trying to accomplish is simply encrypt data from a stream. So i have an incoming stream and i want to encrypt that data and put it into the memory stream. This will then be compressed and saved to a file.

Was it helpful?

Solution

the error says everything: you create the stream for encryption (= put plain-text into and get encrypted output, in write):

Stream crStream = new CryptoStream(data, cryptic.CreateEncryptor(), CryptoStreamMode.Write);

Just have a look at the MSDN-Documentation for CryptoStream - there is a example included of how to do it right - it's basically this part (right from MSDN):

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(plainText);
    }
    encrypted = msEncrypt.ToArray();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top