How to Create a Zip File Locker in Python

Discover how to protect your ZIP files with a custom Python script in this tutorial. Learn to enforce strong passwords using pyzipper and safeguard your data from cyber threats. Perfect for programmers who love to DIY their security tools!
  · 7 min read · Updated nov 2023 · Ethical Hacking · Cryptography

Struggling with multiple programming languages? No worries. Our Code Converter has got you covered. Give it a go!

Today, we will learn how to build a convenient and useful tool - a ZIP file locker. Sometimes, we want to lock our files to keep them away from prying cats (especially in these times of rapidly increasing cyber-attacks). In this tutorial, we will see how we can do that easily with Python. Of course, there are already-made programs that can do this for us, but I mean, we’re programmers, and we like to build our own stuff because we’re cool!

In this tutorial's code, we specify a ZIP file, the password to lock the file with, and the files to be locked in this ZIP file. Also, our program takes security to the next level by ensuring the user enters a strong password, and you cannot lock a ZIP file with a weak password. This is not something you see in most programs that perform this function. I included that feature because I feel it’s necessary. So please do me a favor and store your password in a secure password manager (so you don’t forget), similar to what we built here.

Related: How to Make a Password Generator in Python

So, let’s get locking with Python! The first thing to do is install the necessary library. Which is pyzipper. pyzipper is a Python library for working with ZIP archives, providing features such as creating, extracting, and managing ZIP files with encryption and compression support:

$ pip install pyzipper colorama

Next up, we import the necessary libraries in our newly created file named zip_file_locker.py for instance:

# Import the necessary libraries.
import pyzipper, argparse, sys, re, getpass
from colorama import Fore, init

init()

We already talked about what pyzipper does. I’m not repeating that :)

  • argparse is a Python library used for parsing command-line arguments and options. We have a tutorial on this library.
  • sys is a Python library that provides access to various runtime system functions and variables. One key one is exiting a program.
  • re is the Python regular expression library for working with regular expressions.
  • colorama is a library that simplifies colored text output in the terminal, enhancing the visual presentation of text with foreground and background colors. We also have a detailed tutorial on Colorama.
  • getpass: is a Python library that lets us enter our passwords without displaying them on the screen. Similar to the way we enter our passwords on the Linux terminal. This is for security purposes.

The init() function initializes colorama.

This program is CLI-based. Next, we create a function that accepts user arguments from the command line:

# Define a function to get CLI commands.
def get_cli_arguments():
    parser = argparse.ArgumentParser(description="A program to lock a ZIP File.")
    # Collect user arguments.
    parser.add_argument('--zipfile', '-z', dest='zip_file', help='Specify the ZIP file to create or update.')
    parser.add_argument('--addfile', '-a', dest='add_files', nargs='+', help='Specify one or more files to add to the ZIP file(s).')
    # Parse the collected arguments.
    args = parser.parse_args()
    # Check if arguments are missing, print appropriate messages and exit the program.
    if not args.zip_file:
        parser.print_help()
        sys.exit()
    if not args.add_files:
        parser.print_help()
        sys.exit()
    return args

Related: Build 39 Ethical Hacking Scripts & Tools with Python EBook

In this function, we allow users to specify various arguments through the command line. This is similar to clicking buttons on a GUI-based program. But we’re cool, so we prefer CLI. In this function, users can use --zipfile or -z to specify the ZIP file to lock. Similarly, --addfile or -a specify the file(s) to be locked in the ZIP file. 

Now, let's create a function that checks the password's strength. As I mentioned, our program will not allow users to set weak passwords (for security reasons). So, we create a function to check if the password is strong enough. We check if the password is not less than 8 characters and has an uppercase, lowercase, and a digit. If the password does not meet the criteria, we flag it as weak. Feel free to modify these criteria to your taste:

# Function to check password strength.
def check_password_strength(password):
    # Check for minimum length. In our case, 8.
    if len(password) < 8:
        return False
    # Check for at least one uppercase letter, one lowercase letter, and one digit.
    if not (re.search(r'[A-Z]', password) and re.search(r'[a-z]', password) and re.search(r'\d', password)):
        return False
    return True

Now, we access the user’s input (from the terminal) and get the user’s desired password using getpass. Then, we make sure the password is strong. If it is, we lock the ZIP file with the specified password and add the specified files:

# Call the arguments function.
arguments = get_cli_arguments()
# Get user password
password = getpass.getpass("[?] Enter your password > ")
# If the password is weak, tell the user and exit the program.
if not check_password_strength(password):
    print(f"{Fore.RED}[-] Password is not strong enough. It should have at least 8 characters and contain at least one uppercase letter, one lowercase letter, and one digit.")
    sys.exit()

# Create a password-protected ZIP file.
with pyzipper.AESZipFile(arguments.zip_file, 'w', compression=pyzipper.ZIP_LZMA, encryption=pyzipper.WZ_AES) as zf:
    zf.setpassword(password.encode())
    # Add files to the ZIP file.
    for file_to_add in arguments.add_files:
        zf.write(file_to_add)

# Print a Success message.
print(f"{Fore.GREEN}[+] ZIP file is locked with a strong password.")

The pyzipper.AESZipFile() creates a new ZIP file with AES encryption, LZMA compression, and a user-provided password, ensuring the file is password-protected. It’s safe to say that this is the heart of this code.

Now, let’s run our code from our terminal:

$ python zip_file_locker.py --zipfile test.zip --addfile ransomware.py test10.pdf backdoor.py domain_info.py

Here, I'm adding the ransomware.py, test10.pdf, backdoor.py, and domain_info.py files into my demo password-protected ZIP file. Let's check it:

When we try to access it:

We’ve successfully locked the ZIP file! Now, this password can only be opened with the set password. We also have the liberty of entering our passwords in public places as it is not being displayed on screen. But that does not mean we should be careless when entering passwords. We should try as much as possible to shield our passwords from the public eye. 

There you have it! We managed to build a very handy tool that can be used daily. You can get the complete code here.

Finally, in our Ethical Hacking with Python EBook, we've built over 39 hacking tools and scripts from scratch using Python! Check it out here if you're interested!

Learn also: How to Crack Hashes in Python.

Happy hacking ♥

Take the stress out of learning Python. Meet our Python Code Assistant – your new coding buddy. Give it a whirl!

View Full Code Switch My Framework
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!