0

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

Andrey Yaskulsky
  • 2,458
  • 9
  • 39
  • 81
  • Is there a specific reason you can't at least use a temporary file as a plan B? – Thomas May 22 '20 at 09:36
  • You could also have a look at [Apache Commons Compress](https://commons.apache.org/proper/commons-compress/zip.html) which seems to support decrypting zip archives into streams and thus byte streams. – Thomas May 22 '20 at 09:38
  • @Thomas Yes, because I need to send given file to external antivirus service. So the content of the file can be potentially dangerous – Andrey Yaskulsky May 22 '20 at 09:43

1 Answers1

2

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.