0

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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Patrick
  • 5,442
  • 9
  • 53
  • 104

1 Answers1

2

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();
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Random Dev
  • 51,810
  • 9
  • 92
  • 119
  • So this means that i have to take the data out of my stream called data into a byte array and then write that into the crypto stream to be able to access it? (Data = Stream and contains a binary serialized class) – Patrick Mar 20 '12 at 10:01
  • 1
    no - you should be able to use CopyTo (http://msdn.microsoft.com/en-us/library/dd782932.aspx) on your source-stream to copy the data into the crypto-stream – Random Dev Mar 20 '12 at 10:07