Архив защиты пароля

Aspose.zip API позволяет вам сжимать и декомпрессировать файлы в Java, не беспокоясь о базовой структуре файлов. В этой статье показана работа с одним, а также с несколькими файлами сжатие.

Сжатие архивов

Зашифруйте файлы с традиционной схемой шифрования

1try (fileOutputStream Zipfile = new FileOutputStream (datadir + "compressWithTraditionalEncryption_out.zip")) {
2    try (fileInputStream Source1 = new FileInputStream (datadir + "alice29.txt")) {
3        Архив Archive = новый архив (новый архивизионный комплекс (null, новые традиционные инфекции ("p@s $")));
4        Archive.createEntry ("alice29.txt", Source1);
5        Archive.save (Zipfile);
6    }
7} catch (ioException ex) {
8    System.out.println (Ex);
9}

Зашифруйте файлы с шифрованием AES

Шифрование файлов с AES128

1try (fileOutputStream ZipFile = new FileOutputStream (dataDir + "passwordProtectwithaes128_out.zip")) {
2    try (fileInputStream Source1 = new FileInputStream (datadir + "alice29.txt")) {
3        Архив Archive = новый архив (новый архивизионный комплекс (null, новые aesencryptionsettings ("p@s $", incryptionmethod.aes128)));
4        Archive.createEntry ("alice29.txt", Source1);
5        Archive.save (Zipfile);
6    }
7} catch (ioException ex) {
8    System.out.println (Ex);
9}

Шифрование файлов с AES192

1try (fileOutputStream ZipFile = new FileOutputStream (datadir + "passwordProtectWithaes192_out.zip")) {
2    try (fileInputStream Source1 = new FileInputStream (datadir + "alice29.txt")) {
3        Archive Archive = новый архив (новый архивизионный комплекс (null, new aescryptionsettings ("p@s $", incryptionmethod.aes192)));
4        Archive.createEntry ("alice29.txt", Source1);
5        Archive.save (Zipfile);
6    }
7} catch (ioException ex) {
8    System.out.println (Ex);
9}

Шифрование файлов с AES256

1try (fileOutputStream ZipFile = new FileOutputStream (dataDir + "passwordProtectwithaes256_out.zip")) {
2    try (fileInputStream Source1 = new FileInputStream (datadir + "alice29.txt")) {
3        Архив Archive = новый архив (новый архивизионный комплекс (null, new aescryptionsettings ("p@s $", incryptionmethod.aes256))));
4        Archive.createEntry ("alice29.txt", Source1);
5        Archive.save (Zipfile);
6    }
7} catch (ioException ex) {
8    System.out.println (Ex);
9}

Справочник по защите пароля

