Proteger archivos con contraseña

La API Aspose.ZIP permite comprimir y descomprimir archivos en Java sin preocuparse de la estructura de archivos subyacente. Este artículo muestra cómo trabajar con la compresión de archivos individuales y múltiples.

Compresión de Archivos

Encriptar archivos con el esquema de encriptación tradicional

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}

Encriptar archivos con cifrado AES

Encriptación de Archivos con 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}

Encriptación de ficheros con 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}

Encriptación de ficheros con 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}

Proteger directorio con contraseña

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}

Encriptar múltiples archivos con técnicas de encriptación mixtas

 1try (FileOutputStream zipFile = new FileOutputStream("archivo.zip")) {
 2    Archivo fi1 = new Archivo("datos1.bin");
 3    Archivo fi2 = new File("datos2.bin");
 4    Archivo fi3 = nuevo Archivo("datos3.bin");
 5    try (Archivo archive = nuevo Archivo()) {
 6        archive.createEntry("entrada1.bin", fi1, false, new ArchiveEntrySettings(new DeflateCompressionSettings(), new TraditionalEncryptionSettings("pass1"));
 7        archive.createEntry("entrada2.bin", fi2, false, new ArchiveEntrySettings(new DeflateCompressionSettings(), new AesEncryptionSettings("pass2", EncryptionMethod.AES128)));
 8        archive.createEntry("entrada3.bin", fi3, false, new ArchiveEntrySettings(new DeflateCompressionSettings(), new AesEncryptionSettings("pass3", EncryptionMethod.AES256)));
 9        archive.save(zipFile);
10    }
11} catch (IOException ignored) {
12}

Descompresión de archivos

Descompresión de archivos protegidos por contraseña

 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 descomprimido = archive.getEntries().get(0).open()) {
 7                byte[] b = nuevo byte[8192];
 8                int bytesRead;
 9                while (0 < (bytesRead = decompressed.read(b, 0, b.length)) {
10                    extraído.escribir(b, 0, bytesRead);
11                }
12            }
13        }
14    }
15} catch (IOException ex) {
16    System.out.println(ex);
17}

Descomprimir archivos encriptados AES

 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 descomprimido = archive.getEntries().get(0).open("p@s$")) {
 5                byte[] b = nuevo byte[8192];
 6                int bytesRead;
 7                while (0 < (bytesRead = decompressed.read(b, 0, b.length)) {
 8                    extraído.escribir(b, 0, bytesRead);
 9                }
10            }
11        }
12    }
13} catch (IOException ex) {
14    System.out.println(ex);
15}

Descomprimir archivo almacenado cifrado 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 ArchiveLoadOptions();
 4        options.setDecryptionPassword("p@s$");
 5        try (Archive archive = new Archive(fs, options)) {
 6            try (InputStream descomprimido = archive.getEntries().get(0).open()) {
 7                byte[] b = nuevo byte[8192];
 8                int bytesRead;
 9                while (0 < (bytesRead = decompressed.read(b, 0, b.length)) {
10                    extraído.escribir(b, 0, bytesRead);
11                }
12            }
13        }
14    }
15} catch (IOException ex) {
16    System.out.println(ex);
17}

Descomprimir carpeta cifrada a directorio

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}

Descomprimir archivo con un único fichero

 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(porcentaje + "% descomprimido");
10                    percentReady[0] = porcentaje;
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}

Descomprimir archivo con varios ficheros

 1try (FileInputStream fs = new FileInputStream(dataDir + "CompressedMultipleFiles.zip")) {
 2    StringBuilder sb = new StringBuilder("Las entradas son: ");
 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(porcentaje + "% comprimido");
17                percentReady[0] = porcentaje;
18            }
19        }
20    });
21    try (Archivo = nuevo Archivo(fs, opciones)) {
22        System.out.println(sb.substring(0, sb.length() - 2));
23        try (FileOutputStream extracted = new FileOutputStream(dataDir + "alice_extracted_out.txt")) {
24            try (InputStream descomprimido = 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                    extraído.escribir(búfer, 0, bytesRead);
29                }
30                // Leer del flujo descomprimido al archivo extraído.
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}

Extraer archivo almacenado sin compresión

 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 descomprimido = 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                    extraído.escribir(búfer, 0, bytesRead);
 9                }
10                // Leer del flujo descomprimido al archivo extraído.
11            }
12        }
13        try (FileOutputStream extracted = new FileOutputStream(dataDir + "asyoulik_extracted_store_out.txt")) {
14            try (InputStream descomprimido = 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                    extraído.escribir(búfer, 0, bytesRead);
19                }
20                // Leer del flujo descomprimido al archivo extraído.
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.