1

I am trying to send a password protected zip file as a base64 string.

data = BytesIO()
zip = zipfile.ZipFile(data, 'w') 
zip.writestr('test.csv', 'Hello, World')
zip.setpassword(b'1234')
zip.close()
b64zip = base64.b64encode(data.getvalue()).decode('utf-8')

This b64zip variable is then parsed as an email attachment.

However, when I try to unzip the zip it doesn't prompt for a password. Was using this thread for reference:  zipfile: how to set a password for a Zipfile?

How can I create a password protected zip file as a base64 string?

martineau
  • 119,623
  • 25
  • 170
  • 301
Matthew
  • 1,461
  • 3
  • 23
  • 49
  • As the `zipfile` module's [documentation](https://docs.python.org/3/library/zipfile.html#module-zipfile) states, it only supports decryption of encrypted files in ZIP archives, and currently cannot create an encrypted file. Calling `setpassword()` only sets a default password to use when extracting encrypted files (and it warns that decryption is extremely slow). You will have to encrypt the files in the ZIP archive by some other means. – martineau Oct 06 '21 at 18:20
  • I would suggest doing it the way described in [this answer](https://stackoverflow.com/a/27443681/355230). – martineau Oct 06 '21 at 18:31

1 Answers1

3

There are some mistakes you made:

  1. You've opened a zip file to write and the zip file path is the data itself.
  2. You are trying to zip data not files which is wrong. You should encrypt data, not compress it.
  3. If you want to compress data write it to TXT file then compress the TXT file.
  4. Try using another compression library like: [pyunpack, Pyzipper, pyminizip, …].

I've solved the problem by using pyminizip library:

import pyminizip as pyzip

data = 'stored data'.encode()
with open(".\\data.txt", "wb") as dt : dt.write(data)
pyzip.compress("data.txt", "", "data.zip", "PASSWORD", 8)
martineau
  • 119,623
  • 25
  • 170
  • 301
ELAi
  • 170
  • 2
  • 8
  • Can we use this method to 1. input a string instead of a file? and 2. output a base64 encoded string instead of a file? – Matthew Oct 07 '21 at 16:05
  • you can't compress a string unless you write it to a file, yes you can write base64 to a TXT file – ELAi Oct 07 '21 at 17:36