CryptoStream:要解密的数据长度无效。相同的代码不会在相同的数据上生成错误

时间:2012-02-16 17:02:21

标签: c# encryption des

好的,这很奇怪,对我来说。我有这个代码,它有效:

using (MemoryStream memStream = new MemoryStream(inBytes))
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
using (CryptoStream cs = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
{
    byte[] buffer;
    if (inBytes.Length < (1024 * 10)) buffer = new byte[inBytes.Length];
    else buffer = new byte[(1024 * 10)];
    long readBytes = 0;
    long totalBytes = inStream.Length;
    int currBytes;

    while (readBytes < totalBytes)
    {
        currBytes = cs.Read(buffer, 0, buffer.Length);
        fs.Write(buffer, 0, currBytes);
        readBytes += currBytes;
    }
}

这会将解密数据写入文件。

然后我有这个代码执行完全相同的事情,除了它写入(并返回)MemoryStream

using(MemoryStream memStream = new MemoryStream(inBytes))
using(MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
{
    byte[] buffer;
    if (inBytes.Length < (1024 * 10)) buffer = new byte[inBytes.Length];
    else buffer = new byte[(1024 * 10)];
    long readBytes = 0;
    long totalBytes = inStream.Length;
    int currBytes;

    while (readBytes < totalBytes)
    {
        currBytes = cs.Read(buffer, 0, buffer.Length);
        ms.Write(buffer, 0, currBytes);
        readBytes += currBytes;
    }

    return ms;
}

currBytes = cs.Read(buffer, 0, buffer.Length)行上,我收到错误“要解密的数据长度无效”但仅在第二组而不是第一组。 ICryptoTransform“解密器”是从一种常用方法创建的,我知道它使用相同的密钥。

任何人都可以告诉我为什么我不会在第一个实例中收到此错误,但会在第二个实例中,并且(更重要的是)如何修复它。

而且,是的,我知道DES不是有史以来最好的加密方法。这是概念验证的本质,在生产环境中永远不会看到光明。

2 个答案:

答案 0 :(得分:1)

我今天遇到了这个错误,事实证明我在一个函数中使用ASCII将一个源字符串转换为字节数组,而在另一个函数中使用Base64将其转换为字节数组。

虽然您的输入长度正确,但它们可能没有使用相同的编码。

答案 1 :(得分:0)

尝试将这些检查添加到两段代码中。我强烈怀疑其中一个或两个都失败了:

if ( inStream.Length != inBytes.Length )
  throw new Exception("inBytes read incorrectly");
if ( inBytes.Length % 8 == 0 )
  throw new Exception("inBytes is not a valid DES encryption");