Monday, 4 January 2016

Create Password Protected zip file in Java

In this post, I am going to explain how to create password-protected file in Java. I am going to use Zip4j, a java open-source library to handle Zip files.

Following are the Key features of Zip4j
a.   Create, Add, Extract, Update, Remove files from a Zip file
b.   Read/Write password protected Zip files
c.    Supports AES 128/256 Encryption
d.   Supports Standard Zip Encryption
e.   Supports Zip64 format
f.     Supports Store (No Compression) and Deflate compression method
g.   Create or extract files from Split Zip files (Ex: z01, z02,...zip)
h.   Supports Unicode file names
i.      Progress Monitor

Following step-by-step procedure explains how to create a password protected zip file using Zip4j library.

Step 1: Instantiate ZipFile instance.
ZipFile zipFile = new ZipFile(zipFileName);

Step 2: Define list of files to zip.
List<String> filesToZip = new ArrayList<String> ();

Step 3: Instantiate ZipParameters. Following are some of the properties associated with ZipParameters used while zipping files.
1.   Compression method
2.   Compression level
3.   Whether to encrypt files or not
4.   Encryption method
5.   Whether to read hidden files or not
6.   Secret key length etc.,

ZipParameters zipParameters = new ZipParameters();

Step 4: Set Compression type.
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);

Step 5: Set Compression level. Following constants represent the compression levels supported by Zip4j.

static final int DEFLATE_LEVEL_FASTEST = 1;
static final int DEFLATE_LEVEL_FAST = 3;
static final int DEFLATE_LEVEL_NORMAL = 5;
static final int DEFLATE_LEVEL_MAXIMUM = 7;
static final int DEFLATE_LEVEL_ULTRA = 9;

zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

Step 6: Set encryptFiles to true.

zipParameters.setEncryptFiles(true);

Step 7: Select the Encryption method to encrypt files.

Following constants represent the encryption method.
static final int ENC_NO_ENCRYPTION = -1;
static final int ENC_METHOD_STANDARD = 0;
static final int ENC_METHOD_AES = 99;

zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);

Step 8: Since I am going to use AES algorithm to encrypt files, I need to set the key length for it. Following constants specifies the AES key length.

static final int AES_STRENGTH_128 = 0x01;
static final int AES_STRENGTH_192 = 0x02;
static final int AES_STRENGTH_256 = 0x03;

zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);

Step 9: Set the password for the zip file. Always use password as character array. Following link explains, why to use password as character array than string.

zipParameters.setPassword(password);


Following is the complete working application.
import java.io.File;
import java.util.ArrayList;
import java.util.List;

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 FileUtils {
 /**
  * 
  * @param zipFileName
  * @param filesToZip
  * @param password
  *            Password for zip file
  * @return true if files are zipped successfully, else false.
  */
 public static boolean zipFiles(String zipFileName, List<File> filesToZip,
   char[] password) {

  try {
   /* Instantiate ZipFile */
   ZipFile zipFile = new ZipFile(zipFileName);

   /* Instantiate ZipParameters */
   ZipParameters zipParameters = new ZipParameters();

   /* Set compression type */
   zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);

   /* Set Compression level */
   zipParameters
     .setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

   /* Set encryptFiles to true */
   zipParameters.setEncryptFiles(true);

   /* Select the Encryption method to encrypt fies */
   zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);

   /* Set AES key length */
   zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);

   /* Set the password for zip file */
   zipParameters.setPassword(password);

   zipFile.addFiles(new ArrayList<>(filesToZip), zipParameters);

  } catch (ZipException e) {
   e.printStackTrace();
   return false;
  }

  return true;
 }
}

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileUtilsTest {
 public static void main(String ptr[]) {
  String zipFileName = "/Users/harikrishna_gurram/ptr.zip";
  List<File> filesToZip = new ArrayList<>();
  char[] password = { 'p', 'T', 'r', '5', '1', '4' };

  filesToZip.add(new File("/Users/harikrishna_gurram/data.txt"));
  filesToZip.add(new File("/Users/harikrishna_gurram/doc_template.txt"));
  filesToZip.add(new File("/Users/harikrishna_gurram/hadoop_commands.txt"));

  boolean isFilesZipped = FileUtils.zipFiles(zipFileName, filesToZip, password);
  
  if(isFilesZipped){
   System.out.println("Files are zipped successfully");
  }else{
   System.out.println("Files zipping failed");
  }
 }
}




1 comment:

  1. i tried to execute this but while opening the zip file using winRAR it is not prmpting for password

    ReplyDelete