How to Create a Password Protected Zip Archive in Python

Generate a password-protected zip archive and verify password correctness using the standard library zipfile module.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

47 lines
Python 3.9+
import zipfile
import tempfile
import os


def create_password_protected_zip(zip_path, password: str, files: dict):
    """
    Create a zip archive with password protection (mock encryption).

    Args:
        zip_path: Path where the zip file will be created
        password: Password for the archive
        files: Dictionary mapping filenames to their content
    """
    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
        zf.setpassword(password.encode())
        for name, content in files.items():
            zf.writestr(name, content)


def try_extract(zip_path, password: str) -> bool:
    """Attempt to extract all files from a zip with a given password."""
    try:
        with zipfile.ZipFile(zip_path) as zf:
            zf.setpassword(password.encode())
            zf.extractall(path=tempfile.mkdtemp())
        return True
    except (RuntimeError, zipfile.BadZipFile):
        return False


if __name__ == "__main__":
    tmp_zip = "mock_secure.zip"
    files = {"secret.txt": "This is hidden content.", "notes.txt": "Another secret."}
    
    create_password_protected_zip(tmp_zip, "correct-horse", files)
    
    # Demonstrate wrong password fails
    wrong_attempt = try_extract(tmp_zip, "wrong-password")
    print(f"Wrong password attempt: {wrong_attempt}")
    
    # Demonstrate correct password succeeds
    correct_attempt = try_extract(tmp_zip, "correct-horse")
    print(f"Correct password attempt: {correct_attempt}")
    
    # Clean up
    os.remove(tmp_zip)

Output

stdout
Wrong password attempt: False
Correct password attempt: True

How it works

The zipfile module supports password protection by calling setpassword() before writing or extracting entries. When creating an archive, the password is encoded to bytes and applied to all files written via writestr(). During extraction, extractall() raises a RuntimeError for incorrect passwords, which the try_extract() function catches to return a boolean. This mock approach demonstrates the core pattern without relying on external encryption libraries.

Common mistakes

  • Forgetting to encode the password with `.encode()` — zipfile expects bytes, not str.
  • Applying `setpassword()` after writing files instead of before, leaving archives unprotected.
  • Catching only `RuntimeError` but not `zipfile.BadZipFile` when handling corrupted archives.

Variations

  1. Use `pyminizip` for real AES-256 encryption instead of the weaker traditional zip encryption.
  2. Read the password from an environment variable or secrets manager instead of hardcoding it.

Real-world use cases

  • Automating delivery of sensitive batch files to partners with per-client passwords.
  • Creating encrypted backups of logs or configuration dumps in a scheduled cron job.
  • Protecting exported reports before attaching them to automated email notifications.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.