Python Snippets

Password-Protected ZIP File Creator and Extractor

import zipfile
import os
from getpass import getpass

def create_protected_zip(zip_filename, files_to_zip, password=None):
    """
    Creates a password-protected ZIP file containing specified files.
    
    Args:
        zip_filename (str): Name of the output ZIP file
        files_to_zip (list): List of file paths to include in the ZIP
        password (str, optional): Password for the ZIP file. If None, prompts securely.
    
    Returns:
        bool: True if successful, False otherwise
    """
    if not password:
        password = getpass("Enter password for ZIP file: ")
        confirm_password = getpass("Confirm password: ")
        if password != confirm_password:
            print("Passwords do not match!")
            return False
    
    try:
        with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
            # Set password for the entire archive
            zipf.setpassword(password.encode('utf-8'))
            
            for file_path in files_to_zip:
                if os.path.exists(file_path):
                    # Add file to ZIP with just its basename (no full path)
                    zipf.write(file_path, os.path.basename(file_path))
                    print(f"Added: {file_path}")
                else:
                    print(f"Warning: File not found - {file_path}")
        
        print(f"Successfully created protected ZIP: {zip_filename}")
        return True
    except Exception as e:
        print(f"Error creating ZIP file: {e}")
        return False

def extract_protected_zip(zip_filename, extract_to=".", password=None):
    """
    Extracts a password-protected ZIP file.
    
    Args:
        zip_filename (str): Path to the ZIP file
        extract_to (str): Directory to extract files to
        password (str, optional): Password for the ZIP file. If None, prompts securely.
    
    Returns:
        bool: True if successful, False otherwise
    """
    if not os.path.exists(zip_filename):
        print(f"ZIP file not found: {zip_filename}")
        return False
    
    if not password:
        password = getpass("Enter password to extract ZIP: ")
    
    try:
        with zipfile.ZipFile(zip_filename, 'r') as zipf:
            zipf.setpassword(password.encode('utf-8'))
            
            # Test the password by trying to read the file list
            zipf.testzip()
            
            # Extract all files
            zipf.extractall(path=extract_to)
            print(f"Successfully extracted to: {extract_to}")
            return True
    except RuntimeError as e:
        if "Bad password" in str(e):
            print("Incorrect password!")
        else:
            print(f"Error extracting ZIP: {e}")
        return False
    except Exception as e:
        print(f"Error extracting ZIP: {e}")
        return False

# Example usage
if __name__ == "__main__":
    # Example: Create a protected ZIP
    files = ["document.txt", "image.jpg"]  # Replace with your actual files
    zip_name = "protected_archive.zip"
    
    # Uncomment to create a ZIP (you'll need to provide actual files)
    # create_protected_zip(zip_name, files)
    
    # Example: Extract a protected ZIP
    # extract_protected_zip(zip_name)

What This Code Does

This Python snippet provides two main functions for working with password-protected ZIP files:

  1. create_protected_zip() - Creates a password-protected ZIP archive containing specified files
  2. extract_protected_zip() - Extracts files from a password-protected ZIP archive

The code securely handles password input using getpass, which prevents the password from being visible on the screen. It also validates that files exist before adding them to the archive and handles common errors like incorrect passwords.

Why This Is Useful

How to Run It

  1. Save the code as protected_zip.py
  2. Modify the files list in the example usage section to include actual file paths you want to archive
  3. Run the script: python protected_zip.py
  4. Follow the prompts to enter passwords when creating or extracting archives

To create a protected ZIP file:

  1. Uncomment the create_protected_zip() call
  2. Ensure the files in your list actually exist
  3. Run the script and provide a strong password

To extract a protected ZIP file:

  1. Uncomment the extract_protected_zip() call
  2. Run the script and provide the correct password

Note: The password protection uses ZIP 2.0 encryption, which is suitable for general use but not for highly sensitive data. For stronger security, consider using specialized encryption tools.