Python - zipfile:如何为 zipfile 设置密码? [英] Python - zipfile: how to set a password for a zipfile?

查看:153
本文介绍了Python - zipfile:如何为 zipfile 设置密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 (sav.zip) 中有一个 zip 文件,我正在尝试为其设置密码:

I have a zipfile in (sav.zip) and I'm trying to set a Password for it:

zf = zipfile.ZipFile("sav.zip")

zf.setpassword("1234")

但是...我得到一个类型错误:预期的字节数,得到了 str

but... I get a TypeError: expected Bytes, got str

我的错误在哪里?

推荐答案

文档中没有提到,但是在 Python 3 上,密码应该是 bytes,而不是 str.所以:

It is not mentioned in the documentation, but on Python 3, the password should be bytes, not str. So:

zf.setpassword(b"1234")

注意密码用于阅读,不能写!请参阅 Python 3 中 ZipFile.open 的文档字符串.

Note that the password is only used for reading, not writing! See the docstring for ZipFile.open in Python 3.

ZipFile 类可以读取pkzip 2.0"加密,这被认为不是很强(它有 已知弱点 [pdf]).这可能是编写它们当前(从 Python 2.7.13 和 3.6 开始)没有在 Python 中实现的原因.

The ZipFile class can read "pkzip 2.0" encryption, which is not considered very strong (it has known weaknesses [pdf]). That could probably be the reason that writing them is not currently (as of Python 2.7.13 and 3.6) implemented in Python.

注意: zipfile 上的密码所提供的保护可能不是很强,这取决于您想将其用于什么目的.攻击者可以例如替换 zipfile 中受密码保护的条目不知道密码!见例如这个答案在 security.stackexchange 上.

Note: The protection afforded by a password on a zipfile might not very strong, depending on what you want to use it for. An attacker can e.g. replace a password-protected entry in a zipfile without knowing the password! See e.g. this answer on security.stackexchange.

注 2: 更新版本的 e.g.winzip 可以使用 AES 来加密压缩文件的内容.AFAIK,Python 无法读取这些内容.

Note2: More recent versions of e.g. winzip can use AES to encrypt the contents of zipped files. AFAIK, Python cannot read those.

这篇关于Python - zipfile:如何为 zipfile 设置密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