7

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")

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

Where's my mistake?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 4
    Please read [the documentation for `ZipFile.setpassword()`](https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.setpassword). It doesn't do what you think it does. – ChrisGPT was on strike Apr 16 '17 at 17:30
  • try this `zf.setpassword(b"1234")`, basically password param should be bytes instead of string. – Aren Hovsepyan Apr 16 '17 at 17:31
  • 1
    By "set a password" do you want to convert it to a password-protected zipfile, or is it already password-protected and you want to set the password for reading? – tdelaney Apr 16 '17 at 17:46

1 Answers1

21

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

zf.setpassword(b"1234")

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

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.

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.

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

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
  • 6
    I don't think so: [`ZipFile.setpassword(pwd)`](https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.setpassword) sets "_pwd_ as default password to extract encrypted files". It doesn't have anything to do with creating password-protected zip files. – ChrisGPT was on strike Apr 16 '17 at 17:36
  • Edited to reflect that. – Roland Smith Apr 16 '17 at 17:37
  • Thank you - it was just the 'b', problem solved :-) –  Apr 16 '17 at 21:14
  • 3
    ZipFile library can't set password for a zip file, you have to use pyminizip: see https://stackoverflow.com/questions/47547590/create-password-protected-zip-file-python?rq=1 – Minions May 20 '19 at 16:12
  • 1
    If you want to zip multiple in-memory files with a password, use pyzipper. – goodgrief Aug 17 '21 at 10:02