简体   繁体   中英

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

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();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM