I'm given a zip archive that is protected by a password,
And I need to write a piece of code that would decrypt the archive to a byte []
without saving intermediate results to a file system,
So far I've found that standard java JDK does not allow to perform operations like this,
And also that there is a library Zip4j
, but it doesn't seem to allow decryption of file directly to byte[]
but it writes result to a file system instead,
If would really really appreciate any help,
Thanks
You can do this with zip4j. Here is an example from the documentation:
import net.lingala.zip4j.io.inputstream.ZipInputStream;
import net.lingala.zip4j.model.LocalFileHeader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class ZipInputStreamExample {
public void extractWithZipInputStream(File zipFile, char[] password) throws IOException {
LocalFileHeader localFileHeader;
int readLen;
byte[] readBuffer = new byte[4096];
try (ZipInputStream zipInputStream = new ZipInputStream(fileInputStream, password)) {
while ((localFileHeader = zipInputStream.getNextEntry()) != null) {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
while ((readLen = zipInputStream.read(readBuffer)) != -1) {
outputStream.write(readBuffer, 0, readLen);
}
}
}
}
}
}
You can then do outputStream.toByteArray()
on each entry to get the byte content of that entry in the zip.