Overview
Aspose.ZIP facilitates a number of operations related to encryption and decryption of archives. Using Aspose.Zip API for Java, you can quickly Encrypt and Decrypt ZIP, RAR, 7-Zip archives.Encrypt/Decrypt ZIP Files
There are two encryption methods available for ZIP archives : the traditional method, which is now considered weak, and the modern AES method. The ZIP standard allows any entry to be encrypted with either method, even within the same ZIP archive. AES encryption offers stronger security and is available in different key lengths (128-bit, 192-bit, and 256-bit). This provides better protection for sensitive data stored within ZIP archives.
Encrypt a ZIP with Deflate method
try (FileOutputStream zipFile = new FileOutputStream("archive.zip")) {
try (FileInputStream source = new FileInputStream("alice29.txt")) {
Archive archive = new Archive(new ArchiveEntrySettings(CompressionSettings.getDeflate(), new TraditionalEncryptionSettings("p@s$S")));
archive.createEntry("alice29.txt", source);
archive.save(zipFile);
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
This code creates a ZIP archive named "archive.zip" using the Deflate compression method and traditional ZIP encryption. It achieves this by first opening a new output stream for the archive using try FileOutputStream. The FileInputStream source serves as the input stream for the source file "alice29.txt" that will be added to the archive. Next, an Archive object is created, specifying both the Deflate compression method and traditional encryption. The password for encryption is set to "p@s$S". The catch statement handles any exceptions that might arise during file or archive operations, printing an error message to the console.
Encrypting ZIP with AES method
try (FileOutputStream zipFile = new FileOutputStream("archive.zip")) {
try (FileInputStream source = new FileInputStream("alice29.txt")) {
try (Archive archive = new Archive(new ArchiveEntrySettings(CompressionSettings.getDeflate(), new AesEncryptionSettings("p@s$S", EncryptionMethod.AES256)))) {
archive.createEntry("alice29.txt", source);
archive.save(zipFile);
}
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
This code creates a ZIP archive named "archive.zip" using the Deflate compression method and encrypts the data with the strong AES-256 algorithm.
For these samples we provided instances of
EncryptionSetting
within corresponding
Archive constructor
. It is possible to apply encryption for particular entry leaving other unprotected.
Using the ZIP encryption algorithm, encrypt the second entry of three
try (FileOutputStream zipFile = new FileOutputStream("archive.zip")) {
File source1 = new File("alice29.txt");
File source2 = new File("asyoulik.txt");
File source3 = new File("fields.c");
try (Archive archive = new Archive()) {
archive.createEntry("alice29.txt", source1);
archive.createEntry("asyoulik.txt", source2, false, new ArchiveEntrySettings(null, new AesEncryptionSettings("p@s$S", EncryptionMethod.AES256)));
archive.createEntry("fields.c", source3);
archive.save(zipFile);
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
This code demonstrates creating a ZIP archive with three input files: "alice29.txt", "asyoulik.txt", and "fields.c". Uniquely, the first and last files are added unencrypted, while the second file, "asyoulik.txt", is password-protected using AES-256 encryption with the password "p@s$S".
This approach of selectively encrypting files within a ZIP archive is uncommon. However, the Aspose.Zip API for Java provides the functionality to encrypt specific entries within a ZIP archive using different encryption methods and passwords. While this enhances data security, but complicates the process of archive management and decryption
Encrypt ZIP with different methods and passwords
try (FileOutputStream zipFile = new FileOutputStream("archive.zip")) {
File source1 = new File("alice29.txt");
File source2 = new File("asyoulik.txt");
File source3 = new File("fields.c");
try (Archive archive = new Archive()) {
archive.createEntry("alice29.txt", source1, false, new ArchiveEntrySettings(null, new AesEncryptionSettings("p@s$S", EncryptionMethod.AES256)));
archive.createEntry("asyoulik.txt", source2, false, new ArchiveEntrySettings(null, new TraditionalEncryptionSettings("p@s$D")));
archive.createEntry("fields.c", source3, false, new ArchiveEntrySettings(null, new AesEncryptionSettings("p@s$F", EncryptionMethod.AES256)));
archive.save(zipFile);
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
This code creates a ZIP archive containing three encrypted files: "alice29.txt", "asyoulik.txt", and "fields.c". Each file is encrypted with a distinct method.
The first part mirrors the functionality of the previous code example. The core section focuses on creating entries within the archive for each file. These entries reference their names and source files (File objects). Encryption is applied with varying methods:
- "alice29.txt" : AES-256 encryption with the password "p@s$S"
- "asyoulik.txt" : Traditional encryption method with the password "p@s$D"
- "fields.c" : AES-256 encryption with the password "p@s$F"
Encrypt Existing ZIP Archive
try (Archive archive = new Archive("plain.zip")) {
ArchiveSaveOptions options = new ArchiveSaveOptions();
options.setEncryptionOptions(new AesEncryptionSettings("p@s$S", EncryptionMethod.AES256));
archive.save("encrypted.zip", options);
}
This code takes an existing "plain.zip" archive, applies AES encryption to it with the password "p@s$S", and saves it as a new archive named "encrypted.zip"
Decrypt ZIP File With Password
try (Archive archive = new Archive("source.zip")) {
archive.getEntries().get(0).extract("first_entry.bin", "p@s$S");
}
This code extracts the first entry from the "source.zip" archive and saves it as a file named "first_entry.bin" using the password "p@s$S".
The user has the option to decrypt either a specific entry within the encrypted ZIP archive or the entire archive as a whole.
Decrypt Whole ZIP File
ArchiveLoadOptions options = new ArchiveLoadOptions();
options.setDecryptionPassword("p@s$S");
try (Archive archive = new Archive("source.zip", options)) {
archive.extractToDirectory("destination");
}
In this case we need to provide password within a constructor.
Encrypt/Decrypt RAR File with Java
Aspose.ZIP does not provide functionality for creating
RAR archives
; it solely supports extraction. A RAR archive can be encrypted, with the option to protect file names or not.
In the former scenario, the user must supply the decryption password within the
RarArchiveLoadOptions
object at the initialization of the RAR archive. In the latter case, the password can be provided during the extraction of individual entries.
Decrypt RAR file with encrypted file names
RarArchiveLoadOptions options = new RarArchiveLoadOptions();
options.setDecryptionPassword("p@s$S");
try (RarArchive archive = new RarArchive("source.rar", options)) {
archive.extractToDirectory("destination");
}
This code decrypts and extracts the contents of the "source.rar" archive to the "destination" folder. If the archive is encrypted, it uses the specified decryption password.
Here’s a breakdown of how it works:
- Load Settings with Decryption Password: First, it creates a load settings object for the RAR archive using the RarArchiveLoadOptions options operator. It then sets the decryption password for the archive using the options.setDecryptionPassword method.
- Open Encrypted Archive: The next line opens the "source.rar" archive for reading and editing using a try-with-resources construct. It specifies the options object with the decryption password to handle encrypted archives.
- Extract Archive Contents: Finally, the archive.extractToDirectory method extracts the contents of the decrypted archive to the "destination" folder.
Targeted Decryption RAR File
try (RarArchive archive = new RarArchive("source.rar")) {
archive.getEntries().get(0).extract("first_entry.bin", "p@s$S");
}
This code snippet attempts to extract the first entry from the "source.rar" RAR archive and save it as "first_entry.bin", using the decryption password "p@s$S" if the archive is encrypted.
Decrypting Specific RAR Entry Content (Stream)
ByteArrayOutputStream destination = new ByteArrayOutputStream();
try (RarArchive archive = new RarArchive("source.rar")) {
try (InputStream source = archive.getEntries().get(1).open("p@s$S")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = source.read(buffer, 0, buffer.length)) > 0) {
destination.write(buffer, 0, bytesRead);
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
This code snippet targets a specific entry within a RAR archive. It decrypts the entry’s content and streams it directly into memory, assuming only the entry data is encrypted, not the filenames themselves.
A full description of what the code does:
- Memory Buffer Initialization: A ByteArrayOutputStream named destination is created to serve as an in-memory buffer for storing the decrypted content of the targeted entry.
- Archive and Entry Access: The code utilizes a try-with-resources block to open the source RAR archive "source.rar". Inside another try-with-resources block, it retrieves an input stream for the second entry and decrypts it using the password "p@s$S".
- Decryption and Streaming: The decrypted bytes are read from the input stream in chunks using a buffer .Each chunk is then written to the destination ByteArrayOutputStream until all the data is processed.
- Error Handling: The code incorporates a catch block to handle any potential IOExceptions that might arise during the decryption or streaming process. If an error occurs, the error message is printed to the standard error stream for debugging purposes.
Encrypt and Decrypt 7-ZIP File with Java
Will be implemented in Aspose.ZIP for Java 24.4 version. The only 7z archive encryption option is AES.
Encrypt and Compress 7-Zip file with LZMA2
using (FileStream szFile = File.Open("archive.7z", FileMode.Create))
{
FileInfo source1 = new FileInfo("alice29.txt");
FileInfo source2 = new FileInfo("asyoulik.txt");
FileInfo source3 = new FileInfo("fields.c");
using (var archive = new SevenZipArchive(new SevenZipEntrySettings(new SevenZipLZMA2CompressionSettings(), new SevenZipAESEncryptionSettings("p@s$S"))))
{
archive.CreateEntry("alice29.txt", source1);
archive.CreateEntry("asyoulik.txt", source2);
archive.CreateEntry("fields.c", source3);
archive.Save(szFile);
}
}
7Z archives supports an ability to encrypt each entry with own password or leave unprotected. This code creates a new 7z archive with LZMA2 and AES compression and encryption.
- File Opening: A FileStream is used to open a new file named "archive.7z" in creation mode.
- Initializing Objects: Three FileInfo objects are created for the files "alice29.txt", "asyoulik.txt", and "fields.c".
- Creating an 7-zip file: The SevenZipArchive object is created with:
- LZMA2 compression settings.
- AES encryption settings using the password "p@s$S" - Adding Files: The CreateEntry methods are used to add each file to the archive from a separate source.
- Saving the Archive: The archive is saved to the szFile file stream using the Save method.
Selective Encryption in 7z Archive
using (FileStream szFile = File.Open("archive.7z", FileMode.Create))
{
FileInfo source1 = new FileInfo("alice29.txt");
FileInfo source2 = new FileInfo("asyoulik.txt");
FileInfo source3 = new FileInfo("fields.c");
using (var archive = new SevenZipArchive())
{
archive.CreateEntry("alice29.txt", source1);
archive.CreateEntry("asyoulik.txt", source2, false, new SevenZipEntrySettings(new SevenZipLZMA2CompressionSettings(), new SevenZipAESEncryptionSettings("p@s$S")));
archive.CreateEntry("fields.c", source3, false, new SevenZipEntrySettings(new SevenZipLZMA2CompressionSettings(), new SevenZipAESEncryptionSettings("$ecret")));
archive.Save(szFile);
}
}
This code creates a 7z archive containing three files: "alice29.txt", "asyoulik.txt", and "fields.c". The latter two files are compressed and encrypted using different passwords.
Unlike the previous code, the archive.CreateEntry method is used on the archive object to create entries for each file. When creating the entry for "asyoulik.txt" from the source2 FileInfo object, the third parameter of CreateEntry is set to false. This indicates that custom compression and encryption settings will be used, defined in the fourth parameter (a SevenZipEntrySettings object). In this instance, the settings specify "Zip LZMA2" compression and "Zip AES" encryption with the password "p@s$S".
Similar as ZIP, user can decrypt either whole archive or particular entry from it.
7Z archive
can be encrypted with or without protecting file names. If file names are encrypted, you need to provide password
on archive instantiation
.
7z Decryption with Encrypted Filenames
try (SevenZipArchive archive = new SevenZipArchive("archive.7z", "p@s$S")) {
archive.extractToDirectory("C:\\extracted");
}
This code utilizes a try-with-resources block to open a 7z archive named "archive.7z" protected with the password "p@s$S". It then extracts the archive’s contents to the "C:\extracted" folder.
Whether file names are encrypted or not, it is safe to provide password within extracting constructor. The below sample will only work when only content is protected.
Decrypting 7z Specific Entry
try (SevenZipArchive archive = new SevenZipArchive("archive.7z")) {
archive.getEntries().get(0).extract("data.bin", "p@s$S");
}
This code utilizes a try-with-resources block to open a 7z archive named "archive.7z" protected with the password "p@s$S". It then extracts the archive’s contents to the "C:\extracted" folder.
Whether file names are encrypted or not, it is safe to provide password within extracting constructor. The below sample will only work when only content is protected.
Other Supported Java Compression API
Use the Aspose.ZIP Java library to convert, merge, edit zip-file documents, extract data from the arhives, and more!
Support and Learning Resources
- Learning Resources
- Documentation
- Source Code
- API References
- Tutorial Videos
- Product Support
- Free Support
- Paid Support
- Blog
- Release Notes
- Why Aspose.ZIP for Java?
- Customers List
- Success Stories