简体   繁体   English

如何使用 zipfile 模块创建密码保护的 zipfile

[英]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?我有一个名为important.zip的受密码保护的 zip 文件,它包含 1 个文件夹,zip 文件的密码是 123,但是当我使用错误的密码运行此代码时,该文件夹仍然被提取,我该如何制作如果没有正确的密码,我无法提取文件夹?

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

The zipfile module checks for this as well as it can it returns a 'Bad password for file' when the password doesn't match. zipfile 模块会对此进行检查,并在密码不匹配时返回“Bad password for file”。

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.因为 ZIP 文件中的每个文件都可以有自己不同的密码,这是将文件添加到存档时给出的密码。

I think that your zip file was not password protected as zipfile accepts a password when extracting for files that aren't password protected.我认为您的 zip 文件不受密码保护,因为 zipfile 在提取不受密码保护的文件时接受密码。 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:为避免在提供密码时提取不受密码保护的 zip 文件,请检查文件是否受密码保护:

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?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.请注意,每个文件都有自己的密码,因此如果使用不同的密码加密,某些文件可能无法提取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM