I want to create password protected Gzip file in java. Is there any commons jar for that.
I tried with GzipParameters, but there is no options for password.
Thanks in advance.
I want to create password protected Gzip file in java. Is there any commons jar for that.
I tried with GzipParameters, but there is no options for password.
Thanks in advance.
Refer to the following library https://github.com/srikanth-lingala/zip4j
Maven Dependency
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>2.9.0</version>
</dependency>
Sample Code
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionLevel;
import net.lingala.zip4j.model.enums.EncryptionMethod;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ZipAndUnZipFiles {
public static void main(String[] args) {
List<File> files = new ArrayList<File>();
files.add(new File("C:\\code\\demo\\aFile.txt"));
files.add(new File("C:\\code\\demo\\bFile.txt"));
try {
zip(files, "C:\\code\\demo\\compressed.zip", "password123");
} catch (ZipException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
unZip(new File("C:\\code\\demo\\compressed.zip"), "password123", "C:\\code\\demo\\extracted\\");
} catch (ZipException e) {
e.printStackTrace();
}
}
private static void zip( List<File> filesToAdd , String outputZipFilePath, String password) throws IOException {
ZipParameters zipParameters = new ZipParameters();
zipParameters.setEncryptFiles(true);
zipParameters.setCompressionLevel(CompressionLevel.HIGHER);
zipParameters.setEncryptionMethod(EncryptionMethod.AES);
ZipFile zipFile = new ZipFile(outputZipFilePath, password.toCharArray());
zipFile.addFiles(filesToAdd, zipParameters);
zipFile.close();
}
private static void unZip(File zipFileInput, String password, String destinationDirectory) throws ZipException {
ZipFile zipFile = new ZipFile(zipFileInput, password.toCharArray());
zipFile.extractAll(destinationDirectory);
}
}
The gzip format does not have any sort of encryption as an option for that format. You would simply encrypt the .gz file with, for example, gpg.