44

I am creating an ZIP file with ZipFile in Python 2.5, it works OK so far:

import zipfile, os

locfile = "test.txt"
loczip = os.path.splitext (locfile)[0] + ".zip"
zip = zipfile.ZipFile (loczip, "w")
zip.write (locfile)
zip.close()

But I couldn't find how to encrypt the files in the ZIP file. I could use system and call PKZIP -s, but I suppose there must be a more "Pythonic" way. I'm looking for an open source solution.

martineau
  • 119,623
  • 25
  • 170
  • 301
PabloG
  • 25,761
  • 10
  • 46
  • 59
  • 2
    open-source solution http://stackoverflow.com/questions/2195747/python-code-to-create-a-password-encrypted-zip-file/2366917#2366917 – jfs Apr 06 '10 at 19:42

8 Answers8

29

I created a simple library to create a password encrypted zip file in python. - here

import pyminizip

compression_level = 5 # 1-9
pyminizip.compress("src.txt", "dst.zip", "password", compression_level)

The library requires zlib.

I have checked that the file can be extracted in WINDOWS/MAC.

Shin Aoyama
  • 462
  • 4
  • 5
8

The duplicate question: Code to create a password encrypted zip file? has an answer that recommends using 7z instead of zip. My experience bears this out.

Copy/pasting the answer by @jfs here too, for completeness:

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

rc = subprocess.call(['7z', 'a', '-mem=AES256', '-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 utility), 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')
martineau
  • 119,623
  • 25
  • 170
  • 301
tripleee
  • 175,061
  • 34
  • 275
  • 318
8

This thread is a little bit old, but for people looking for an answer to this question in 2020/2021.

Look at pyzipper

A 100% API compatible replacement for Python’s zipfile that can read and write AES encrypted zip files.

7-zip is also a good choice, but if you do not want to use subprocess, go with pyzipper...

edif
  • 105
  • 1
  • 9
  • 1
    Oh man, this is such a great solution. pyminizip is nice, but limited in that its API can only handle actual files on disk. In contrast, I really appreciate that pyzipper mimics the standard ZipFile API. – Sherpa May 19 '22 at 00:00
3

pyminizip works great in creating a password protected zip file. For unziping ,it fails at some situations. Tested on python 3.7.3

Here, i used pyminizip for encrypting the file.

import pyminizip
compression_level = 5 # 1-9
pyminizip.compress("src.txt",'src', "dst.zip", "password", compression_level)

For unzip, I used zip file module:

from zipfile import ZipFile

with ZipFile('/home/paulsteven/dst.zip') as zf:
    zf.extractall(pwd=b'password')
Smack Alpha
  • 1,828
  • 1
  • 17
  • 37
1

You can use pyzipper for this task and it will work great when you want to encrypt a zip file or generate a protected zip file.

pip install pyzipper

import pyzipper

def encrypt_():

    secret_password = b'your password'

    with pyzipper.AESZipFile('new_test.zip',
                             'w',
                             compression=pyzipper.ZIP_LZMA,
                             encryption=pyzipper.WZ_AES) as zf:
        zf.setpassword(secret_password)
        zf.writestr('test.txt', "What ever you do, don't tell anyone!")

    with pyzipper.AESZipFile('new_test.zip') as zf:
        zf.setpassword(secret_password)
        my_secrets = zf.read('test.txt')

The strength of the AES encryption can be configure to be 128, 192 or 256 bits. By default it is 256 bits. Use the setencryption() method to specify the encryption kwargs:

def encrypt_():
    
    secret_password = b'your password'

    with pyzipper.AESZipFile('new_test.zip',
                             'w',
                             compression=pyzipper.ZIP_LZMA) as zf:
        zf.setpassword(secret_password)
        zf.setencryption(pyzipper.WZ_AES, nbits=128)
        zf.writestr('test.txt', "What ever you do, don't tell anyone!")

    with pyzipper.AESZipFile('new_test.zip') as zf:
        zf.setpassword(secret_password)
        my_secrets = zf.read('test.txt')

Official Python ZipFile documentation is available here: https://docs.python.org/3/library/zipfile.html

martineau
  • 119,623
  • 25
  • 170
  • 301
Try2Code
  • 69
  • 2
0

@tripleee's answer helped me, see my test below.

This code works for me on python 3.5.2 on Windows 8.1 ( 7z path added to system).

rc = subprocess.call(['7z', 'a', output_filename + '.zip', '-mx9', '-pSecret^)'] + [src_folder + '/'])

With two parameters:

  1. -mx9 means max compression
  2. -pSecret^) means password is Secret^). ^ is escape for ) for Windows OS, but when you unzip, it will need type in the ^.

Without ^ Windows OS will not apply the password when 7z.exe creating the zip file.

Also, if you want to use -mhe switch, you'll need the file format to be in 7z instead of zip.

I hope that may help.

Maher Abuthraa
  • 17,493
  • 11
  • 81
  • 103
zqcolor
  • 332
  • 2
  • 4
  • 13
0

2022 answer:

I believe this is an utterly mundane task and therefore should be oneliner. I abstracted away all the frevolous details in a library that is as powerfull as a bash terminal.

from crocodile.toolbox import Path

file = Path(r'my_string_path')
result_file = file.zip(pwd="lol", use_7z=True)
  • when the 7z flag is raised, it gets called behind the scenes.
    • You don't need to learn 7z command line syntax.
    • You don't need to worry about installing 7z, does that automatically if it's not installed. (tested on windows so far)
Alex Deft
  • 2,531
  • 1
  • 19
  • 34
-1

You can use the Chilkat library. It's commercial, but has a free evaluation and seems pretty nice.

Here's an example I got from here:

import chilkat

# Demonstrates how to create a WinZip-compatible 128-bit AES strong encrypted zip
zip = chilkat.CkZip()
zip.UnlockComponent("anything for 30-day trial")

zip.NewZip("strongEncrypted.zip")

# Set the Encryption property = 4, which indicates WinZip compatible AES encryption.
zip.put_Encryption(4)
# The key length can be 128, 192, or 256.
zip.put_EncryptKeyLength(128)
zip.SetPassword("secret")

zip.AppendFiles("exampleData/*",True)
zip.WriteZip()
Kijewski
  • 25,517
  • 12
  • 101
  • 143
Harley Holcombe
  • 175,848
  • 15
  • 70
  • 63
  • I already saw the Chilkat examples, but I'm looking for an open source option (sorry didn't mention this in my original post) I keep looking in google, but without luck. – PabloG Aug 20 '08 at 02:00