Step 1: Import Necessary Libraries
Let’s proceed with creating the script. We’ll need PyPDF2 for working with the PDF and itertools for generating brute-force combinations.
pythonCopy codeimport PyPDF2
import itertools
import stringStep 2: Define the Character Set and Load Dictionary
We’ll define our character set for brute-force attempts and load a dictionary of common words or phrases.
pythonCopy codecharacters = string.ascii_lowercase + string.digits
dictionary_file = "common_passwords.txt" # A file containing common passwords or phrases, one per linedef load_dictionary(file_path):
with open(file_path, 'r') as file:
return [line.strip() for line in file.readlines()]Step 3: Create the PDF Password Recovery Function
We’ll create a function that first attempts to unlock the PDF using dictionary words, and if that fails, it switches to brute-force.
pythonCopy codedef recover_pdf_password(pdf_file, max_length):
pdf_reader = PyPDF2.PdfReader(pdf_file)
dictionary = load_dictionary(dictionary_file)
# Attempt dictionary attack
for word in dictionary:
if pdf_reader.decrypt(word) == 1:
print(f"Password found: {word}")
return word
# If dictionary attack fails, perform brute-force attack
for length in range(1, max_length + 1):
for guess in itertools.product(characters, repeat=length):
password = ''.join(guess)
if pdf_reader.decrypt(password) == 1:
print(f"Password found: {password}")
return password print("Password not found")
return NoneStep 4: Run the Script
Finally, you can run the script by specifying the PDF file’s path and the maximum length for brute-force attempts.
pythonCopy codepdf_file = "path/to/your/encrypted.pdf"
max_length = 6 # Adjust based on the complexity of the password
recover_pdf_password(pdf_file, max_length)Explanation:
- Dictionary Attack: The script first tries every word or phrase in the dictionary file. This is usually faster and more effective if the password is a common word.
- Brute-Force Fallback: If the dictionary attack fails, the script generates all possible combinations of lowercase letters and digits up to the specified maximum length.
- Success Check: The
decrypt()method returns1if the correct password is found, at which point the script prints and returns the password.
Use Case:
This script is useful when you suspect that a password might be a common word but want to ensure all possibilities are covered by also attempting a brute-force attack.
Final Thoughts:
This demonstration combines the efficiency of a dictionary attack with the thoroughness of brute-force, offering a robust solution for recovering passwords from encrypted PDF files.
Get Aardvark Infinity’s stories in your inbox
Join Medium for free to get updates from this writer.
Here are five related hashtags:
- #PDFEncryption
- #PasswordRecovery
- #DictionaryAttack
- #CyberSecurity
- #DecryptPDF








