1

I'm trying to get a specific file inside a Zip Archive, extract it, Encrypt it, and then get it back inside the archive replacing the origial one.

here's what I've tried so far..

public static boolean encryptXML(File ZipArchive, String key) throws ZipException, IOException, Exception {
    ZipFile zipFile = new ZipFile(ZipArchive);
    List<FileHeader> fileHeaderList = zipFile.getFileHeaders();
    for (FileHeader fh : fileHeaderList)
    {
        if (fh.getFileName().equals("META-INF/file.xml"))
        {
            Path tempdir = Files.createTempDirectory("Temp");
            zipFile.extractFile(fh, tempdir.toString());
            File XMLFile = new File(tempdir.toFile(), fh.getFileName());

            // Encrypting XMLFile, Ignore this part

            // Here, Replace the original XMLFile inside ZipArchive with the encrypted one <<<<<<<<

            return true;
        }
    }
    return false;
}

I stuck at the replacing part of the code is there anyway I can do this without having to extract the whole Zip Archive?

Any help is appreciated, thanks in advance.

Aboud Zakaria
  • 567
  • 9
  • 25

3 Answers3

1

Not sure if this will help you as you are using a different library but the solution in ZT Zip would be the following.

ZipUtil.unpackEntry(new File("/tmp/demo.zip"), "foo.txt", new File("foo.txt"));
// encrypt the foo.txt
ZipUtil.replaceEntry(new File("/tmp/demo.zip"), "foo.txt", new File("foo.txt"));

This will unpack the foo.txt file and then after you encrypt it you can replace the previous entry with the new one.

toomasr
  • 4,731
  • 2
  • 33
  • 36
0

You may use the ZipFilesystem (as of Java 7) as explained in the Oracle documentation to read/write within a zip file as if it were its own file system.

However, on my machine, this unpacks and re-packs the zip file under the hood anyway (tested with 7 and 8). I am not sure if there is a way to reliably change zip files like you describe.

llogiq
  • 13,815
  • 8
  • 40
  • 72
0

Bingo!

I'm able to do it that way

ZipParameters parameters = new ZipParameters();
parameters.setIncludeRootFolder(true);
zipFile.removeFile(fh);
zipFile.addFolder(new File(tempdir.toFile(), "META-INF"), parameters);
Aboud Zakaria
  • 567
  • 9
  • 25