HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Password Protected Zip Files

Java Create Password Protected Zip File

This Java tutorial covers creating password-protected zip files using a very useful library zip4j.

Java, by default, does not provide any support for password protection for file; though it has very good API support for creating/extracting zip files.

There are some other useful libraries out there, which are equally good and sometimes better than zip4j, but they use some native code as well, which makes their usage platform dependent to some extent. Zip4j uses completely java code without any support of native code, and that’s what makes it a better fit for me.

1. Zip4j

Zip4j provides following features:

  • Create, Add, Extract, Update, Remove files from a Zip file
  • Read/Write password protected Zip files
  • Supports AES 128/256 Encryption
  • Supports Standard Zip Encryption
  • Supports Zip64 format
  • Supports Store (No Compression) and Deflate compression method
  • Create or extract files from Split Zip files (Ex: z01, z02,…zip)
  • Supports Unicode file names
  • Progress Monitor

Adding Zip4j into Project

Use its maven dependency into the project.

<dependency>
    <groupId>net.lingala.zip4j</groupId>
    <artifactId>zip4j</artifactId>
    <version>2.6.1</version>
</dependency>

2. Creating password protected zip file

The given below is a very simple example of creating a password protected zip file using the library. See its Git page for extended options and more examples.

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 CreatePasswordProtectedZipExample
{
	public static void main(String[] args) 
	{
		try {
			//This is name and path of zip file to be created
			ZipFile zipFile = new ZipFile("C:/temp/test.zip");
			
			//Add files to be archived into zip file
			ArrayList<File> filesToAdd = new ArrayList<File>();
			filesToAdd.add(new File("C:/temp/test1.txt"));
			filesToAdd.add(new File("C:/temp/test2.txt"));
			
			//Initiate Zip Parameters which define various properties
			ZipParameters parameters = new ZipParameters();
			parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression
			
			//DEFLATE_LEVEL_FASTEST 	- Lowest compression level but higher speed of compression
			//DEFLATE_LEVEL_FAST 		- Low compression level but higher speed of compression
			//DEFLATE_LEVEL_NORMAL 	- Optimal balance between compression level/speed
			//DEFLATE_LEVEL_MAXIMUM 	- High compression level with a compromise of speed
			//DEFLATE_LEVEL_ULTRA 		- Highest compression level but low speed
			parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); 
			
			//Set the encryption flag to true
			parameters.setEncryptFiles(true);
			
			//Set the encryption method to AES Zip Encryption
			parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
			
			//AES_STRENGTH_128 - For both encryption and decryption
			//AES_STRENGTH_192 - For decryption only
			//AES_STRENGTH_256 - For both encryption and decryption
			//Key strength 192 cannot be used for encryption. But if a zip file already has a
			//file encrypted with key strength of 192, then Zip4j can decrypt this file
			parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
			
			//Set password
			parameters.setPassword("howtodoinjava");
			
			//Now add files to the zip file
			zipFile.addFiles(filesToAdd, parameters);
		} 
		catch (ZipException e) 
		{
			e.printStackTrace();
		}
	}
}

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. pintu

    March 30, 2018

    Hi Lokesh,

    Thanks for sharing useful example.
    i have one requirement in my project like i need to send a mail with attached zipped password protected file.
    i am using JavaMailSenderImpl & MimeMessageHelper to send a TXT, CSV & XML file in mail but now client requested to send in password protected zipped file.
    i am trying to use your code but problem is MimeMessageHelper dose not allow to attach zipped file.
    did lot of search but not able to come to the Solution.
    could you please guide here if it possible ASAP.

    Note :- i already have generated file in my application(File type) just need to zipped with password and send to mail.

    • CAC

      March 27, 2020

      Hi have u found the solution for this?

  2. Isa

    December 9, 2017

    Is there a program to decode, thank you very much

    • Lokesh Gupta

      December 11, 2017

      I guess… no.

  3. RAM

    May 1, 2016

    Hi,
    Whether this can be supported in java1.4? Are we able to do this password protected in Java 1.4 version. Kindly share if any example is there

    • Lokesh Gupta

      May 1, 2016

      I have not tried with 1.4 – I have no plan to find and install 1.4 as of now. Please try and share with us.

  4. Pankaj Jain

    September 29, 2015

    Hi there,

    Very good example with proper comments.
    Can you please help me making a “Exiting Zip file” password protected?
    Thanks in advance!!

  5. Himansu

    June 25, 2015

    Hi Lokesh,
    Again very clean and simple example. zip4j has a overloaded setpassword() with char[] to avoid immutable property of string.

    Regards,
    Himansu

    • Lokesh Gupta

      June 25, 2015

      Good catch. Thanks for sharing.

Comments are closed on this article!

Search Tutorials

Java IO

  • Java IO Introduction
  • Java How IO works?
  • Java IO vs NIO
  • Java Create File
  • Java Write to File
  • Java Append to File
  • Java Read File
  • Java Read File to String
  • Java Read File to Byte[]
  • Java Make File Read Only
  • Java Copy File
  • Java Copy Directory
  • Java Delete Directory
  • Java Current Working Directory
  • Java Read/Write Properties File
  • Java Read File from Resources
  • Java Read File from Classpath
  • Java Read/Write UTF-8 Data
  • Java Check if File Exist
  • Java Create Temporary File
  • Java Write to Temporary File
  • Java Delete Temporary File
  • Java Read from Console
  • Java Typesafe input using Scanner
  • Java Password Protected Zip
  • Java Unzip with Subdirectories
  • Java Generate SHA/MD5
  • Java Read CSV File
  • Java InputStream to String
  • Java String to InputStream
  • Java OutputStream to InputStream
  • Java InputStreamReader
  • Java BufferedReader
  • Java FileReader
  • Java LineNumberReader
  • Java StringReader
  • Java FileWriter
  • Java BufferedWriter
  • Java FilenameFilter
  • Java FileFilter

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces