我正在使用.NET 4.0并尝试执行以下操作:
我尝试创建一个MemoryStream并通过以下方式将文件添加到它:
using (var memoryZip = Package.Open(_memoryStream, FileMode.Open))
{
var partUri = PackUriHelper.CreatePartUri(_fileUri);
var part = memoryZip.CreatePart(
partUri,
String.Empty,
CompressionOption.NotCompressed);
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
fileStream.CopyTo(packagePart.GetStream());
}
}
然后我尝试加密并将其保存到文件中:
_key = new DESCryptoServiceProvider
{
Key = Encoding.ASCII.GetBytes(_password);
IV = Encoding.ASCII.GetBytes(_password);
}
var fileStream = File.Open(_fileName, FileMode.Create, FileAccess.Write);
var cryptoStream = new CryptoStream(streamToFile, _key.CreateEncryptor(), CryptoStreamMode.Write);
//Convert filestream to byte[]
var streamAsBytes = new byte[(_memoryStream.Length)];
_memoryStream.Read(streamAsBytes, 0, streamAsBytes.Length);
//Encrypt
cryptoStream.Write(streamAsBytes, 0, streamAsBytes.Length);
fileStream.Close();
cryptoStream.Flush();
cryptoStream.Close();
然而,当我去解密时:
var fileStream = new FileStream(_zipFileName, FileMode.Open, FileAccess.Read);
var cryptoStream = new CryptoStream(fileStream, _key.CreateDecryptor(), CryptoStreamMode.Read);
using(var zipPackage = Package.Open(cryptoStream, FileMode.Open))
我收到FileFormatException:“文件包含损坏的数据。”
这与解密失败时获得的信息不同。我希望在加密过程中进入的流与出现的流相同,以便知道为什么包会被破坏?