I created a simple code (and a test zip file with the password cat_666) to check if the entered password is correct (using zip4j library)
var filechooser = new FileChooser();
filechooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("zipfile", "*.zip"));
var archive = filechooser.showOpenDialog(null);
try {
if (new ZipFile(archive).isEncrypted()) {
System.out.println(correctPassword(archive, "cat.666"));
System.out.println(correctPassword(archive, "cat_666"));
} else {
System.out.println("Without password");
}
} catch (ZipException ex) {
}
public static String correctPassword(File archive, String password) {
try {
var fileHeaders = new ZipFile(archive).getFileHeaders();
var smallest_size = fileHeaders.stream().map(f -> f.getComssedSize()).min(Long::compare).get();
var smallest_file = fileHeaders.stream().filter(f -> f.getCompressedSize() == smallest_size).findFirst().get();
new ZipFile(archive, password.toCharArray()).extractFile(smallest_file, "/tmp_directory");
FileUtils.deleteDirectory(new File("C:/tmp_directory"));
} catch (ZipException ex) {
return password + " is not correct";
} catch (IOException ex) {
System.out.println("bad path");
}
return password + " is correct";
}
Although it works, there are three drawbacks.
I call the method only when the file is encrypted. However, this validation alone requires a try catch, so it is there twice in the result.
Password verification is probably not possible without extraction. Fortunately, it is possible to extract even one file and the size can be found even without a password, so I can extract the smallest file. However, its selection is unnecessarily complicated.
By extracting the file, I want to delete it afterwards, for which it has to add another Commons-io library there.
Can it be simplified please?
Thank you
UPDATE:
I managed to partially solve the second problem to extract the smallest file to find the password. However, the code is unnecessarily complex.
Since extracting at least one file is obviously necessary, it's not worth solving the third problem (library size is negligible)
And the first problem is probably only an aesthetic detail, which I would ignore.