Crack a zip file password using lists in Python

Hello and welcome everyone, in this tutorial we are going to crack a zip file password using lists in Python. This does sound interesting. doesn’t it? Well, we are going to do this in this tutorial. Let’s see how we can accomplish this task.

How to Crack a zip file password using lists in Python

Python has a zipfile module that we can use to deal with zip files on our system as shown here. This module allows us to use functions ZipFile() and extractall().

import zipfile

Now let’s define a function that takes file_name and password as input parameters and returns true for the correct password. Here it is.

def crackZip(file_name, passwd):
    file = zipfile.ZipFile(file_name)
    try:
        file.extractall(pwd = bytes(passwd, 'utf-8'))
        return True
    except Exception:
        return False

As you can see, in the above function crackZip(), we have used ZipFile() and extractall() methods. These methods are used to open and extract files respectively. If the password is correct, crackZip() function returns true else it returns false.

In the next step, we define a list of passwords from which we need to find the right password. See below.

passwords = ['Ranjeet', 'NOTme', '8753474', '85737222', '01010010', 'PASS1234' , '19194567', 'CodeSpeedy']

Then we create a loop to check for every element in the given list of passwords whether it is the right one or not using previously defined crackZip() function. If the function returns true, we print the password as it is the correct password. For incorrect password, we continue the loop.

for password in passwords:
    ret = crackZip(file_name, password)
    if (ret):
        print('The password is',password)
    else:
        continue

The full code is given here.

import zipfile

def crackZip(file_name, passwd):
    file = zipfile.ZipFile(file_name)
    try:
        file.extractall(pwd = bytes(passwd, 'utf-8'))
        return True
    except Exception:
        return False

 
        
passwords = ['Ranjeet', 'NOTme', '8753474', '85737222', '01010010', 'PASS1234' , '19194567', 'CodeSpeedy']
file_name = 'example_2.zip'

for password in passwords:
    ret = crackZip(file_name, password)
    if (ret):
        print('The password is',password)
    else:
        continue

And it gives the output as follows:

The password is CodeSpeedy

I hope you liked the article. Please comment below if you have any suggestions.

Thank you.

Also read:  Sort files by size in a directory in Python.

Leave a Reply