how to check given inputstream(zip file) is password protected or not using java?

I have inputstream of zip file , want to check if this inputstream is password protected or not . I have gone through this How to use zip4j to extract an zip file with password protection.

String source = "folder/source.zip";
String destination = "folder/source/";
String password = "password";

try {
ZipFile zipFile = new ZipFile(source);
if (zipFile.isEncrypted()) {
    zipFile.setPassword(password);
}
zipFile.extractAll(destination);
} catch (ZipException e) {
e.printStackTrace();
}

in this website above solution is given . but i do not have file or file path location. i have only inputstream of zip file can someone tell me how i can check whether given inputstream (zip file) is password protected or not. thanks in advance.

Answer

Sorry, I don’t think there is a library that will do exactly what you want.

  • zip4j ZipFile can only open a File or a String pathname.

  • Java SE ZipFile can only open a File or a String pathname … and doesn’t support encrypted entries.

  • Java SE ZipInputStream does support an InputStream, but doesn’t support encrypted entries.

  • Apache Commons ZipFile does support seekable input streams (and channels), but not InputStream. And it doesn’t understand encrypted entries.

  • Apache Commons ZipInputStream works with any InputStream but it doesn’t understand encrypted entries.


So what are the options?

The simplest option would be to copy the InputStream contents to a temporary file and then use zip4j ZipFile as per the code in your question. When you are finished, delete the temporary file.

In theory, you ought to be able to use Java SE ZipInputStream and scan the entries to check the FileHeader for each file. (Bit zero of the “general purpose bit” field tells you if the file is encrypted.) The problem is that ZipEntry doesn’t expose the information.

However, Apache’s ZipInputStream class (which can read an InputStream!), exposes the general purpose bit field. So this would provide a way to test if any of the files in the ZIP is encrypted. If that is all you need, then you have another possible option.