🔐 Encrypt & Decrypt Files in Python with a Custom Extension
Introduction
Data security is one of the most important aspects of today’s digital world. Whether you’re storing sensitive documents, credentials, or personal projects, securing them is a must.
In this blog, we’ll create a simple Python program that can:
Encrypt any file and save it with a custom extension (e.g.,
.zeshan
).Decrypt the file only with your secret key.
This is a practical way to learn about file encryption while keeping your own files secure.
⚠️ Legal & Educational Disclaimer
This tutorial is for educational and personal use only. Using encryption in malicious ways such as ransomware, unauthorized data locking, or accessing someone else’s files without permission is illegal.
You may use this code for:
⚡ Protecting your personal files
⚡ Securing your own projects
⚡ Learning how encryption works
You must not use this code for:
❌ Locking or damaging other people’s data
❌ Creating ransomware or malware
❌ Any unauthorized access
Step 1: Install Required Library
We’ll use Python’s cryptography
library. Install it with:
pip install cryptography
Step 2: Generate Your Secret Key
Before encrypting, you need a secret key. This key will be used to both encrypt and decrypt your files. Generate it once:
from cryptography.fernet import Fernet
print(Fernet.generate_key())
Save this key somewhere safe. Without it, you will not be able to decrypt your files.
Step 3: Python Code (Encrypt + Decrypt)
from cryptography.fernet import Fernet
import os
# ------------ SECRET KEY ------------
# Replace with the key you generated
SECRET_KEY = b'YOUR_SECRET_KEY_HERE'
fernet = Fernet(SECRET_KEY)
def encrypt_file(input_file, output_file=None, custom_ext=".zeshan"):
"""Encrypts a file and saves with custom extension"""
if not output_file:
output_file = input_file + custom_ext
with open(input_file, "rb") as f:
data = f.read()
encrypted = fernet.encrypt(data)
with open(output_file, "wb") as f:
f.write(encrypted)
print(f"[+] File encrypted as: {output_file}")
def decrypt_file(input_file, output_file=None, custom_ext=".zeshan"):
"""Decrypts a file (only with correct key)"""
if input_file.endswith(custom_ext):
if not output_file:
output_file = input_file.replace(custom_ext, "")
with open(input_file, "rb") as f:
encrypted_data = f.read()
try:
decrypted = fernet.decrypt(encrypted_data)
except Exception:
print("[-] Wrong key or corrupted file!")
return
with open(output_file, "wb") as f:
f.write(decrypted)
print(f"[+] File decrypted as: {output_file}")
else:
print(f"[-] File does not have extension {custom_ext}")
if __name__ == "__main__":
# Example usage
encrypt_file("test.txt") # Encrypts test.txt → test.txt.zeshan
decrypt_file("test.txt.zeshan") # Decrypts back to test.txt
Step 4: How It Works
Encryption → The script reads the original file, encrypts its content, and saves it with a custom extension (e.g.,
test.txt.zeshan
).Decryption → The script takes the encrypted file and decrypts it back to the original, but only if the correct secret key is provided.
Security Check → If the wrong key is used or the file is corrupted, decryption will fail.
Step 5: Example Run
$ python encryptor.py
[+] File encrypted as: test.txt.zeshan
[+] File decrypted as: test.txt
Now you have:
test.txt.zeshan
→ the encrypted (locked) filetest.txt
→ the decrypted (original) file
Real-Life Use Cases
- Protect personal notes
Lock sensitive project files - Secure data on a USB drive
- Demonstrate basic encryption for learning purposes
Conclusion
With just a few lines of Python, you can create your own file encryption and decryption system. This approach ensures that only you, with your secret key, can unlock your files.
Remember:
Security is about controlling access, not just keeping secrets.
Use this responsibly to secure your own files and to understand how encryption works in real-world applications.