Password Protect Zip Files and Archives in Java

Aspose.ZIP API lets you compress and decompress files in Java without worrying about the underlying file structure. This article shows working with single as well as multiple files compression.

Compressing Archives

Encrypt Files with Traditional Encryption Scheme

1try (FileOutputStream zipFile = new FileOutputStream(dataDir + "CompressWithTraditionalEncryption_out.zip")) {
2    try (FileInputStream source1 = new FileInputStream(dataDir + "alice29.txt")) {
3        Archive archive = new Archive(new ArchiveEntrySettings(null, new TraditionalEncryptionSettings("p@s$")));
4        archive.createEntry("alice29.txt", source1);
5        archive.save(zipFile);
6    }
7} catch (IOException ex) {
8    System.out.println(ex);
9}

Encrypt Files with AES Encryption

Encryption of Files with AES128

1try (FileOutputStream zipFile = new FileOutputStream(dataDir + "PasswordProtectWithAES128_out.zip")) {
2    try (FileInputStream source1 = new FileInputStream(dataDir + "alice29.txt")) {
3        Archive archive = new Archive(new ArchiveEntrySettings(null, new AesEncryptionSettings("p@s$", EncryptionMethod.AES128)));
4        archive.createEntry("alice29.txt", source1);
5        archive.save(zipFile);
6    }
7} catch (IOException ex) {
8    System.out.println(ex);
9}

Encryption of Files with AES192

1try (FileOutputStream zipFile = new FileOutputStream(dataDir + "PasswordProtectWithAES192_out.zip")) {
2    try (FileInputStream source1 = new FileInputStream(dataDir + "alice29.txt")) {
3        Archive archive = new Archive(new ArchiveEntrySettings(null, new AesEncryptionSettings("p@s$", EncryptionMethod.AES192)));
4        archive.createEntry("alice29.txt", source1);
5        archive.save(zipFile);
6    }
7} catch (IOException ex) {
8    System.out.println(ex);
9}

Encryption of Files with AES256

1try (FileOutputStream zipFile = new FileOutputStream(dataDir + "PasswordProtectWithAES256_out.zip")) {
2    try (FileInputStream source1 = new FileInputStream(dataDir + "alice29.txt")) {
3        Archive archive = new Archive(new ArchiveEntrySettings(null, new AesEncryptionSettings("p@s$", EncryptionMethod.AES256)));
4        archive.createEntry("alice29.txt", source1);
5        archive.save(zipFile);
6    }
7} catch (IOException ex) {
8    System.out.println(ex);
9}

Password Protect Directory

1try (FileOutputStream zipFile = new FileOutputStream(".\\all_corpus_encrypted_out.zip")) {
2    File corpus = new File(".\\CanterburyCorpus");
3    try (Archive archive = new Archive(new ArchiveEntrySettings(null, new TraditionalEncryptionSettings("p@s$")))) {
4        archive.createEntries(corpus);
5        archive.save(zipFile);
6    }
7} catch (IOException ex) {
8    System.out.println(ex);
9}

Encrypt Multiple Files with Mixed Encryption Techniques

 1try (FileOutputStream zipFile = new FileOutputStream("archive.zip")) {
 2    File fi1 = new File("data1.bin");
 3    File fi2 = new File("data2.bin");
 4    File fi3 = new File("data3.bin");
 5    try (Archive archive = new Archive()) {
 6        archive.createEntry("entry1.bin", fi1, false, new ArchiveEntrySettings(new DeflateCompressionSettings(), new TraditionalEncryptionSettings("pass1")));
 7        archive.createEntry("entry2.bin", fi2, false, new ArchiveEntrySettings(new DeflateCompressionSettings(), new AesEncryptionSettings("pass2", EncryptionMethod.AES128)));
 8        archive.createEntry("entry3.bin", fi3, false, new ArchiveEntrySettings(new DeflateCompressionSettings(), new AesEncryptionSettings("pass3", EncryptionMethod.AES256)));
 9        archive.save(zipFile);
10    }
11} catch (IOException ignored) {
12}

Decompressing Archives

Decompression of Traditionally Password Protected Archives

 1try (FileInputStream fs = new FileInputStream(dataDir + "CompressWithTraditionalEncryption_in.zip")) {
 2    try (FileOutputStream extracted = new FileOutputStream(dataDir + "alice_extracted_out.txt")) {
 3        ArchiveLoadOptions options = new ArchiveLoadOptions();
 4        options.setDecryptionPassword("p@s$");
 5        try (Archive archive = new Archive(fs, options)) {
 6            try (InputStream decompressed = archive.getEntries().get(0).open()) {
 7                byte[] b = new byte[8192];
 8                int bytesRead;
 9                while (0 < (bytesRead = decompressed.read(b, 0, b.length))) {
10                    extracted.write(b, 0, bytesRead);
11                }
12            }
13        }
14    }
15} catch (IOException ex) {
16    System.out.println(ex);
17}

Decompress AES Encrypted Archives

 1try (FileInputStream fs = new FileInputStream(dataDir + "PasswordProtectWithAES256_in.zip")) {
 2    try (FileOutputStream extracted = new FileOutputStream(dataDir + "alice_aesextracted_out.txt")) {
 3        try (Archive archive = new Archive(fs)) {
 4            try (InputStream decompressed = archive.getEntries().get(0).open("p@s$")) {
 5                byte[] b = new byte[8192];
 6                int bytesRead;
 7                while (0 < (bytesRead = decompressed.read(b, 0, b.length))) {
 8                    extracted.write(b, 0, bytesRead);
 9                }
10            }
11        }
12    }
13} catch (IOException ex) {
14    System.out.println(ex);
15}

