tags:

views:

642

answers:

4

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.

+4  A: 

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 ...

Johan Dahlin
Bollocks. """ZipFile.setpassword(pwd) Set pwd as default password to extract encrypted files."""It doesn't do **creating** a zip with a password.
John Machin
Thanks for mentioning that John, I've updated the entry to mention a command line utility solution instead.
Johan Dahlin
I don't see `-P` on the standard `zip` utility. `zip --help | grep -i -e '-p'` returns nothing (Ubuntu, Zip 3.0 (July 5th 2008), by Info-ZIP). I use open-source solution in my answer: http://stackoverflow.com/questions/2195747/python-code-to-create-a-password-encrypted-zip-file/2366917#2366917
J.F. Sebastian
A: 

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.

ghostdog74
You can even call these tools from python with subprocess.Popen
Nikwin
+2  A: 

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

The solution(not to my liking):

http://stackoverflow.com/questions/17250/create-an-encrypted-zip-file-in-python

Diego Castro
+4  A: 

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')
J.F. Sebastian
+1 7-Zip is available on Windows also. It supports many compression/archive formats, not just zip.
John Machin