user2837459
user2837459

Reputation: 33

check password correction in zip file using zip4j

Is any way to check password correction in zip file using zip4j library in Java without trying to extract zip?

Regards

Upvotes: 2

Views: 4623

Answers (1)

Srikanth
Srikanth

Reputation: 1956

Unfortunately, this is not directly possible with the current version of Zip4j. I am currently rewriting Zip4j and I will include this feature in the next release.

However, with the current version, there is a workaround for this. Have a look at the code below. You can try to read zip file into memory. For an AES encrypted zip file, you will immediately get a ZipException and with a code ZipExceptionConstants.WRONG_PASSWORD. For Standard zip encryption, verifying password is not quite easy. Zip4j will throw a CRC exception if the input password is wrong, which most probably means a wrong password, but can also be a corrupt data in zip file

I know that the code below is not a clean code, but unfortunately this is the only way at the moment. Next version of Zip4j will include a neat feature to verify password.

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.exception.ZipExceptionConstants;
import net.lingala.zip4j.model.FileHeader;

public class VerifyPassword {

    public static void verify() {
        try {
            ZipFile zipFile = new ZipFile(new File("myZip.zip"));
            if (zipFile.isEncrypted()) {
                zipFile.setPassword(new char[] {'t', 'e', 's', 't'});
            }
            List<FileHeader> fileHeaders = zipFile.getFileHeaders();

            for(FileHeader fileHeader : fileHeaders) {
                try {
                    InputStream is = zipFile.getInputStream(fileHeader);
                    byte[] b = new byte[4 * 4096];
                    while (is.read(b) != -1) {
                        //Do nothing as we just want to verify password
                    }
                    is.close();
                } catch (ZipException e) {
                    if (e.getCode() == ZipExceptionConstants.WRONG_PASSWORD) {
                        System.out.println("Wrong password");
                    } else {
                        //Corrupt file
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                     System.out.println("Most probably wrong password.");
                     e.printStackTrace();
                }
            }

        } catch (Exception e) {
            System.out.println("Some other exception occurred");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        verify();
    }

}

Upvotes: 3

Related Questions