我正在尝试将内存流复制到文件流中。我注意到解密时输出exe已损坏。我确信解密功能没有问题。这是代码
private MemoryStream My_Encrypt(Stream inputFile)
{
//FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
MemoryStream fsCrypt = new MemoryStream();
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);
int data;
while ((data = inputFile.ReadByte()) != -1)
cs.WriteByte((byte)data);
inputFile.Flush();
return fsCrypt;
}
MemoryStream ms = My_Encrypt(bundleStream);
ms.Seek(0, SeekOrigin.Begin);
FileStream atest = new FileStream("c:\\Somefile.exe",FileMode.Create);
ms.Seek(0, SeekOrigin.Begin);
ms.CopyTo(atest);
atest.Close();
更多详情:
我说内存流方法不起作用的原因是因为在My_Encrypt
方法中,如果我用FileStream而不是Memory Stream替换fsCrypt并在方法结束时关闭fsCrypt然后重新打开保存的文件并写入到它的另一个文件。我的问题是为什么内存流方法不起作用。
答案 0 :(得分:2)
我相信你必须在CryptoStream上调用FlushFinalBlock。
private MemoryStream My_Encrypt(Stream inputFile)
{
//FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
MemoryStream fsCrypt = new MemoryStream();
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);
int data;
while ((data = inputFile.ReadByte()) != -1)
cs.WriteByte((byte)data);
cs.FlushFinalBlock();
return fsCrypt;
}