Password Protecting Archives
Aspose.ZIP API lets you compress and decompress files in C# or any .NET langauge without worrying about the underlying file structure. This article provides examples of how to implement password protection with both traditional and AES encryption schemes. Additionally, it shows how to work with directories and compress multiple files using mixed encryption techniques.
Password Protection with Traditional Encryption
Aspose.ZIP enables traditional password protection for compressed files. Using a simple password, you can secure individual files or entire directories within an archive, ensuring that only authorized users can extract the contents.
Encrypt Files with Traditional Encryption Scheme
Encrypt files using a simpler, traditional encryption method. This approach allows for basic password protection of archives, ensuring that files are securely compressed while remaining accessible through the use of the correct password.
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (FileStream zipFile = File.Open(dataDir + "CompressWithTraditionalEncryption_out.zip", FileMode.Create))
3 {
4 using (FileStream source1 = File.Open(dataDir + "alice29.txt", FileMode.Open, FileAccess.Read))
5 {
6 var archive = new Archive(new ArchiveEntrySettings(null, new TraditionalEncryptionSettings("p@s$")));
7 archive.CreateEntry("alice29.txt", source1);
8 archive.Save(zipFile);
9 }
10 }
Encrypt Files with AES Encryption
Aspose.ZIP for .NET provides encryption capabilities to help you secure sensitive files within archives. The API supports AES encryption, offering multiple key sizes (128-bit, 192-bit, and 256-bit) for varying levels of security. With these encryption methods, you can ensure that your data is well-protected and only accessible to authorized users.
Encryption of Files with AES128
Aspose.ZIP for .NET provides encryption capabilities to help you secure sensitive files within archives. The API supports AES encryption, offering multiple key sizes (128-bit, 192-bit, and 256-bit) for varying levels of security. With these encryption methods, you can ensure that your data is well-protected and only accessible to authorized users. Here’s an example of how it’s done.
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (FileStream zipFile = File.Open(dataDir + "PasswordProtectWithAES128_out.zip", FileMode.Create))
3 {
4 using (FileStream source1 = File.Open(dataDir + "alice29.txt", FileMode.Open, FileAccess.Read))
5 {
6 using (var archive = new Archive(new ArchiveEntrySettings(null, new AesEcryptionSettings("p@s$", EncryptionMethod.AES128))))
7 {
8 archive.CreateEntry("alice29.txt", source1);
9 archive.Save(zipFile);
10 }
11 }
12 }
Encryption of Files with AES192
AES192 encryption offers a higher level of security compared to AES128, with a slightly increased encryption overhead. This method is suitable for scenarios where stronger protection is required without compromising too much on performance. Check out the following example to understand its usage.
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (FileStream zipFile = File.Open(dataDir + "PasswordProtectWithAES192_out.zip", FileMode.Create))
3 {
4 using (FileStream source1 = File.Open(dataDir + "alice29.txt", FileMode.Open, FileAccess.Read))
5 {
6 using (var archive = new Archive(new ArchiveEntrySettings(null, new AesEcryptionSettings("p@s$", EncryptionMethod.AES192))))
7 {
8 archive.CreateEntry("alice29.txt", source1);
9 archive.Save(zipFile);
10 }
11 }
12 }
Encryption of Files with AES256
AES256 is the strongest encryption option available in the AES family, providing maximum security. It is ideal for protecting highly sensitive data where the utmost security is needed, even if it requires more computational power for encryption and decryption. See the example below.
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (FileStream zipFile = File.Open(dataDir + "PasswordProtectWithAES256_out.zip", FileMode.Create))
3 {
4 using (FileStream source1 = File.Open(dataDir + "alice29.txt", FileMode.Open, FileAccess.Read))
5 {
6 using (var archive = new Archive(new ArchiveEntrySettings(null, new AesEcryptionSettings("p@s$", EncryptionMethod.AES256))))
7 {
8 archive.CreateEntry("alice29.txt", source1);
9 archive.Save(zipFile);
10 }
11 }
12 }
Password Protect Directory
In addition to encrypting individual files, Aspose.ZIP allows you to password protect entire directories. This is particularly useful when you need to encrypt multiple files at once, securing all the contents within a directory under a single password.
1// For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2using (FileStream zipFile = File.Open(".\\all_corpus_encrypted_out.zip", FileMode.Create))
3{
4 DirectoryInfo corpus = new DirectoryInfo(".\\CanterburyCorpus");
5 using (var archive = new Archive(new ArchiveEntrySettings(null, new TraditionalEncryptionSettings("p@s$"))))
6 {
7 archive.CreateEntries(corpus);
8 archive.Save(zipFile);
9 }
10}
Encrypt Multiple Files with Mixed Encryption Techniques
API also supports using different encryption techniques within the same archive. This allows you to apply a mixture of encryption algorithms, such as AES and traditional password protection, to different files based on their sensitivity and security requirements. This flexibility enables more granular control over file protection within an archive. Take a look at this example to see how it works in practice.
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (FileStream zipFile = File.Open(dataDir + "CompressWithTraditionalEncryption_out.zip", FileMode.Create))
3 {
4 using (FileStream source1 = File.Open(dataDir + "alice29.txt", FileMode.Open, FileAccess.Read))
5 {
6 var archive = new Archive(new ArchiveEntrySettings(null, new TraditionalEncryptionSettings("p@s$")));
7 archive.CreateEntry("alice29.txt", source1);
8 archive.Save(zipFile);
9 }
10 }
Decompression of Password Protected Files
After encrypting archives, you will also need to know how to decrypt and extract files when needed. Aspose.ZIP simplifies the decompression of password-protected archives, regardless of whether traditional or AES encryption was used. You can extract files individually or decompress an entire encrypted directory.
Decompression of Traditionally Password Protected Archives
Easily extract files that have been protected with a traditional password. This method handles archives secured using older encryption techniques, ensuring access to your data once the correct password is provided.
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (FileStream fs = File.OpenRead(dataDir + "CompressWithTraditionalEncryption_out.zip"))
3 {
4 using (var extracted = File.Create(dataDir + "alice_extracted_out.txt"))
5 {
6 using (Archive archive = new Archive(fs, new ArchiveLoadOptions() { DecryptionPassword = "p@s$" }))
7 {
8 using (var decompressed = archive.Entries[0].Open())
9 {
10 byte[] b = new byte[8192];
11 int bytesRead;
12 while (0 < (bytesRead = decompressed.Read(b, 0, b.Length)))
13 {
14 extracted.Write(b, 0, bytesRead);
15 }
16 }
17 }
18 }
19 }
Decompress AES Encrypted Archives
This section covers how to extract files that are encrypted using AES, one of the most secure encryption standards. Whether you’re dealing with AES128, AES192, or AES256, the extraction process is straightforward as long as the correct decryption key is supplied.
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (FileStream fs = File.OpenRead(dataDir + "PasswordProtectWithAES256_out.zip"))
3 {
4 using (var extracted = File.Create(dataDir + "alice_aesextracted_out.txt"))
5 {
6 using (Archive archive = new Archive(fs))
7 {
8 using (var decompressed = archive.Entries[0].Open("p@s$"))
9 {
10 byte[] b = new byte[8192];
11 int bytesRead;
12 while (0 < (bytesRead = decompressed.Read(b, 0, b.Length)))
13 {
14 extracted.Write(b, 0, bytesRead);
15 }
16 }
17 }
18 }
19 }
Decompress AES Encrypted Stored Archive
Extract files from an archive that has been encrypted and stored without compression. This process ensures that even uncompressed files remain secure, protecting sensitive data while maintaining original file structure.
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (FileStream fs = File.OpenRead(dataDir + "StoreMutlipleFilesWithoutCompressionWithPassword_out.zip"))
3 {
4 using (var extracted = File.Create(dataDir + "alice_aesextracted_out.txt"))
5 {
6 using (Archive archive = new Archive(fs, new ArchiveLoadOptions() { DecryptionPassword = "p@s$" }))
7 {
8 using (var decompressed = archive.Entries[0].Open())
9 {
10 byte[] b = new byte[8192];
11 int bytesRead;
12 while (0 < (bytesRead = decompressed.Read(b, 0, b.Length)))
13 {
14 extracted.Write(b, 0, bytesRead);
15 }
16 }
17 }
18 }
19 }
Decompress Encrypted Folder to Directory
Extract entire encrypted directories back to their original folder structure. This process restores all files from the encrypted archive to a specified directory while preserving their original hierarchy and security, provided the correct decryption key is used.
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (FileStream zipFile = File.Open(".\\all_corpus_encrypted.zip", FileMode.Open))
3 {
4 new Archive(zipFile, new ArchiveLoadOptions() { DecryptionPassword = "p@s$" }).ExtractToDirectory(".\\all_corpus_decrypted");
5 }
Decompressing Archives
Aspose.ZIP for .NET offers an easy-to-use API for decompressing archives, whether they contain a single file, multiple files, or even stored files without compression. This section demonstrates various decompression scenarios, providing efficient solutions for extracting your compressed data.
Decompress Archive having Single File
In scenarios where an archive contains only one file, decompression is straightforward.You can extract the content of the archive quickly and with minimal overhead, ensuring the original data integrity using the next example:
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (FileStream fs = File.OpenRead(dataDir + "CompressSingleFile_out.zip"))
3 {
4 using (Archive archive = new Archive(fs))
5 {
6 int percentReady = 0;
7 archive.Entries[0].ExtractionProgressed += (s, e) =>
8 {
9 int percent = (int)((100 * e.ProceededBytes) / ((ArchiveEntry)s).UncompressedSize);
10 if (percent > percentReady)
11 {
12 Console.WriteLine(string.Format("{0}% decompressed", percent));
13 percentReady = percent;
14 }
15 };
16 archive.Entries[0].Extract(dataDir + "alice_extracted_out.txt");
17 }
18 }
Decompress Archive having Multiple Files
When working with archives containing multiple files, our API simplifies the process of iterating through the entries and efficiently extracting them. The event-based progress tracking during extraction is especially helpful for monitoring large decompression tasks.
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (FileStream zipFile = File.Open(dataDir + "CompressMultipleFiles_out.zip", FileMode.Open))
3 {
4 StringBuilder sb = new StringBuilder("Entries are: ");
5 int percentReady = 0;
6 using (Archive archive = new Archive(zipFile,
7 new ArchiveLoadOptions()
8 {
9 EntryListed = (s, e) => { sb.AppendFormat("{0}, ", e.Entry.Name); },
10 EntryExtractionProgressed = (s, e) =>
11 {
12 int percent = (int)((100 * e.ProceededBytes) / ((ArchiveEntry)s).UncompressedSize);
13 if (percent > percentReady)
14 {
15 Console.WriteLine(string.Format("{0}% compressed", percent)); percentReady = percent;
16 }
17 }
18 }))
19 {
20 Console.WriteLine(sb.ToString(0, sb.Length - 2));
21 using (var extracted = File.Create(dataDir + "alice_extracted_out.txt"))
22 {
23 using (var decompressed = archive.Entries[0].Open())
24 {
25 byte[] buffer = new byte[8192];
26 int bytesRead;
27 while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
28 {
29 extracted.Write(buffer, 0, bytesRead);
30 }
31 // Read from decompressed stream to extracting file.
32 }
33 }
34 percentReady = 0;
35 archive.Entries[1].Extract(dataDir + "asyoulik_extracted_out.txt");
36 }
37 }
Extract Stored Archive without Compression
Stored archives, which contain files that haven’t been compressed, are also supported by Aspose.Zip API. While these archives don’t reduce file size, they allow for quick access and efficient extraction of stored data. This is useful when you need to package files together without changing their structure.
1 // For complete examples and data files, please go to https://github.com/aspose-zip/Aspose.ZIP-for-.NET
2 using (FileStream zipFile = File.Open(dataDir + "StoreMultipleFilesWithoutCompression_out.zip", FileMode.Open))
3 {
4 using (Archive archive = new Archive(zipFile))
5 {
6 using (var extracted = File.Create(dataDir + "alice_extracted_store_out.txt"))
7 {
8 using (var decompressed = archive.Entries[0].Open())
9 {
10 byte[] buffer = new byte[8192];
11 int bytesRead;
12 while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
13 {
14 extracted.Write(buffer, 0, bytesRead);
15 }
16 // Read from decompressed stream to extracting file.
17 }
18 }
19
20 using (var extracted = File.Create(dataDir + "asyoulik_extracted_store_out.txt"))
21 {
22 using (var decompressed = archive.Entries[1].Open())
23 {
24 byte[] buffer = new byte[8192];
25 int bytesRead;
26 while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
27 {
28 extracted.Write(buffer, 0, bytesRead);
29 }
30 // Read from decompressed stream to extracting file.
31 }
32 }
33 }
34 }