加密流:读取数据错误

时间:2012-03-20 09:52:26

标签: c# .net encryption exception-handling cryptostream

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

运行时出现以下异常: “Stream不支持阅读。”

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

1 个答案:

答案 0 :(得分: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();
}