Have you ever heard of a hash? If you haven’t, let’s dive into what makes it a cornerstone in cybersecurity, it is a unique string of characters of a fixed size for data (password, files, messages,…), which is why they are used for hacking, since each password has its unique hash you only need to crack the hash to get the password.
In today’s tutorial, we will talk about a certain hacking method that uses a hash called “the dictionary attack” and how to Protect Ourselves From it. This method consists of comparing the hash of different passwords in a password file list to the hash of the password we want to crack.
Let’s get started!
Table of Contents
- Disclaimer
- Imports
- hash_password Function
- crack_password_hash Function
- Main Function
- Executing the Main Function
- How to Protect Yourself
- Example
- Full Code
Disclaimer
Please note: Before we proceed with this code, it is imperative for me to warn you not to use this code illegally or without consent since it is for educational purposes only.
PS: This is the password file txt that I used, I named it password-list after downloading it:
If you want to create your own wordlist, check out this tutorial.
Imports
First of all, we start by importing the hashlib module, which allows us to use functions that will transform data in this case passwords into hash.
import hashlib
hash_password Function
Next, we start by defining our hash_password
function which we will use to transform the passwords that exist on the password-list.txt
file (which we downloaded) into their respective sha1
hash by selecting the correct method from the hashlib
module. However, in the case that there is no method to turn a specific password into a sha1
hash then an error will appear saying “Unsupported hashing algorithm“.
def hash_password(password, algorithm='sha1'):
"""Hashes the given password using the specified algorithm."""
if algorithm not in hashlib.algorithms_available:
raise ValueError("Unsupported hashing algorithm.")
hash_func = getattr(hashlib, algorithm)
return hash_func(password.encode()).hexdigest()
crack_password_hash Function
After the earlier function transforms the passwords in the password-list.txt
file into sha1
hash, this function will compare them to the sha1
hash password that the user wants to crack, once this function finds a match it will return the matched password to the main function, if not it will return None
.
def crack_password_hash(hash_to_crack, password_list_file):
"""Attempts to crack the given hash using passwords from the provided list."""
with open(password_list_file, 'r') as f:
for line in f:
password = line.strip()
hashed_password = hash_password(password)
if hash_to_crack == hashed_password:
return password
return None
Main Function
Following that, we create the main function that will be responsible for taking the user’s input, then it calls the crack_password_hash
function to retrieve the sha1
hash password that matches the user’s input that was transformed into sha1
hash by the hash_password
function, if a match is found this function will print the cracked password, if not it will print “failed to crack the password“.
def main():
user_hash = input("Enter the hash you want to crack: ").strip().lower()
password_list_file = 'password-list.txt' # Update with your password list file
cracked_password = crack_password_hash(user_hash, password_list_file)
if cracked_password:
print(f"Password successfully cracked: {cracked_password}")
else:
print("Failed to crack the password.")
Executing the Main Function
Finally, these two lines make sure that this script can only run directly, and not as an imported module.
if __name__ == '__main__':
main()
How to Protect Yourself
Since hacking through the dictionary attack is based on an existing password list, then the obvious way to protect ourselves is :
- Make sure that our password is strong and unique, and also cannot be guessed (Learn how to create strong and secure passwords with our Python password generator tutorial).
- Periodically change our password, in this case even if the hacker obtains the hash of our previous password, it will be useless.
- Monitoring our accounts regularly for any unusual activity.
- Provide different factors such as fingerprints or facial recognition to verify our identity.
- Use the sha 256 instead of sha 1 since it is larger in output size and more secure.
Learn also: How to Crack PDF Files in Python
Example
You can try this code by taking a password from our password list file and transforming it into a sha1 hash using this website:
https://passwordsgenerator.net/sha1-hash-generator/
Full Code
import hashlib
def hash_password(password, algorithm='sha1'):
"""Hashes the given password using the specified algorithm."""
if algorithm not in hashlib.algorithms_available:
raise ValueError("Unsupported hashing algorithm.")
hash_func = getattr(hashlib, algorithm)
return hash_func(password.encode()).hexdigest()
def crack_password_hash(hash_to_crack, password_list_file):
"""Attempts to crack the given hash using passwords from the provided list."""
with open(password_list_file, 'r') as f:
for line in f:
password = line.strip()
hashed_password = hash_password(password)
if hash_to_crack == hashed_password:
return password
return None
def main():
user_hash = input("Enter the hash you want to crack: ").strip().lower()
password_list_file = 'password-list.txt' # Update with your password list file
cracked_password = crack_password_hash(user_hash, password_list_file)
if cracked_password:
print(f"Password successfully cracked: {cracked_password}")
else:
print("Failed to crack the password.")
if __name__ == '__main__':
main()
Happy Coding!