Create password protected zip file Python [duplicate]

拟墨画扇 提交于 2019-12-22 08:34:21

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/47547590/create-password-protected-zip-file-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!