C# 中的加密流正在缩小

Encrypted streams in C# are shrinking

我显然在这里做错了什么,但我不明白为什么会这样。我一直在我的加密流函数中遇到错误,并添加了额外的代码来向 Visual studio 的调试器显示函数中发生的事情。据我发现,我发送到其中的任何数据的加密版本都比原始流短,并且尝试解密流会导致更短的流。

        public Stream encryptStream(Stream input)
    {
        MemoryStream output = new MemoryStream();
        RijndaelManaged alg = new RijndaelManaged();
        alg.Padding = PaddingMode.PKCS7;
        byte[] key = HashStringMD5(DefaultKey);
        alg.KeySize = key.Length * 8;
        alg.Key = key;
        alg.IV = key;


        CryptoStream crypt = new CryptoStream(output, alg.CreateEncryptor(), CryptoStreamMode.Write);



        output.Position = 0;
        input.CopyTo(crypt);
        byte[] EncryptedCopy = output.ToArray();
        byte[] InputCopy = new byte[input.Length];
        input.Position = 0;
        input.Read(InputCopy, 0, InputCopy.Length);
        output.Position = 0;
        MemoryStream test = new MemoryStream();
        crypt.Close();
        crypt = new CryptoStream(test, alg.CreateDecryptor(), CryptoStreamMode.Write);
        crypt.Write(EncryptedCopy, 0, EncryptedCopy.Length);
        test.Position = 0;
        byte[] DecryptionTest = test.ToArray();


        input.Position = 0;


        return output;
    }

不确定是什么原因导致数据丢失,如下所示

您只需要在正确的时间刷新到包含流即可。此外,您有相当多的资源可以实现 IDisposable 并且可以通过使用 using 结构轻松处理。这应该会产生您正在寻找的结果以及正确确定性地处理资源:

public Stream encryptStream(Stream input)
{
    var output = new MemoryStream();

    using (var alg = new RijndaelManaged { Padding = PaddingMode.PKCS7 })
    {
        var key = HashStringMD5(DefaultKey);
        alg.KeySize = key.Length * 8;
        alg.Key = key;
        alg.IV = key;
        byte[] encryptedCopy;

        using (var enc = alg.CreateEncryptor())
        {
            var crypt = new CryptoStream(output, enc, CryptoStreamMode.Write);

            input.CopyTo(crypt);
            crypt.FlushFinalBlock();
            encryptedCopy = output.ToArray();
        }

        var inputCopy = new byte[input.Length];

        input.Position = 0;
        input.Read(inputCopy, 0, inputCopy.Length);
        using (var test = new MemoryStream())
        using (var dec = alg.CreateDecryptor())
        using (var crypt = new CryptoStream(test, dec, CryptoStreamMode.Write))
        {
            crypt.Write(encryptedCopy, 0, encryptedCopy.Length);
            crypt.FlushFinalBlock();

            var decryptionTest = test.ToArray();

            if (decryptionTest.Length != inputCopy.Length || decryptionTest.Where((t, i) => t != inputCopy[i]).Any())
            {
                throw new InvalidOperationException("not orthogonal");
            }
        }
    }

    input.Position = 0;
    output.Position = 0;
    return output;
}

虽然我可能会将测试代码拆分成一个单独的方法,因为它会增加加密代码的简单性。