是否有办法直接用python解压缩AES-128加密文件,因为ZipFile抛出一个坏密码错误。如果我使用7zip,它可以工作,所以密码是正确的,但是7zip需要作为依赖项安装。
What i tried:
from ZipFile import ZipFile
zip = ZipFile('test.zip')
zip.extractall(pwd='password')
这会抛出错误密码异常。
使用7zip检查文件
7z l -slt test.zip
这回报:
Encrypted = +
Method = pkAES-128 Deflate
您可以使用库pyzipper: https://github.com/danifus/pyzipper。它的工作原理与Python的zipfile几乎相同:
import pyzipper
with pyzipper.AESZipFile('my_archive.zip') as f:
f.pwd = b'myPassword'
print(f.infolist())
file_content = f.read('testfile.txt')
Python标准库中的zipfile模块只支持CRC32加密的zip文件(参见这里:http://hg.python.org/cpython/file/71adf21421d9/Lib/zipfile.py#l420)。所以,没有办法绕过一些第三方依赖。
最简单的方法是安装7zip并使用标准库中的subprocess
模块调用命令行实用程序7z
:
import subprocess
subprocess.call(["7z", "x", "-ppassword", "test.zip"])
另一个选项是python模块"PyLzma",它也可以处理AES加密的7zip档案:https://github.com/fancycode/pylzma。它不直接支持解密经典的zip文件,但您可以使用它的例程来编写自己的解压缩函数。
你可以使用stream-unzip来解密AES加密的ZIP文件(完全披露:由我写的)
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)