Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create and Read password protected ZIP using streams.(Not physical File)

Tags:

zip4j

I need to implement a solution that creates password protected ZIP streams and save to database as a

blob. Also need to read the password protected content from the database read as the stream. This

should not create a physical File. Standard JAVA SDK does not support creating and reading password

protected ZIP. I tried with different solutions all most the available solution creating a physical file.

I found examples with writing/Reading password protected ZIP with ZIP4J

How to password protect a zipped Excel file in Java?

Is it possible to create and read password protected ZIPs with ZIP4j library without creating physical files. ?

Applying a patch to the other available source seems difficult to cater my requirement.

Write a password protected Zip file in Java

like image 454
user3693532 Avatar asked Oct 21 '22 05:10

user3693532


1 Answers

If your intention is protecting the BLOB data in database, why don't you just use javax.crypto.CipherOutputStream/javax.crypto.CipherInputStream?

Reading zip content from BLOB and convert it to stream using ZIP4J is quite complicate, you have to work on file header first...(check the source code of net.lingala.zip4j.unzip.UnzipEngine class)

Writing zip content into memory is easier, here is a example code:

ZipParameters zipParam = new ZipParameters();
zipParam.setSourceExternalStream(true);
//set parameter for encryption... 
zipParam.setEncryptFiles(true);
zipParam.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
zipParam.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
zipParam.setPassword("test123");

ByteArrayOutputStream bo = new ByteArrayOutputStream(256);
ZipOutputStream zout = new ZipOutputStream(bo, new ZipModel());

String[] filenames = new String[]{"1.txt"};
for (int i = 0; i < filenames.length; i++) {
    zipParam.setFileNameInZip(filenames[0]);
    zout.putNextEntry(null, zipParam);
    zout.write(filenames[0].getBytes());//data waiting for compressed...
    zout.closeEntry();
}
zout.finish();
zout.close();

bo.toByteArray();//compressed data of zip file
like image 54
Beck Yang Avatar answered Oct 23 '22 23:10

Beck Yang