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?

2
  • As the zipfile module's documentation 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
    Commented Oct 6, 2021 at 18:20
  • I would suggest doing it the way described in this answer.
    – martineau
    Commented Oct 6, 2021 at 18:31

1 Answer 1

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)
2
  • 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
    Commented Oct 7, 2021 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
    Commented Oct 7, 2021 at 17:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.