Python code to create a password encrypted zip file? [duplicate]

跟風遠走 提交于 2019-12-17 07:14:52

问题


What is the Python code to create a password encrypted zip file? I'm fine with using some apt-get'able utilities using system on the command line.


回答1:


To create encrypted zip archive (named 'myarchive.zip') using open-source 7-Zip utility:

rc = subprocess.call(['7z', 'a', '-pP4$$W0rd', '-y', 'myarchive.zip'] + 
                     ['first_file.txt', 'second.file'])

To install 7-Zip, type:

$ sudo apt-get install p7zip-full

To unzip by hand (to demonstrate compatibility with zip utitity), type:

$ unzip myarchive.zip

And enter P4$$W0rd at the prompt.

Or the same in Python 2.6+:

>>> zipfile.ZipFile('myarchive.zip').extractall(pwd='P4$$W0rd')



回答2:


Extraction is pretty easy, you just use zipfile.ZipFile.setpassword() which was introduced in python 2.6, however the standard python library lacks support for creating encrypted zip files.

There are commercially available libraries for Python which supports creation of encrypted and password protected zip files. If you want to use something freely available, you need to use the standard zip command line utility.

zip -e -Ppassword filename.zip fileA fileB ...




回答3:


Actually setpassword("yourpassword") is only valid for extracting, not for creating a zip file.

The solution(not to my liking):

Create an encrypted ZIP file in Python




回答4:


If Python is not a must and you can use system utilities, tools like zip or rar provides password encrypted compression. zip with -e option, and rar with -p.




回答5:


You can use Pygpgme to create a password-protected gpg file, which is compressed.

You'll need to use the equivalent of gpg -c myFile or gpg --symmetric myFile and gpg myFile.gpg

I don't know what the equivalents are in that Python module, but I know they've existed since version 0.2. There was a bug report before then mentioning the lack of it, but someone released a patch and they fixed it in version 0.2.

This uses symmetric encryption so you don't have to worry about keys.

You might find my post asking how to use it on UbuntuForums. Feel free to answer it if you know.



来源:https://stackoverflow.com/questions/2195747/python-code-to-create-a-password-encrypted-zip-file

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