1

I have an encrypted file stored in my local machine. I decrypt the file, I get the decrypted data as a stream and I am trying to convert it to a string. Below is my code, but i always get the text as empty.

private void Decrypt(string inputFilePath, string outputfilePath)
{
   string EncryptionKey = "MAKV2SPBNI99212";
   using (Aes encryptor = Aes.Create())
   {
      Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, 
                               new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 
                               0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
      encryptor.Key = pdb.GetBytes(32);
      encryptor.IV = pdb.GetBytes(16);
      using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))
      {
         using (CryptoStream cs = new CryptoStream(fsInput, 
                            encryptor.CreateDecryptor(), CryptoStreamMode.Read))
         {
            using (Stream s = new MemoryStream())
            {
               int data;
               while ((data = cs.ReadByte()) != -1)
               {
                  s.WriteByte((byte)data);
               }
               StreamReader reader = new StreamReader(s);
               string text = reader.ReadToEnd();
            }
         }
      }
   }
}
Brandon
  • 645
  • 5
  • 13
user2480288
  • 619
  • 2
  • 11
  • 28
  • 1
    possible duplicate of [How do you get a string from a MemoryStream?](http://stackoverflow.com/questions/78181/how-do-you-get-a-string-from-a-memorystream) – andyp May 07 '14 at 20:52

2 Answers2

4

On your memorystream -- try .Flush() and Position = 0 after you write the data to it.

jtm001
  • 371
  • 2
  • 3
  • Always a good practice but I believe since both the memorystream and streamreader are both managed objects they would still be collected as expected. This is as compared to a streamreader dependent on an unmanaged handle. – jtm001 May 07 '14 at 20:57
1

Give up on the MemoryStream and just wrap the CryptoStream with a StreamReader directly. Now you dont even have to worry about position etc. Easier to code.. Less bugs.

spender
  • 117,338
  • 33
  • 229
  • 351