Decompress AES Encrypted Stored Archive

 1try (FileInputStream fs = new FileInputStream(dataDir + "StoreMutlipleFilesWithoutCompressionWithPassword_in.zip")) {
 2    try (FileOutputStream extracted = new FileOutputStream(dataDir + "alice_aesextracted_out.txt")) {
 3        ArchiveLoadOptions options = new ArchiveLoadOptions();
 4        options.setDecryptionPassword("p@s$");
 5        try (Archive archive = new Archive(fs, options)) {
 6            try (InputStream decompressed = archive.getEntries().get(0).open()) {
 7                byte[] b = new byte[8192];
 8                int bytesRead;
 9                while (0 < (bytesRead = decompressed.read(b, 0, b.length))) {
10                    extracted.write(b, 0, bytesRead);
11                }
12            }
13        }
14    }
15} catch (IOException ex) {
16    System.out.println(ex);
17}

Decompress Encrypted Folder to Directory

1try (FileInputStream zipFile = new FileInputStream(".\\all_corpus_encrypted.zip")) {
2    ArchiveLoadOptions options = new ArchiveLoadOptions();
3    options.setDecryptionPassword("p@s$");
4    new Archive(zipFile, options).extractToDirectory(".\\all_corpus_decrypted");
5} catch (IOException ex) {
6    System.out.println(ex);
7}

Decompress Archive having Single File

 1try (FileInputStream fs = new FileInputStream(dataDir + "CompressedSingleFile.zip")) {
 2    try (Archive archive = new Archive(fs)) {
 3        int[] percentReady = new int[] {0};
 4        archive.getEntries().get(0).setExtractionProgressed(new Event<ProgressEventArgs>() {
 5            @Override
 6            public void invoke(Object sender, ProgressEventArgs progressEventArgs) {
 7                int percent = (int) ((100 * progressEventArgs.getProceededBytes()) / ((ArchiveEntry) sender).getUncompressedSize());
 8                if (percent > percentReady[0]) {
 9                    System.out.println(percent + "% decompressed");
10                    percentReady[0] = percent;
11                }
12            }
13        });
14        archive.getEntries().get(0).extract(dataDir + "alice_extracted_out.txt");
15    }
16} catch (IOException ex) {
17    System.out.println(ex);
18}

Decompress Archive having Multiple Files

 1try (FileInputStream fs = new FileInputStream(dataDir + "CompressedMultipleFiles.zip")) {
 2    StringBuilder sb = new StringBuilder("Entries are: ");
 3    int[] percentReady = new int[] {0};
 4    ArchiveLoadOptions options = new ArchiveLoadOptions();
 5    options.setEntryListed(new Event<EntryEventArgs>() {
 6        @Override
 7        public void invoke(Object sender, EntryEventArgs entryEventArgs) {
 8            sb.append(entryEventArgs.getEntry().getName()).append(", ");
 9        }
10    });
11    options.setEntryExtractionProgressed(new Event<ProgressEventArgs>() {
12        @Override
13        public void invoke(Object sender, ProgressEventArgs progressEventArgs) {
14            int percent = (int) ((100 * progressEventArgs.getProceededBytes()) / ((ArchiveEntry) sender).getUncompressedSize());
15            if (percent > percentReady[0]) {
16                System.out.println(percent + "% compressed");
17                percentReady[0] = percent;
18            }
19        }
20    });
21    try (Archive archive = new Archive(fs, options)) {
22        System.out.println(sb.substring(0, sb.length() - 2));
23        try (FileOutputStream extracted = new FileOutputStream(dataDir + "alice_extracted_out.txt")) {
24            try (InputStream decompressed = archive.getEntries().get(0).open()) {
25                byte[] buffer = new byte[8192];
26                int bytesRead;
27                while (0 < (bytesRead = decompressed.read(buffer, 0, buffer.length))) {
28                    extracted.write(buffer, 0, bytesRead);
29                }
30                // Read from decompressed stream to extracting file.
31            }
32        }
33        percentReady[0] = 0;
34        archive.getEntries().get(1).extract(dataDir + "asyoulik_extracted_out.txt");
35    }
36} catch (IOException ex) {
37    System.out.println(ex);
38}

Extract Stored Archive without Compression

 1try (FileInputStream zipFile = new FileInputStream(dataDir + "StoreMultipleFilesWithoutCompression.zip")) {
 2    try (Archive archive = new Archive(zipFile)) {
 3        try (FileOutputStream extracted = new FileOutputStream(dataDir + "alice_extracted_store_out.txt")) {
 4            try (InputStream decompressed = archive.getEntries().get(0).open()) {
 5                byte[] buffer = new byte[8192];
 6                int bytesRead;
 7                while (0 < (bytesRead = decompressed.read(buffer, 0, buffer.length))) {
 8                    extracted.write(buffer, 0, bytesRead);
 9                }
10                // Read from decompressed stream to extracting file.
11            }
12        }
13        try (FileOutputStream extracted = new FileOutputStream(dataDir + "asyoulik_extracted_store_out.txt")) {
14            try (InputStream decompressed = archive.getEntries().get(1).open()) {
15                byte[] buffer = new byte[8192];
16                int bytesRead;
17                while (0 < (bytesRead = decompressed.read(buffer, 0, buffer.length))) {
18                    extracted.write(buffer, 0, bytesRead);
19                }
20                // Read from decompressed stream to extracting file.
21            }
22        }
23    }
24} catch (IOException ex) {
25    System.out.println(ex);
26}
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.