The Palos Publishing Company

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

Build a file encryption and decryption tool

Here’s a simple Python tool for file encryption and decryption using the cryptography library. This tool will allow you to encrypt a file with a password and later decrypt it using the same password.

Requirements:

First, install the required library:

bash
pip install cryptography

File Encryption and Decryption Tool Code:

python
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives import hashes from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives import padding import os import base64 # Helper function to derive a key from a password def derive_key(password: str, salt: bytes) -> bytes: kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend() ) return kdf.derive(password.encode()) # Function to encrypt a file def encrypt_file(file_path: str, password: str, output_path: str): salt = os.urandom(16) # Generate a random salt key = derive_key(password, salt) # AES cipher in CBC mode iv = os.urandom(16) # Initialization vector cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()) encryptor = cipher.encryptor() # Open file and pad it with open(file_path, 'rb') as f: file_data = f.read() padder = padding.PKCS7(128).padder() padded_data = padder.update(file_data) + padder.finalize() encrypted_data = encryptor.update(padded_data) + encryptor.finalize() # Write encrypted data to the output file with open(output_path, 'wb') as f: f.write(salt) # Write the salt at the beginning of the file f.write(iv) # Write the initialization vector f.write(encrypted_data) # Write the encrypted content print(f"File encrypted successfully and saved as {output_path}") # Function to decrypt a file def decrypt_file(file_path: str, password: str, output_path: str): # Read the encrypted file with open(file_path, 'rb') as f: salt = f.read(16) # Salt is the first 16 bytes iv = f.read(16) # IV is the next 16 bytes encrypted_data = f.read() # Remaining data is the encrypted content key = derive_key(password, salt) # AES cipher in CBC mode cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()) decryptor = cipher.decryptor() # Decrypt the data decrypted_data = decryptor.update(encrypted_data) + decryptor.finalize() # Unpad the data unpadder = padding.PKCS7(128).unpadder() unpadded_data = unpadder.update(decrypted_data) + unpadder.finalize() # Write decrypted data to output file with open(output_path, 'wb') as f: f.write(unpadded_data) print(f"File decrypted successfully and saved as {output_path}") # Example usage if __name__ == "__main__": action = input("Choose action (encrypt/decrypt): ").strip().lower() if action == "encrypt": input_file = input("Enter the file to encrypt: ").strip() password = input("Enter password for encryption: ").strip() output_file = input("Enter the output file name: ").strip() encrypt_file(input_file, password, output_file) elif action == "decrypt": input_file = input("Enter the file to decrypt: ").strip() password = input("Enter password for decryption: ").strip() output_file = input("Enter the output file name: ").strip() decrypt_file(input_file, password, output_file) else: print("Invalid action. Please choose 'encrypt' or 'decrypt'.")

Explanation of the Code:

  1. Key Derivation:
    The derive_key function uses PBKDF2 to generate a secure key from the password and a random salt. This is essential for secure encryption.

  2. Encryption:

    • A random 16-byte salt is generated and stored with the encrypted file to ensure the encryption process is unique every time.

    • A random initialization vector (IV) is also generated for the AES cipher in CBC mode.

    • The file’s content is padded to make its size a multiple of the block size (128 bits) before encryption.

    • After encryption, the salt, IV, and encrypted content are saved into the output file.

  3. Decryption:

    • The salt and IV are read from the encrypted file.

    • The key is derived from the password and the salt.

    • AES decryption is performed, followed by unpadding to restore the original file content.

How to Use:

  1. Run the script.

  2. Choose whether to encrypt or decrypt a file.

  3. Provide the file path, password, and output file name.

The tool will either encrypt or decrypt the file as requested and save the result.

Let me know if you need help modifying or expanding the tool!

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