I'm compressing and then encrypting a file. Not problem with this. Problems come when I try to decrypt the file and finally, I try to decompress the decrypted file. In that moment, I get an exception in ReadEndOfCentralDirectory
: (Updated)
Offset to Central Directory cannot be held in an Int64.
en System.IO.Compression.ZipArchive.ReadEndOfCentralDirectory()
en System.IO.Compression.ZipArchive.Init(Stream stream, ZipArchiveMode mode, Boolean leaveOpen)
en System.IO.Compression.ZipArchive..ctor(Stream stream, ZipArchiveMode mode, Boolean leaveOpen, Encoding entryNameEncoding)
en System.IO.Compression.ZipFile.Open(String archiveFileName, ZipArchiveMode mode, Encoding entryNameEncoding)
en System.IO.Compression.ZipFile.ExtractToDirectory(String sourceArchiveFileName, String destinationDirectoryName, Encoding entryNameEncoding)
en System.IO.Compression.ZipFile.ExtractToDirectory(String sourceArchiveFileName, String destinationDirectoryName)`
For zip the folder I'm using this
ZipFile.CreateFromDirectory(sourcePath, pathZipFile, CompressionLevel.Fastest, false);
For encrypt:
RijndaelManaged key = new RijndaelManaged();
key.KeySize = 256;
key.BlockSize = 256;
key.Padding = System.Security.Cryptography.PaddingMode.ISO10126;
key.Key = Convert.FromBase64String(aes);
key.IV = Convert.FromBase64String(aes);
ICryptoTransform encryptor = key.CreateEncryptor();
using (FileStream InputFile = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
using (FileStream OutputFile = new FileStream(targetPath, FileMode.Create, FileAccess.Write))
{
using (CryptoStream csEncrypt = new CryptoStream(OutputFile, encryptor, CryptoStreamMode.Write))
{
long total = InputFile.Length;
var buffer = new byte[total];
var read = InputFile.Read(buffer, 0, buffer.Length);
csEncrypt.Write(buffer, 0, read);
}
}
For decrypt:
RijndaelManaged key = new RijndaelManaged();
key.KeySize = 256;
key.BlockSize = 256;
key.Padding = System.Security.Cryptography.PaddingMode.ISO10126;
key.Key = Convert.FromBase64String(aes);
key.IV = Convert.FromBase64String(aes);
ICryptoTransform cryptor = key.CreateDecryptor();
using (FileStream InputFile = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
{
CryptoStream csEncrypt = new CryptoStream(InputFile, cryptor, CryptoStreamMode.Read);
StreamWriter fsDecrypted = new StreamWriter(targetPath);
fsDecrypted.Write(new StreamReader(csEncrypt).ReadToEnd());
fsDecrypted.Close();
}
For unzip:
ZipFile.ExtractToDirectory(zipPath, extractPath);
If I change the whole process and first of all I encrypt file, then compress it, I can decompress it and finally decrypt it without problems. Could be the issue in the encryption/decryption phase (maybe related to encoding, bytes or similar...)? Thanks in advance.
StreamWriter
you're writing text. You should write bytes. The conversion is not lossless. Use FileStream
.