将流转换为字符串

时间:2014-05-07 20:48:19

标签: c# wpf encryption stream

我的本​​地计算机中存有加密文件。我解密文件,我将解密数据作为流,我试图将其转换为字符串。下面是我的代码,但我总是将文本视为空。

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();
            }
         }
      }
   }
}

2 个答案:

答案 0 :(得分:4)

在内存流上 - 在向其写入数据后尝试.Flush()和Position = 0.

答案 1 :(得分:1)

放弃MemoryStream,直接用StreamReader包装CryptoStream。现在你甚至不必担心位置等。更容易编码..减少错误。