0

我得到了这个(我也试过 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 并包含一个二进制序列化类

当我运行它时出现以下异常:“流不支持阅读。”

我想要完成的只是加密来自流的数据。所以我有一个传入流,我想加密该数据并将其放入内存流中。然后将其压缩并保存到文件中。

4

1 回答 1

2

错误说明了一切:您创建了用于加密的流(= 将纯文本放入并以写入方式获取加密输出):

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

只需查看CryptoStream的 MSDN 文档- 包含一个如何正确执行此操作的示例 - 基本上就是这部分(来自 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();
}
于 2012-03-20T09:55:56.693 回答