'Unable to unzip a .zip file with a password with python zipfile library

I created a zip file with Gnome Archive Manager (Ubuntu OS). I created the zip file with a password and I am trying to unzip it using the zipfile Python library:

import zipfile

file_name = '/home/mahmoud/Desktop/tester.zip'
pswd = 'pass'

with zipfile.ZipFile(file_name, 'r') as zf:
    zf.printdir()
    zf.extractall(path='/home/mahmoud/Desktop/testfolder', pwd = bytes(pswd, 'utf-8'))

When I run this code I get the following error and I am pretty sure that the password is correct. The error is:

File "/home/mahmoud/anaconda3/lib/python3.7/zipfile.py", line 1538, in open
  raise RuntimeError("Bad password for file %r" % name)

RuntimeError: Bad password for file <ZipInfo filename='NegSkew.pdf' compress_type=99 filemode='-rw-rw-r--' external_attr=0x8020 file_size=233252 compress_size=199427>

How can I unzip the file?



Solution 1:[1]

zipfile library doesn't support AES encryption (compress_type=99) and only supports CRC-32 as mentioned in the _ZipDecrypter code (https://hg.python.org/cpython/file/a80c14ace927/Lib/zipfile.py#l508). _ZipDecrypter is called and used right before that particular RuntimeError is raised in ZipFile.open which can be traced from extractall.

You can use pyzipper library (https://github.com/danifus/pyzipper) instead of zipfile to unzip the file:

import pyzipper

file_name = '/home/mahmoud/Desktop/tester.zip'
pswd = 'pass'

with pyzipper.AESZipFile(file_name) as zf:
    zf.extractall(path='/home/mahmoud/Desktop/testfolder', pwd = bytes(pswd, 'utf-8'))

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 Mehrdad Bakhtiari