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.
5 Answers
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+1 7-Zip is available on Windows also. It supports many compression/archive formats, not just zip. Commented Mar 2, 2010 at 22:22
-
zipfile.ZipFile does not create an encrypted zip file. It can only read from encrypted zip files. pyminizip does this as stated in the link.– shadowbqCommented Dec 8, 2014 at 20:15
-
@shadowbq: yes.
ZipFile
can extract (unzip) the encrypted archive. If it could create the encrypted archives; you wouldn't need7z
utility.pyminizip
hasn't existed in 2010. I don't know how convenient (to install) or reliable (compared to7z
)pyminizip
is -- its development status is alpha.– jfsCommented Dec 12, 2014 at 16:25 -
2On Windows, I had to replace '7z' by 'C:\\Program Files\\7-Zip\\7z.exe'– fstevensCommented Jun 6, 2017 at 15:04
-
1Can use
subprocess.run
instead ofsubprocess.call
on Python 3.5+.– ytuCommented Nov 8, 2018 at 7:35
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 ...
-
I don't see
-P
on the standardzip
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: stackoverflow.com/questions/2195747/…– jfsCommented Mar 2, 2010 at 21:44
Actually setpassword("yourpassword")
is only valid for extracting, not for creating a zip file.
The solution (not to my liking):
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.