我显然在这里做错了,但我不明白为什么会这样。我一直在验证我的加密流功能中的错误,并添加了额外的代码,以显示给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;
}
答案 0 :(得分:1)
您只需要在合适的时间刷新包含的流。此外,您有相当多的资源实现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;
}
虽然我可能会将测试代码拆分为单独的方法,因为它会增加加密代码的简单性。