Understanding Dictionary Attacks Through Code:
A Practical Overview

Secutry Corp
3 min readNov 21, 2023



In cybersecurity, a dictionary attack is a technique for defeating a cipher or authentication mechanism by trying to determine its decryption key or passphrase by trying hundreds, thousands, or sometimes millions of possible combinations that are most likely to succeed. To grasp how such an attack operates in real-world contexts, let’s delve into an example of Python code that demonstrates a simulated dictionary attack against encrypted data.
The Code’s Core Functionality The provided Python script includes three primary functions that collectively aim to crack an encryption cipher using precomputed hash values (from a dictionary file) and generate new possible passwords to expand the dictionary for future attacks. Here’s a breakdown of its workings:

import sys
import cryptography
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
import time

cipherText = open("xifrat.bin", 'rb').read()

def desxifrar_text(text_xifrat, clau):
cipher = Cipher(algorithms.AES(clau), modes.ECB(), backend=default_backend())
decryptor = cipher.decryptor()
text_desxifrat = decryptor.update(text_xifrat) + decryptor.finalize()
return text_desxifrat

def pbkdf2():
print("----Desxifrant text sense diccionari de hashos precomputats.")
file = open("output.txt", "rb")
with open("pbkdf2.txt", "wb") as binary_file:
dexifrat = open("resultat_no_precomputats.txt", 'w')
start_time = time.time()
for line in file:
line = line.strip()
key = kdf.derive(line)
if len(key) != 16:
print(f"La clau generada per la contrasenya {line} no té la longitud correcta.")

binary_file.write(key + b"

text_desxifrat = desxifrar_text(cipherText[16:], key)

if text_desxifrat.decode("utf-8"):
print(f"------La contrasenya és: {line}")
print(f"------Desxifrat completat")
end_time = time.time() # Record the end time
elapsed_time = end_time - start_time
print(f"-------Temps amb hash NO precomputat: {elapsed_time} segons")
except Exception as e:


def passwordsGeneration():
print("--Generant diccionari.")
if len(sys.argv) != 2:
print("Usage: python3 script.py <file>")
file = open(sys.argv[1], "r")
outputFile = open("output.txt", "w")
print("Error: file not found")
for line in file:
line = line.strip()
outputFile.write(line + "
for i in range(0, 10):
outputFile.write(line + str(i) + "
for j in range(0, 10):
outputFile.write(line + str(i) + str(j) + "
print("--Diccionari generat.")

if __name__ == "__main__":

Password Dictionary Generation


The script generates a dictionary of potential passwords based on a simple pattern; it reads from an input file and then writes sequences of passwords by appending numerical combinations.

Password Hashing and Key Derivation pbkdf2:

This function attempts to simulate a non-dictionary attack scenario by generating keys using the PBKDF2 (Password-Based Key Derivation Function 2) with SHA-1 hashing. It illustrates the process of deriving keys from passwords not precomputed and attempts to decrypt ciphertext with these keys.

Understanding Dictionary Attacks: A Code Perspective

Data Preparation

The script begins with the generation of a potential password list, a common step in preparing for a dictionary attack. Passwords are often derived from common patterns or collected from breaches.

Key Derivation Function (KDF) Usage

In the real world, passwords are rarely used directly as keys; instead, they are processed through a KDF like PBKDF2HMAC. The script shows how an actual password can be hashed to produce a key, simulating how attackers would prepare for an attack by processing their dictionary of potential passwords in advance.

Efficient Decryption Attempts

With a list of potential keys at hand, the script then demonstrates an attempt to decrypt the given ciphertext. By iterating over each precomputed hash, the attack is expedited since the computationally intensive task of key derivation is pre-processed.

Error Handling and Validation

The script includes error handling to skip over hashes that do not result in successful decryption, indicating a real attack would need to handle various potential decryption failures.

Performance Measurement

The code measures the time taken to decrypt the text with precomputed hashes versus without, demonstrating the efficiency gains of using a dictionary attack with precomputed hashes.

Github link: https://github.com/Secutry-Corp/dictionary-attack/blob/main/script.py



Secutry Corp

www.secutry.com - Secutry Is a compant that offers services on multiplatform, web development. Also Smart contracts, blockchain development.