The Length of Data is invalid while decrypting a txt file - c#

I made a console app to decrypt a file . Please refer to the screenshot for detail error message.
If you copy paste the code in a console app . You should be able to debug .
1) Need to make folder SourceFolder\Newfolder\ and a new txt file destination.txt
2) Need to make folder for C:\DestinationFolder\source.txt(encrypted file cannot attach file here i hope you can make one
using System;
using System.IO;
using System.Security.Cryptography;
namespace ConsoleApp5
{
class Program
{
//SALT is a random data that is used as addition to a password to encrypt data
// The primary function is to protect against lists of often used password
private static readonly byte[] SALT = new byte[] {0x26,0xdc,0xff,0x76,0x76,
0xad,0xed,0x7a,0x64,0xc5,0xfe
,0x20,0xaf,0x4d,0x08,0x3c};
static void Main(string[] args)
{
//Need to make a SourceFolder and but the file in there abc.txt
string path = #"C:\SourceFolder\New folder\";
string[] txtFile = Directory.GetFiles(path, "*.txt");
string fileinnn = txtFile[0];
//Get the filepath of the decrypted file. Need to make this folder and add a new file that is what i am donig for now for this cosole app
string filepathDecrypted = #"C:\DestinationFolder\destination.txt"; //this is a new file need to create
//Get the password
string encrytionKey = "password.";
Decrypt(fileinnn, filepathDecrypted, encrytionKey);
}
public static void Decrypt(string fileIn, string fileOut, string Password)
{
//open filestreat for encrypted source file
using (System.IO.FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read))
{
using (System.IO.FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write))
{
try
{
//Create Key and IV from the password with the SALT
Rfc2898DeriveBytes pdf = new Rfc2898DeriveBytes(Password, SALT);
//Create a symmetric algorithm with Rijndael
Rijndael alg = Rijndael.Create();
alg.Padding = PaddingMode.PKCS7;
//alg.BlockSize = 128;
//SET key and IV
alg.Key = pdf.GetBytes(32);
alg.IV = pdf.GetBytes(16);
//Create a cryptoStream
using (CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(), CryptoStreamMode.Write))
{
//Intialize the buffer and process the input in chunks
// this is done to avoid reading the whole file which is huge and memory consumption.
int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int bytesRead;
do
{ //read a chunck of data from the input file
bytesRead = fsIn.Read(buffer, 0, bufferLen);
//Decrypt it
cs.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);
//close everything
cs.Close(); //this is where it throws exception
fsOut.Close();
fsIn.Close();
}
}
catch (Exception ex)
{
var error = ex.Message;
throw;
}
}
}
}
}
}
Error message that i am getting

Related

Decryption using CryptoStream returns an empty file

