Crear archivo zip protegido por contraseña en Java

Principalmente, java no tiene ninguna función o paquete que cree un archivo zip protegido por contraseña sin usar algunos códigos nativos. Java tiene una biblioteca útil que es buena, pero usan algunos códigos nativos para realizar su tarea que hace que su plataforma de uso dependa hasta cierto punto. Mientras que en la biblioteca zip4j solo usamos código Java sin soporte de código nativo, esa es la razón por la que las personas usan jip4j sobre otras bibliotecas integradas. 

Hay una biblioteca llamada ‘zip4j’ que fue escrita por » Srikanth Reddy Lingala» en 2008/2009. Es la biblioteca Java más completa para archivos zip.

Algunas características importantes de la biblioteca zip4j son las siguientes:

  1. Creará, agregará, extraerá, actualizará y eliminará archivos de un archivo zip.
  2. Tiene soporte para flujos como ZipInputStream y ZipOuputStream .
  3. Podemos usar esta biblioteca para crear cualquier archivo zip protegido con contraseña en java.
  4. Podemos comprimir/descomprimir cualquier archivo o directorio existente simplemente especificando la ruta del archivo.
  5. También proporciona compatibilidad con el cifrado AES 128/256 y el cifrado Zip estándar.

Nota: ‘ zip4j’ está escrito en JDK 8 y si intentamos ejecutar esta biblioteca en JDK 7, no se admitirán todas las funciones.

Métodos:

  1. Enfoque ingenuo usando el paquete java.util.zip
  2. Enfoque eficiente

Método 1: enfoque ingenuo 

No tenemos ninguna biblioteca incorporada estándar de Java para crear un archivo zip protegido con contraseña. Solo podemos hacer un archivo zip simple con la ayuda del paquete java.util.zip .

Ejemplo

Java

// Java Program to Create Password Protected Zip File
 
// Importing all input output classes
import java.io.*;
// Importing java.nio utility package API
// used for manipulating files and directories
// mostly working on Path object
import java.nio.file.*;
// Importing all zip classes from
// java.util package
import java.util.zip.*;
 
// Class
// Main class
public class ZipFile {
 
// Method 1
 // Creating an existing file as a zip file
    private static void zipFile(String filePath) {
         
        // Try block  to check if any exception occurs
        try {
 
            // Creating an object of File type
            // getting filePath by passing as an argument
            File file = new File(filePath);
 
            // Getting the name of the above file
            // as an ZIP format
            String zipFileName = file.getName().concat(".zip");
             
            // Creating FileOutputStream object and passing the
            // zip file as an argument
            FileOutputStream fos = new FileOutputStream(zipFileName);
 
            // Creating sn object of FileOutputStream and
            // passing the above object as an argument
            ZipOutputStream zos = new ZipOutputStream(fos);
             
            zos.putNextEntry(new ZipEntry(file.getName()));
  
            // Writing the ZipEntry to stream is not enough
            // as we need to write its content as well
            // using the putNextEntry() method
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
            zos.write(bytes, 0, bytes.length);
             
            // ZipFile can only hold 1 entry stream at a go, &
            // if another entry is to be passed then
            // current entry stream has to be closed closeEntry
 
            // Closing the current entry stream
            // using the closeEntry() method
            zos.closeEntry();
 
            // Closing the entire stream completely
            zos.close();
 
        // If file does not find then it will return the file does not exist
        }
         
        // Catch block 1
        // Catch block to handle FieNotFoundException
        catch (FileNotFoundException ex) {
 
            // Print and display message
            System.err.format("The file does not exist", filePath);
        }
 
        // Catch block 2
        // Catch block to handle input output exception
        catch (IOException ex) {
 
            // Print and display message 
            System.err.println("ERROR: " + ex);
        }
    }
  
    // Method 2
    // Main driver method
    public static void main(String[] args) {
         
        String filePath = args[0];
         
        // Calling the above method 1
        zipFile(filePath);
 
    }
}

Método 2: enfoque eficiente

Procedimiento:

  1. Primero, cree una lista de archivos para agregar al archivo ZIP y
  2. Especificando la ruta, puede agregarla a la lista.

Ejemplo

Java

// Java Program to Create Password Protected Zip File
 
// Importing required  libraries
// Here, lingala is the name of men
// who created zip4j library
import java.io.File;
import java.util.ArrayList;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
 
// Class
// To create password protected ZIP file
public class GFG {
 
    // Main driver method
    public static void main(String[] args) {
             
           // Try block to check if any exception occurs
           try {
  
                  // Creating encryption zipParameters
                  // for password protection
                  ZipParameters zipParameters = new ZipParameters();
  
                  // Setting encryption files
                  zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
                  zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
  
                  // Setting encryption of files to true
                  zipParameters.setEncryptFiles(true);
  
                  // Setting encryption method
                  zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
                   
                  // Set the key strength
                  zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
  
                  // Set the password
                  zipParameters.setPassword("password");
  
              
                  // *********CREATE ZIP FILE***************
  
                  //Zip file name
                  String destinationZipFilePath = "D:/myZipFile.zip";
                   
                  // Creating ZIP file
                  ZipFile zipFile = new ZipFile(destinationZipFilePath);
  
                  // Creating list of files to be added to ZIP file
                  ArrayList<File> list = new ArrayList<File>();
                  //Add SPECIFIC  files
                  list.add(new File("D:/myFile1.txt"));
                  list.add(new File("D:/myFile2.txt"));
  
                  // Pass and ZIP parameters
                  // for Zip file to be created
                  zipFile.addFiles(list, zipParameters);
  
                  // Print the destination in the local directory
                  // where ZIP file is created
                  System.out.println("Password protected Zip file"
                               + "have been created at "  + destinationZipFilePath);
             
            // Catch block to handle the exceptions
           } catch (ZipException e) {
 
                  // Print the exception and line number
                  // where tit occurred 
                  e.printStackTrace();
           }
    }
}

Salida: Después de ejecutar este código, se ha creado un archivo Zip protegido con contraseña de archivos específicos en D:/myZipFile.zip.

Explicación de salida: 

Antes de la ejecución en la imagen de arriba, podemos ver 1 directorio y 2 archivos llamados GeeksForGeeks.txt y  krishana_97

Ahora, después de la ejecución, podemos ver el nuevo archivo zip creado. Este archivo zip es el archivo zip protegido por contraseña. Tienes que dar la contraseña correcta para acceder al archivo dentro de este zip. 

Publicación traducida automáticamente

Artículo escrito por krishna_97 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *