The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Create a file encryption tool

Here’s a simple file encryption tool written in Python using the cryptography library. It allows you to encrypt and decrypt files securely with a password-derived key.

python
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives import hashes from cryptography.hazmat.backends import default_backend from cryptography.fernet import Fernet import base64 import os def derive_key(password: bytes, salt: bytes) -> bytes: # Derive a secret key from a password and salt using PBKDF2 HMAC SHA256 kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100_000, backend=default_backend() ) return base64.urlsafe_b64encode(kdf.derive(password)) def encrypt_file(filepath: str, password: str): salt = os.urandom(16) # Random salt for key derivation key = derive_key(password.encode(), salt) fernet = Fernet(key) with open(filepath, 'rb') as f: data = f.read() encrypted = fernet.encrypt(data) # Save salt + encrypted data to file with open(filepath + '.enc', 'wb') as f: f.write(salt + encrypted) print(f"File encrypted successfully: {filepath}.enc") def decrypt_file(encrypted_filepath: str, password: str): with open(encrypted_filepath, 'rb') as f: salt = f.read(16) # First 16 bytes are the salt encrypted_data = f.read() key = derive_key(password.encode(), salt) fernet = Fernet(key) try: decrypted = fernet.decrypt(encrypted_data) except Exception as e: print("Decryption failed. Incorrect password or corrupted file.") return # Save decrypted file without the .enc extension original_filepath = encrypted_filepath.rsplit('.enc', 1)[0] with open(original_filepath, 'wb') as f: f.write(decrypted) print(f"File decrypted successfully: {original_filepath}") if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Simple file encryption tool.") parser.add_argument('mode', choices=['encrypt', 'decrypt'], help="Choose to encrypt or decrypt") parser.add_argument('file', help="File to encrypt or decrypt") parser.add_argument('password', help="Password for encryption/decryption") args = parser.parse_args() if args.mode == 'encrypt': encrypt_file(args.file, args.password) else: decrypt_file(args.file, args.password)

Usage

  • Encrypt:
    python encrypt_tool.py encrypt filename.txt yourpassword

  • Decrypt:
    python encrypt_tool.py decrypt filename.txt.enc yourpassword


This uses a strong password-based key derivation (PBKDF2) with a random salt stored alongside the encrypted file for security, and symmetric encryption via Fernet (AES-128 in CBC mode with HMAC). Let me know if you want me to adapt it to other languages or add features!

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About