Python unzip AES-128 encrypted file

Question:

Is there a way to decompress an AES-128 encrypte file directly with python, since ZipFile throws a Bad Password error. If i use 7zip it works, so the password is correct, but then again 7zip needs to be installed as a dependency.

What i tried:

from ZipFile import ZipFile
zip = ZipFile('test.zip')
zip.extractall(pwd='password')

This throws the Bad Password exception.

Checking the file with 7zip

7z l -slt test.zip

This returns:

Encrypted = +
Method = pkAES-128 Deflate
Asked By: rabra

||

Answers:

The zipfile module from the Python standard library supports only CRC32 encrypted zip files (see here: http://hg.python.org/cpython/file/71adf21421d9/Lib/zipfile.py#l420 ). So, there is no way around some 3rd party dependency.

The easiest way would be to just install 7zip and call the commandline utility 7z using the subprocess module from the standard lib:

import subprocess
subprocess.call(["7z", "x", "-ppassword", "test.zip"])

Another option would be the python module “PyLzma” which can also handle AES encrypted 7zip archives: https://github.com/fancycode/pylzma . It doesn’t directly support decrypting classic zip files but you could use its routines to write your own decompressor function.

Answered By: Bernhard Kausler

You can use the library pyzipper: https://github.com/danifus/pyzipper. It works nearly the same as Python’s zipfile:

import pyzipper

with pyzipper.AESZipFile('my_archive.zip') as f:
    f.pwd = b'myPassword'
    print(f.infolist())
    file_content = f.read('testfile.txt')
Answered By: Fabian Heller

You can use stream-unzip to decrypt AES encrypted ZIP files (full disclosure: written by me)

from stream_unzip import stream_unzip

def zipped_chunks(filename):
    with open(filename, 'rb') as f:
        while chunk := f.read(65536):
           yield chunk

for file_name, file_size, unzipped_chunks in stream_unzip(zipped_chunks('test.zip'), password=b'password'):
    for chunk in unzipped_chunks:
        print(chunk)
Answered By: Michal Charemza
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.