Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 352
Mahmoud Abdel-Rahman Avatar asked Nov 06 '22 07:11

Mahmoud Abdel-Rahman


1 Answers

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'))
like image 100
Mehrdad Bakhtiari Avatar answered Nov 14 '22 22:11

Mehrdad Bakhtiari