Understanding Dictionary Attacks Through Code:
A Practical Overview

Secutry Corp
3 min readNov 21, 2023

--

Introduction

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()
kdf = PBKDF2HMAC(
algorithm=cryptography.hazmat.primitives.hashes.SHA1(),
length=16,
salt=cipherText[8:16],
iterations=1,
backend=default_backend()
)
key = kdf.derive(line)
if len(key) != 16:
print(f"La clau generada per la contrasenya {line} no té la longitud correcta.")
continue

binary_file.write(key + b"
")

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

if text_desxifrat.decode("utf-8"):
print(f"------La contrasenya és: {line}")
print(f"------Desxifrat completat")
dexifrat.write(text_desxifrat.decode("utf-8"))
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:
pass

file.close()
binary_file.close()
dexifrat.close()

def passwordsGeneration():
print("--Generant diccionari.")
if len(sys.argv) != 2:
print("Usage: python3 script.py <file>")
sys.exit(1)
try:
file = open(sys.argv[1], "r")
outputFile = open("output.txt", "w")
except:
print("Error: file not found")
sys.exit(1)
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) + "
")
file.close()
outputFile.close()
print("--Diccionari generat.")


if __name__ == "__main__":
passwordsGeneration()
pbkdf2()

Password Dictionary Generation

passwordsGeneration:

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.