1try (fileOutputStream ZipFile = new FileOutputStream (". \\ all_corpus_encrypted_out.zip")) {
2    File corpus = new File (". \\ canterbycorpus");
3    Попробуйте (Archive Archive = New Archive (New ArchiveEntrySettings (NULL, New TranteralEncryptionSettings ("P@S $"))) {
4        Archive.CreateEntries (корпус);
5        Archive.save (Zipfile);
6    }
7} catch (ioException ex) {
8    System.out.println (Ex);
9}

Зашифруйте несколько файлов с помощью методов смешанного шифрования

 1try (fileOutputStream ZipFile = new FileOutputStream ("archive.zip")) {
 2    File fi1 = новый файл ("data1.bin");
 3    File fi2 = новый файл ("data2.bin");
 4    Файл fi3 = новый файл ("data3.bin");
 5    Попробуйте (Archive Archive = new Archive ()) {
 6        archive.createEntry ("intry1.bin", fi1, false, новые архивизионные установки (новые defflecompressionsettings (), новые традиционные инфекции ("pass1")));
 7        Archive.CreateEntry ("intrint2.bin", fi2, false, новые архивизионные установки (новые defflecompressionsettings (), новые aesencryptionsettings ("pass2", incryptionmethod.aes128)));
 8        Archive.CreateEntry ("entry3.bin", fi3, false, новые архивизионные установки (новые defflecompressionsettings (), новые aesencryptionsettings ("pass3", incryptionmethod.aes256)));
 9        Archive.save (Zipfile);
10    }
11} catch (ioException игнорируется) {
12}

Декомпрессирующие архивы

Декомпрессия традиционно защищенных паролем архивов

 1try (fileInputStream fs = new FileInputStream (datadir + "compressWithtraditionalEncryption_in.zip")) {
 2    try (fileOutputStream Extracted = new FileOutputStream (dataDir + "alice_extracted_out.txt")) {
 3        Archiveloadoptions Options = new ArchiveLodoptions ();
 4        Options.setDecryptionPassword ("p@s $");
 5        Попробуйте (Archive Archive = New Archive (fs, Options)) {
 6            try (inputstream decompressed = archive.getEntries (). get (0) .open ()) {
 7                байт [] b = новый байт [8192];
 8                int bytesread;
 9                while (0 <(bytesread = decompressed.read (b, 0, b.length))) {
10                    Извлечен.
11                }
12            }
13        }
14    }
15} catch (ioException ex) {
16    System.out.println (Ex);
17}

Раздражайте AES зашифрованные архивы

 1try (fileInputStream fs = new FileInputStream (datadir + "passwordProtectWithaes256_in.zip")) {
 2    try (fileOutputStream Extracted = new FileOutputStream (datAdir + "alice_aesextracted_out.txt")) {
 3        Попробуйте (Archive Archive = New Archive (fs)) {
 4            Попробуйте (inputStream decompressed = archive.getEntries (). get (0) .open ("p@s $")) {
 5                байт [] b = новый байт [8192];
 6                int bytesread;
 7                while (0 <(bytesread = decompressed.read (b, 0, b.length))) {
 8                    Извлечен.
 9                }
10            }
11        }
12    }
13} catch (ioException ex) {
14    System.out.println (Ex);
15}

Раздражанный AES зашифровал сохраненный архив

 1try (fileInputStream fs = new FileInputStream (dataDir + "StoreMutliplefileswithoutCompressionWithPassword_in.zip")) {
 2    try (fileOutputStream Extracted = new FileOutputStream (datAdir + "alice_aesextracted_out.txt")) {
 3        Archiveloadoptions Options = new ArchiveLodoptions ();
 4        Options.setDecryptionPassword ("p@s $");
 5        Попробуйте (Archive Archive = New Archive (fs, Options)) {
 6            try (inputstream decompressed = archive.getEntries (). get (0) .open ()) {
 7                байт [] b = новый байт [8192];
 8                int bytesread;
 9                while (0 <(bytesread = decompressed.read (b, 0, b.length))) {
10                    Извлечен.
11                }
12            }
13        }
14    }
15} catch (ioException ex) {
16    System.out.println (Ex);
17}

Decompress зашифрованная папка в каталог

1try (fileInputStream Zipfile = new FileInputStream (". \\ all_corpus_encrypted.zip")) {
2    Archiveloadoptions Options = new ArchiveLodoptions ();
3    Options.setDecryptionPassword ("p@s $");
4    Новый архив (Zipfile, Options) .ExtractToDirectory (". \\ all_corpus_decrypted");
5} catch (ioException ex) {
6    System.out.println (Ex);
7}

Архив декомпрессации с одним файлом

 1try (fileInputStream fs = new FileInputStream (datadir + "compressedsinglefile.zip")) {
 2    Попробуйте (Archive Archive = New Archive (fs)) {
 3        int [] inpityRead = new int [] {0};
 4        archive.getEntries (). get (0) .setExtractionProgressed (New Event <prosingEventargs> () {
 5            @Override
 6            public void indoke (отправитель объектов, ProgressEventargs ProgressEventargs) {
 7                int procet = (int) ((100 * progresseventargs.getproudeedbytes ()) / ((ArchiveEntry) отправитель). GetunCompressedSize ());
 8                if (процент> процент готов [0]) {
 9                    System.out.println (процент + "% декомпрессирован");
10                    процент готовы [0] = процент;
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}

Архив распаковки с несколькими файлами

 1try (fileInputStream fs = new FileInputStream (dataDir + "compressedMultiplefiles.zip")) {
 2    StringBuilder SB = new StringBuilder ("Записи:");
 3    int [] inpityRead = new int [] {0};
 4    Archiveloadoptions Options = new ArchiveLodoptions ();
 5    Options.SetEntryListed (New Event <pretniEventargs> () {
 6        @Override
 7        public void indoke (отправитель объектов, enteventargs enteventargs) {
 8            SB.Append (enteVentargs.getEntry (). getName ()). Append (",");
 9        }
10    });
11    Options.setEntryExtractionProgressed (New Event <progressEventargs> () {
12        @Override
13        public void indoke (отправитель объектов, ProgressEventargs ProgressEventargs) {
14            int procet = (int) ((100 * progresseventargs.getproudeedbytes ()) / ((ArchiveEntry) отправитель). GetunCompressedSize ());
15            if (процент> процент готов [0]) {
16                System.out.println (процент + "% сжатый");
17                процент готовы [0] = процент;
18            }
19        }
20    });
21    Попробуйте (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                байт [] буфер = новый байт [8192];
26                int bytesread;
27                while (0 <(bytesread = decompressed.read (buffer, 0, buffer.length))) {
28                    Извлечен.
29                }
30                // Читать из декомпрессированного потока в извлечение файла.
31            }
32        }
33        процент готовы [0] = 0;
34        archive.getEntries (). get (1) .extract (datadir + "asyoulik_extracted_out.txt");
35    }
36} catch (ioException ex) {
37    System.out.println (Ex);
38}

Извлечение хранимого архива без сжатия

 1try (fileInputStream Zipfile = new FileInputStream (datadir + "StoreMultipleFileswithoutCompression.zip")) {
 2    попробуйте (архив архив = новый архив (Zipfile)) {
 3        try (fileOutputStream Extracted = new FileOutPutStream (datAdir + "alice_extracted_store_out.txt")) {
 4            try (inputstream decompressed = archive.getEntries (). get (0) .open ()) {
 5                байт [] буфер = новый байт [8192];
 6                int bytesread;
 7                while (0 <(bytesread = decompressed.read (buffer, 0, buffer.length))) {
 8                    Извлечен.
 9                }
10                // Читать из декомпрессированного потока в извлечение файла.
11            }
12        }
13        try (fileOutputStream Extracted = new FileOutputStream (datAdir + "asyoulik_extracted_store_out.txt")) {
14            try (inputstream decompressed = archive.getEntries (). get (1) .open ()) {
15                байт [] буфер = новый байт [8192];
16                int bytesread;
17                while (0 <(bytesread = decompressed.read (buffer, 0, buffer.length))) {
18                    Извлечен.
19                }
20                // Читать из декомпрессированного потока в извлечение файла.
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.