'How to create a password protected zipfile using the zipfile module

I have a password protected zip-file called important.zip, it contains 1 folder, the password for the zip-file is 123, however when I use run this code with a wrong password the folder is still getting extracted, how can I make it that I can not extract the folder without the correct password?

import zipfile
zFile=zipfile.ZipFile("important.zip")
try:
    zFile.extractall(pwd="oranges")
except Exception as e:
    print e


Solution 1:[1]

The zipfile module checks for this as well as it can it returns a 'Bad password for file' when the password doesn't match.

But it does this on a per file basis. As each file in a ZIP file can have its own different password which was the password that was given when the file was added to the archive.

I think that your zip file was not password protected as zipfile accepts a password when extracting for files that aren't password protected. It does not report an error when the password is not used because the file was not password protected.

To avoid extracting a zip file that is not password protected when a password is provided one has check if the files are password protected:

import zipfile

def all_files_are_password_protected(zf):
    return all(zinfo.flag_bits & 0x1 for zinfo in zf.infolist())

zFile=zipfile.ZipFile("important.zip")
try:
    if all_files_are_password_protected(zFile):
        zFile.extractall(pwd="oranges")
except Exception as e:
    import traceback
    traceback.print_exc()

Based on:

zf = zipfile.ZipFile(archive_name)
for zinfo in zf.infolist():
    is_encrypted = zinfo.flag_bits & 0x1 
    if is_encrypted:
        print '%s is encrypted!' % zinfo.filename

From How to check if a zip file is encrypted using python's standard library zipfile?

Note that every file has their own password so some files might fail to be extracted if encrypted with a different password.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1