【问题标题】:'Stream does not support seeking' with CryptoStream object“流不支持搜索”与 CryptoStream 对象
【发布时间】:2009-10-26 16:03:51
【问题描述】:

我正在尝试使用以下代码加密一些数据:

public static byte[] EncryptString(byte[] input, string password)
{
    PasswordDeriveBytes pderiver = new PasswordDeriveBytes(password, null);
    byte[] ivZeros = new byte[8];
    byte[] pbeKey = pderiver.CryptDeriveKey("RC2", "MD5", 128, ivZeros);

    RC2CryptoServiceProvider RC2 = new RC2CryptoServiceProvider();

    byte[] IV = new byte[8];
    ICryptoTransform encryptor = RC2.CreateEncryptor(pbeKey, IV);

    MemoryStream msEncrypt = new MemoryStream();
    CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
    csEncrypt.Write(input, 0, input.Length);
    csEncrypt.FlushFinalBlock();

    return msEncrypt.ToArray();
}

但是,当它初始化我的 CryptoStream 对象时,它会引发以下错误:

“流不支持搜索。” 为了澄清,上面的代码中没有错误处理,所以只是运行它不会“破坏”,persay。但单步执行代码时,CryptoStream 对象在初始化后将在其属性中显示此错误。

这是为什么?我该如何避免呢?

【问题讨论】:

  • 因为这个流不支持搜索。为什么要避免它?只要你不使用 Seek,一切都应该没问题。

标签: c# encryption cryptography


【解决方案1】:

所以代码实际上运行时没有异常,但问题是当您在调试器中查看属性时?如果是这样,那很容易 - 某些属性(例如Position)依赖于能够在流中查找。 CryptoStream 无法做到这一点 - 因此属性评估失败。

您无需避免这种情况 - 完全没问题。

【讨论】:

  • 所以发生异常的原因仅仅是因为尝试查看 Position 属性在流上无效,所以它只是向我确认我无法查看?
【解决方案2】:

您可以使用 MemoryStream 上的构造函数之一,将“true”传递给可写参数吗?

【讨论】:

  • 我可以通过这个仍然有效的构造函数推送什么字节数组?
  • 我相信 MD5 散列到 16 个字节。
【解决方案3】:

为了避免这个问题,它更容易使用:

    using (var reader = new StreamReader(csEncrypt))
    {
        return reader.ReadToEnd();
    }

【讨论】:

  • 抛出CryptographicException : Padding is invalid and cannot be removed.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-11
  • 2015-05-29
  • 1970-01-01
  • 2014-04-23
  • 2019-11-12
  • 2017-09-20
  • 1970-01-01
相关资源
最近更新 更多