June 24, 2022

Creating Password Protected Zip File in Java

In the post how to zip files in Java and how to zip a folder in Java we have already seen how to compress files and directories in Java. In this post we’ll see how to create a password protected zip file in Java and how to unzip a password protected compressed file.

Password protected zip file support in Java

With in the java.util.zip package which includes classes for compressing and decompressing files there is no support for creating password protected zip files therefore Zip4j library is used for the purpose.

Jar that is needed for creating password protected zip files- zip4j_1.3.2.jar can be downloaded from this location- http://www.lingala.net/zip4j/download.php.

Though Zip4j library is a bit old and there are other available options but in my opinion this library is still the best bet for creating password protected zip files.

Password protected zip file Java example

Two examples given here cover the following scenarios-

  • Where you have separate files which you can add to folder then compress and password protect it. See example.
  • When you want to compress a directory and password protect it. See example.

With in these examples we’ll also see how to unzip a password protected file.

Add files to folder and compress

If you want to compress separate files then add them to an ArrayList and pass that list along with the parameters for compression and encryption to get a password protected zipped file. In the example, unZipPasswordProtectedFiles() method unzips the password protected zipped file.

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;

public class PwdZipFiles {

  public static void main(String[] args) {
    PwdZipFiles pwdZipFiles = new PwdZipFiles();
    String zipFilePath = "F:\\ZipTest\\Final.zip";
    pwdZipFiles.compressFilesWithPwd(zipFilePath);
    pwdZipFiles.unZipPasswordProtectedFiles(zipFilePath);
  }
	
  public void compressFilesWithPwd(String zipFilePath) {
    // Zipped folder name
    try {
      ZipFile zipFile = new ZipFile(zipFilePath);
      ArrayList<File> filesToAdd = new ArrayList<>();
      // Add files which are to be compressed to the array list
      filesToAdd.add(new File("F:\\ZipTest\\Shop Implementation.docx"));
      filesToAdd.add(new File("F:\\ZipTest\\Test.txt"));
      filesToAdd.add(new File("F:\\Test\\sample.txt"));
			
      // Initiate Zip Parameters 
      ZipParameters parameters = new ZipParameters();
      // set compression method to deflate compression
      parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); 
      parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
      parameters.setEncryptFiles(true);
      parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
      parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
      // Setting password
      parameters.setPassword("password");	        
      zipFile.addFiles(filesToAdd, parameters);

    } catch (ZipException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }				
  }
	
  public void unZipPasswordProtectedFiles(String zipFilePath){
    // Get unzip file path by removing .zip from the zipped file name
    String unZipFilePath = zipFilePath.substring(0, zipFilePath.lastIndexOf("."));;	
    try {
      ZipFile zipFile = new ZipFile(zipFilePath);
      // provide password if encrypted
      if(zipFile.isEncrypted()){
        zipFile.setPassword("password");
      }
      // unzip
      zipFile.extractAll(unZipFilePath);
    } catch (ZipException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Zip whole directory with password protection

If a directory structure has to be compressed recursively then you can do it as given here. Directory structure which is compressed in the example is as given below.

password protected zip file
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

public class PwdZipFiles {

  public static void main(String[] args) {
    PwdZipFiles pwdZipFiles = new PwdZipFiles();
    // Directory to be zipped
    String dirPath = "F:\\ZipTest";
    String zippedDirPath = "F:\\ZipTest\\ZippedDir.zip";
    pwdZipFiles.compressDirWithPwd(dirPath, zippedDirPath);
    pwdZipFiles.unZipPasswordProtectedFiles(zippedDirPath);

  }
	
  public void compressDirWithPwd(String dirPath, String zippedDirPath) {
    
    try {
      ZipFile zipFile = new ZipFile(zippedDirPath);
      
      // Initiate Zip Parameters 
      ZipParameters parameters = new ZipParameters();
      // set compression method to deflate compression
      parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); 
      parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
      parameters.setEncryptFiles(true);
      parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
      parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
      // Setting password
      parameters.setPassword("password");	        
      zipFile.addFolder(dirPath, parameters);

    } catch (ZipException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }				
  }
	
  public void unZipPasswordProtectedFiles(String zipFilePath){
    // Get unzip file path by removing .zip from the zipped file name
    String unZipFilePath = zipFilePath.substring(0, zipFilePath.lastIndexOf("."));;
    try {
      ZipFile zipFile = new ZipFile(zipFilePath);
      // provide password if encrypted
      if(zipFile.isEncrypted()){
        zipFile.setPassword("password");
      }
      // unzip
      zipFile.extractAll(unZipFilePath);
    } catch (ZipException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

You can see how unzipping a zipped directory requires a password.

password protected zip file java

That's all for the topic Creating Password Protected Zip File in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment