I'm using following code to create password protected zip file, from a file uploaded by user, in my Python34 application using zipFile
. But when I open the zip file from windows, it doesn't ask for the password. I will be using the same password to read zip files from python later on. What am I doing wrong?
Here's my code:
pwdZipFilePath = uploadFilePath + "encryptedZipFiles/"
filePath = uploadFilePath
if not os.path.exists(pwdZipFilePath):
os.makedirs(pwdZipFilePath)
#save csv file to a path
fd, filePath = tempfile.mkstemp(suffix=source.name, dir=filePath)
with open(filePath, 'wb') as dest:
shutil.copyfileobj(source, dest)
#convert that csv to zip
fd, pwdZipFilePath = tempfile.mkstemp(suffix=source.name + ".zip", dir=pwdZipFilePath)
with zipfile.ZipFile(pwdZipFilePath, 'w') as myzip:
myzip.write(filePath)
myzip.setpassword(b"tipi")
Can you put a password on a zip file? Windows doesn't have an option to protect your zipped file with a password, so there's no other way but to use third-party tools. You can choose from various trusted software options, such as WinZip, WinRAR, and 7-Zip.
The builtin zipfile
module does not support writing password-encrypted files (only reading). Either you could use pyminizip
:
import pyminizip
pyminizip.compress("dummy.txt", "myzip.zip", "noneshallpass", compression_level)
Or, if you're on Windows/msysgit, and agnostic to the format:
import os
os.system('tar cz dummy.txt | openssl enc -aes-256-cbc -e -k noneshallpass > mypacked.enc')
os.remove('dummy.txt')
os.system('openssl enc -aes-256-cbc -d -k noneshallpass -in mypacked.enc | tar xz')
The documentation for zipfile
indicates that ZipFile.setpassword
sets the "default password to extract encrypted files."
At the very top of the documentation: "It supports decryption of encrypted files in ZIP archives, but it currently cannot create an encrypted file."
Edit: To create a password protected ZIP file, try a package like pyminizip.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With