I'm trying to use AES to see how encryption/decryption works. Encrypting files works fine with the following code:
(These methods are in two separate files)
private void tempEncrypt()
{
// Creates file with "Test String" inside
byte[] test = Encoding.ASCII.GetBytes("Test String");
var file = File.Create("test.txt");
file.Write(test, 0, test.Length);
// Saves key and IV for decryption
var temp = new AesCryptoServiceProvider();
Console.WriteLine(System.Convert.ToBase64String(temp.Key));
Console.WriteLine(System.Convert.ToBase64String(temp.IV));
Encryptor.Encrypt(file, temp.Key, temp.IV);
}
public static void Encrypt(FileStream source, byte[] key, byte[] IV)
{
// Creates a temp file for encrypting
var destination = File.Create("encrypted.tmp");
string path = source.Name;
using (var provider = new AesCryptoServiceProvider())
using (var transform = provider.CreateEncryptor(key, IV))
using (var cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
{
// Encrypts file
source.CopyTo(cryptoStream);
source.Close();
// Deletes unencrypted file
File.Delete(path);
}
// Replaces source file with encrypted file
destination.Close();
File.Move(destination.Name, path);
File.Delete(destination.Name);
}
But when I use this to decrypt the file, the file will be empty:
private void tempDecrypt()
{
// Opens encrypted file
var file = File.OpenRead("test.txt");
var temp = new AesCryptoServiceProvider();
temp.Key = System.Convert.FromBase64String("SANeQe1MK4UKrQmJ4fa16lrhIexK7gaxqE/N/HycdhI=");
temp.IV = System.Convert.FromBase64String("Pb2SciISBP2p0hWzEUG05A==");
Encryptor.Decrypt(file, temp.Key, temp.IV);
}
public static void Decrypt(FileStream source, byte[] key, byte[] IV)
{
// Creates a temp file for decrypting
var destination = File.Create("decrypted.tmp");
string path = source.Name;
Console.WriteLine(source.Length);
// Decrypts rest of file
using (var provider = new AesCryptoServiceProvider())
using (var transform = provider.CreateDecryptor(key, IV))
using (var cryptoStream = new CryptoStream(source, transform, CryptoStreamMode.Read))
{
// Decrypts file
cryptoStream.CopyTo(destination);
}
// Replaces source file with decrypted file
destination.Close();
source.Close();
File.Delete(path);
File.Move(destination.Name, path);
File.Delete(destination.Name);
}
Replacing the file doesn't seem to be the problem because even "decrypted.tmp" is empty before I replace the destination file with the source one.
In the tempEncrypt() method, I had to close the file then re-open using File.OpenRead() for it to decrypt properly. I guess test.txt was still empty even though I used file.Write() to write to the file. Here is the working method:
private void tempEncrypt()
{
// Creates file with "Test String" inside
byte[] test = Encoding.ASCII.GetBytes("Test String");
var file = File.Create("test.txt");
file.Write(test, 0, test.Length);
file.Close();
var newFile = File.OpenRead("test.txt");
// Saves key and IV for decryption
var temp = new AesCryptoServiceProvider();
Console.WriteLine(System.Convert.ToBase64String(temp.Key));
Console.WriteLine(System.Convert.ToBase64String(temp.IV));
Encryptor.Encrypt(newFile, temp.Key, temp.IV);
}

Encrypt and decrypt a file with aes in c#?

I wanted to know if there is a code that encrypts and decrypts a file using AES in C#?I have seen some code about encrypting and decrypting a text in c# using aes but
encrypting and decrypting a file in c# ..there was no full code to understand it well..If somebody can help me please?
In general, you don't want to encrypt a file. That is, you don't want to write a file, then encrypt it. The data is probably in a different sector of the storage device, and can likely be recovered. (Of course, if you're trying to write ransomware, by all means write it poorly). What you want to do instead is encrypt contents before they make it to disk.
What you asked for
public static void EncryptFile(string filePath, byte[] key)
{
string tempFileName = Path.GetTempFileName();
using (SymmetricAlgorithm cipher = Aes.Create())
using (FileStream fileStream = File.OpenRead(filePath))
using (FileStream tempFile = File.Create(tempFileName))
{
cipher.Key = key;
// aes.IV will be automatically populated with a secure random value
byte[] iv = cipher.IV;
// Write a marker header so we can identify how to read this file in the future
tempFile.WriteByte(69);
tempFile.WriteByte(74);
tempFile.WriteByte(66);
tempFile.WriteByte(65);
tempFile.WriteByte(69);
tempFile.WriteByte(83);
tempFile.Write(iv, 0, iv.Length);
using (var cryptoStream =
new CryptoStream(tempFile, cipher.CreateEncryptor(), CryptoStreamMode.Write))
{
fileStream.CopyTo(cryptoStream);
}
}
File.Delete(filePath);
File.Move(tempFileName, filePath);
}
public static void DecryptFile(string filePath, byte[] key)
{
string tempFileName = Path.GetTempFileName();
using (SymmetricAlgorithm cipher = Aes.Create())
using (FileStream fileStream = File.OpenRead(filePath))
using (FileStream tempFile = File.Create(tempFileName))
{
cipher.Key = key;
byte[] iv = new byte[cipher.BlockSize / 8];
byte[] headerBytes = new byte[6];
int remain = headerBytes.Length;
while (remain != 0)
{
int read = fileStream.Read(headerBytes, headerBytes.Length - remain, remain);
if (read == 0)
{
throw new EndOfStreamException();
}
remain -= read;
}
if (headerBytes[0] != 69 ||
headerBytes[1] != 74 ||
headerBytes[2] != 66 ||
headerBytes[3] != 65 ||
headerBytes[4] != 69 ||
headerBytes[5] != 83)
{
throw new InvalidOperationException();
}
remain = iv.Length;
while (remain != 0)
{
int read = fileStream.Read(iv, iv.Length - remain, remain);
if (read == 0)
{
throw new EndOfStreamException();
}
remain -= read;
}
cipher.IV = iv;
using (var cryptoStream =
new CryptoStream(tempFile, cipher.CreateDecryptor(), CryptoStreamMode.Write))
{
fileStream.CopyTo(cryptoStream);
}
}
File.Delete(filePath);
File.Move(tempFileName, filePath);
}
What you really want
Instead of writing the original file via a FileStream, open the file, write the header and IV, create the CryptoStream, and use the CryptoStream for everything. There's no reason to ever let the unencrypted form be on disk.

C# DES File Decryption Breaking Non-Text Files

I have these two methods which are pretty much copy+pastes from http://support.microsoft.com/kb/307010.
When I decrypt the files, if they are any type of text file such as .txt, .xml, .html, etc. I can open them up and everything is fine. Any type of file not just text, such as .exe, .jpg, .pdf, etc. all break when decrypted. Is there anything I am doing wrong? Are these methods using binary to encrypt/decrypt the files? If not is there a way I can make it binary?
Any help is greatly appreciated!
public static void EncryptFile(string sInputFilename,
string sOutputFilename,
string sKey)
{
FileStream fsInput = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.Read);
FileStream fsEncrypted = new FileStream(sOutputFilename,
FileMode.Create,
FileAccess.Write);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsEncrypted,
desencrypt,
CryptoStreamMode.Write);
byte[] bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fsInput.Close();
fsEncrypted.Close();
}
public static void DecryptFile(string sInputFilename,
string sOutputFilename,
string sKey)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
//A 64 bit key and IV is required for this provider.
//Set secret key For DES algorithm.
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
//Set initialization vector.
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
//Create a file stream to read the encrypted file back.
FileStream fsread = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.Read);
//Create a DES decryptor from the DES instance.
ICryptoTransform desdecrypt = DES.CreateDecryptor();
//Create crypto stream set to read and do a
//DES decryption transform on incoming bytes.
CryptoStream cryptostreamDecr = new CryptoStream(fsread,
desdecrypt,
CryptoStreamMode.Read);
//Print the contents of the decrypted file.
StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
fsread.Close();
cryptostreamDecr.Close();
}
I don't know what the guy that wrote that article was smoking, but:
DESCryptoServiceProvider desCrypto =
(DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
will not get you a valid key. At least one problem is the fact that the key you use to encrypt is not the same key that you're using to decrypt, because you can't convert bytes to ASCII and back like that.
If you want to treat the key as a string, what you probably want is:
string keyAsString = Convert.ToBase64String(desCrypto.Key);
Then when you want to turn it back into bytes, instead of ASCIIEncoding.ASCII.GetBytes, you'll do:
byte[] key = Convert.FromBase64String(keyAsString);
EDIT
There's a ton more wrong with that article too. I'd say ignore that one and find a better example.
EDIT
Here's a very clean basic AES working example that I use for my standard encryption needs. Some of the major improvements over the article are:
Proper creation of a key
Current algorithm (AES 256-bit key)
Random IV
Buffered file access instead of reading/writing the entire file in one chunk
Wrapping all the disposable objects in using
Aside from that, it's the same basic idea.
using System;
using System.IO;
using System.Security.Cryptography;
namespace ConsoleApplication12
{
class Program
{
private const int KEY_SIZE_BYTES = 32;
private const int IV_SIZE_BYTES = 16;
static void Main(string[] args)
{
var rand = new Random();
using (var fs = File.Open(#"C:\temp\input.bin", FileMode.Create, FileAccess.Write, FileShare.None))
{
byte[] buffer = new byte[10000];
for (int i = 0; i < 100; ++i)
{
rand.NextBytes(buffer);
fs.Write(buffer, 0, buffer.Length);
}
}
string key = GenerateRandomKey();
Encrypt(#"C:\temp\input.bin", #"C:\temp\encrypted.bin", key);
Decrypt(#"C:\temp\encrypted.bin", #"C:\temp\decyrypted.bin", key);
}
static string GenerateRandomKey()
{
byte[] key = new byte[KEY_SIZE_BYTES];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(key);
}
return Convert.ToBase64String(key);
}
static void Encrypt(string inputFile, string outputFile, string key)
{
const int BUFFER_SIZE = 8192;
byte[] buffer = new byte[BUFFER_SIZE];
byte[] keyBytes = Convert.FromBase64String(key);
byte[] ivBytes = new byte[IV_SIZE_BYTES];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(ivBytes);
}
using (var inputStream = File.Open(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var outputStream = File.Open(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
outputStream.Write(ivBytes, 0, ivBytes.Length);
using (var cryptoAlgo = Aes.Create())
{
using (var encryptor = cryptoAlgo.CreateEncryptor(keyBytes, ivBytes))
{
using (var cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write))
{
int count;
while ((count = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
cryptoStream.Write(buffer, 0, count);
}
}
}
}
}
}
}
static void Decrypt(string inputFile, string outputFile, string key)
{
const int BUFFER_SIZE = 8192;
byte[] buffer = new byte[BUFFER_SIZE];
byte[] keyBytes = Convert.FromBase64String(key);
byte[] ivBytes = new byte[IV_SIZE_BYTES];
using (var inputStream = File.Open(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
inputStream.Read(ivBytes, 0, ivBytes.Length);
using (var outputStream = File.Open(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (var cryptoAlgo = Aes.Create())
{
using (var decryptor = cryptoAlgo.CreateDecryptor(keyBytes, ivBytes))
{
using (var cryptoStream = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read))
{
int count;
while ((count = cryptoStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, count);
}
}
}
}
}
}
}
}
}
Because the IV is random, you'll see another small difference in technique. When encrypting the file, you first write the IV to the encrypted file (it's not a secret, so you just write it straight out). When decrypting the file, you read the first few bytes to retrieve the IV, then the rest of the file contains the actual encrypted data. The purpose of a random IV is so the same plaintext file will encrypt into a different encrypted file every time you run it.
The Main method here demonstrates encryption with a random key. If you want to use a password, it's a little more work, but you can implement PBKDF2 with maybe a dozen or so extra lines of code.

Encryption/ Decryption

I want to decrypt an already encrypted file but getting the error "Bad Data". I think that that the method I used here to generate key is not generating same key while encrypting and decrypting. So, I want to declare my own key. How can i do this?
This is my code.
using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
public static class crypto
{
public static String tempdir = Environment.ExpandEnvironmentVariables("%temp%");
// Call this function to remove the key from memory after use for security
[System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
public static extern bool ZeroMemory(IntPtr Destination, int Length);
// Function to Generate a 64 bits Key.
static string GenerateKey()
{
// Create an instance of Symetric Algorithm. Key and IV is generated automatically.
DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
Clipboard.SetText(desCrypto.Key.ToString());
// Use the Automatically generated key for Encryption.
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}
static void EncryptFile(string sInputFilename,
string sOutputFilename,
string sKey)
{
FileStream fsInput = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.Read);
FileStream fsEncrypted = new FileStream(sOutputFilename,
FileMode.Create,
FileAccess.Write);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsEncrypted,
desencrypt,
CryptoStreamMode.Write);
byte[] bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fsInput.Close();
fsEncrypted.Close();
}
static void DecryptFile(string sInputFilename,
string sOutputFilename,
string sKey)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
//A 64 bit key and IV is required for this provider.
//Set secret key For DES algorithm.
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
//Set initialization vector.
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
//Create a file stream to read the encrypted file back.
FileStream fsread = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.Read);
//Create a DES decryptor from the DES instance.
ICryptoTransform desdecrypt = DES.CreateDecryptor();
//Create crypto stream set to read and do a
//DES decryption transform on incoming bytes.
CryptoStream cryptostreamDecr = new CryptoStream(fsread,
desdecrypt,
CryptoStreamMode.Read);
//Print the contents of the decrypted file.
StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
}
public static void Encrypt(String table, String file)
{
GenerateKey();
try
{
String filepath = Path.Combine(tempdir + #"\Manager\data\" + table,file);
// Must be 64 bits, 8 bytes.
// Distribute this key to the user who will decrypt this file.
string sSecretKey;
// Get the Key for the file to Encrypt.
sSecretKey = GenerateKey();
// For additional security Pin the key.
GCHandle gch = GCHandle.Alloc(sSecretKey, GCHandleType.Pinned);
// Encrypt the file.
EncryptFile(#"" + filepath,
#"" + Application.StartupPath + #"\data\"+ table + #"\" + file,
sSecretKey);
try
{
File.Delete(filepath);
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message, "Error while deletion of decrypted file");
}
// Remove the Key from memory.
ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2);
gch.Free();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error during encryption");
}
}
public static void Decrypt(String table, String file)
{
try
{
String filepath = Path.Combine(tempdir + #"\Manager\data\"+table, file);
create.folder("Manager", tempdir);
create.folder(table, tempdir + #"\Manager\");
create.file(file, tempdir + #"\Manager\" + table);
// Must be 64 bits, 8 bytes.
// Distribute this key to the user who will decrypt this file.
string sSecretKey;
// Get the Key for the file to Encrypt.
sSecretKey = GenerateKey();
// For additional security Pin the key.
GCHandle gch = GCHandle.Alloc(sSecretKey, GCHandleType.Pinned);
// Decrypt the file.
DecryptFile(#".\data\" + table + #"\" + file,
#"" + filepath,
sSecretKey);
// Remove the Key from memory.
ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2);
gch.Free();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error during decryption");
}
}
}
Your GenerateKey Method generates a new (random) key every time you call it (like you already stated in the comments there). If you want to use a random key, store the generated key somewhere and use it for decryption and encryption.
You can use a own "password" for encryption by giving your encryption/decryption method a own string value. e.g.
crypto.EncryptFile(#"D:\Testing\brownfox.txt", #"D:\Testing\brownfox_enc.txt", "abcd1234");
crypto.DecryptFile(#"D:\Testing\brownfox_enc.txt", #"D:\Testing\brownfox_dec.txt", "abcd1234");
As you can see in the MSDN reference to "DES.Key", DES supports keys with a length of 64bit, so it's important to note, that the string must have 8 characters.

How to create a encrypted zip file can be decompressed by winzip/7zip

I've used AESManaged Class to encrypt a zip file, but it couldn't be decompressed by winzip/7zip. I can only decompress it after decrypting in my code.
Below is the code I used to encrypt and decrypt. Anyone can help?
private static void EncryptFile(string input, string output, string pwd)
{
using (AesManaged aes = new AesManaged())
{
FileStream fsCrypt=null;
try
{
byte[] key = Encoding.UTF8.GetBytes(pwd);
fsCrypt = new FileStream(output, FileMode.Create);
using (CryptoStream cs = new CryptoStream(fsCrypt, aes.CreateEncryptor(key, key), CryptoStreamMode.Write))
{
using (FileStream fsIn = new FileStream(input, FileMode.Open))
{
int data;
while ((data = fsIn.ReadByte()) != -1)
{
cs.WriteByte((byte)data);
}
aes.Clear();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
aes.Clear();
}
finally
{
if(fsCrypt!=null)
{
fsCrypt.Dispose();
}
}
}
}
private static void DecryptFile(string input, string output, string pwd)
{
using (AesManaged aes = new AesManaged())
{
FileStream fsCrypt = null;
try
{
byte[] key = Encoding.UTF8.GetBytes(pwd);
fsCrypt = new FileStream(input, FileMode.Open);
{
using (FileStream fsOut = new FileStream(output, FileMode.Create))
{
using (CryptoStream cs = new CryptoStream(fsCrypt, aes.CreateDecryptor(key, key), CryptoStreamMode.Read))
{
int data;
while ((data = cs.ReadByte()) != -1)
{
fsOut.WriteByte((byte)data);
}
aes.Clear();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
aes.Clear();
}
finally
{
if (fsCrypt != null)
{
fsCrypt.Dispose();
}
}
}
}
You are overwriting the internal structure of a zip file with your encryption algorithm.
How could you expect that an external zip manager recognizes your encrypted file as a valid zip file?
If you really want to use a password protected zip file then use a library that can do this for you without destroying the zip file structure.
I recommend this library DotNetZip
It is not possible to unzip a file if the format is not that of zip. Once you encrypt a file you the format is no longer zip.
But it is possible to perform both encryption and compression in C#. For better compression ratio you would need to compress the file first and then encrypt.
You can use GZipstream to compress and the code you have depicted to encrypt.

Categories