Open In App

How to Brute Force ZIP File Passwords in Python?

In this article, we will see a Python program that will crack the zip file’s password using the brute force method.

The ZIP file format is a common archive and compression standard. It is used to compress files. Sometimes, compressed files are confidential and the owner doesn’t want to give its access to every individual. Hence, the zip file is protected with a password. If the password is common then it’s easily crack-able. Here, we’ll use the brute force method to crack the zip file’s password.



How to Brute Force ZIP File Passwords in Python?

A brute force method is a method where a set of predefined values are used to crack a password until successful. This is basically a “hit and try” method. This method might take a long time if the set of values are high, but its success rate is high. The more the number of values, the greater the chances of cracking passwords. Here we’ll be using “rockyou” text file of size 133 MB with over 14 million sets of passwords to try. Download the text file here.

Approach:



Below is the full implementation:




import zipfile
 
 
def crack_password(password_list, obj):
    # tracking line no. at which password is found
    idx = 0
 
    # open file in read byte mode only as "rockyou.txt"
    # file contains some special characters and hence
    # UnicodeDecodeError will be generated
    with open(password_list, 'rb') as file:
        for line in file:
            for word in line.split():
                try:
                    idx += 1
                    obj.extractall(pwd=word)
                    print("Password found at line", idx)
                    print("Password is", word.decode())
                    return True
                except:
                    continue
    return False
 
 
password_list = "rockyou.txt"
 
zip_file = "gfg.zip"
 
# ZipFile object initialised
obj = zipfile.ZipFile(zip_file)
 
# count of number of words present in file
cnt = len(list(open(password_list, "rb")))
 
print("There are total", cnt,
      "number of passwords to test")
 
if crack_password(password_list, obj) == False:
    print("Password not found in this file")

Output:


Article Tags :