【问题标题】:Converting stream to string将流转换为字符串
【发布时间】:2014-06-25 00:57:36
【问题描述】:

我的本​​地计算机中存储了一个加密文件。我解密文件,将解密的数据作为流获取,并尝试将其转换为字符串。以下是我的代码,但我总是将文本设为空。

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

【问题讨论】:

标签: c# wpf encryption stream


【解决方案1】:

在您的内存流上 -- 将数据写入其中后尝试 .Flush() 和 Position = 0。

【讨论】:

  • 始终是一个很好的做法,但我相信由于 memorystream 和 streamreader 都是托管对象,它们仍会按预期收集。这与依赖于非托管句柄的流读取器相比。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2018-01-03
    • 2015-11-18
    • 1970-01-01
    • 2014-11-15
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多