Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create password protected zip file Python [duplicate]

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")
like image 765
Tahreem Iqbal Avatar asked Nov 29 '17 07:11

Tahreem Iqbal


People also ask

Can you password protect a whole zip file?

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.


2 Answers

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')
like image 66
Jonas Byström Avatar answered Sep 30 '22 23:09

Jonas Byström


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.

like image 44
Galen Avatar answered Sep 30 '22 23:09

Galen