File Encryption Tool Project (code) in Python

← Back to Projects

File Encryption Tool in Python

About the project: This is a project for a File Encryption Tool. This code uses the cryptography library, which is a modern and secure library for cryptographic operations in Python.

This project is a great way to learn about symmetric encryption and how to securely handle data. The script will be able to encrypt and decrypt any file you choose.

Instructions

  1. Install cryptography: This project uses the cryptography library, which is not part of the standard Python installation. You'll need to install it first:
    
      pip install cryptography
      
  2. Save the Code: Save the code below as a file named file_encryption_tool.py.
  3. Place a File: Make sure you have a file you want to encrypt (e.g., document.txt) in the same directory as your Python script.
  4. Run the App: Open your terminal or command prompt, navigate to the directory where you saved the file, and run the script:
    
      python file_encryption_tool.py
      
  5. Follow the Prompts: The application will prompt you to choose whether to encrypt or decrypt, enter the file path, and provide a password. The password will be hidden as you type it. The encrypted file will have .encrypted added to its name.
The tool securely generates a unique salt for each encryption and uses a password-based key derivation function (PBKDF2HMAC) to create a strong encryption key.
This makes it resistant to common attacks like rainbow table attacks.
The salt is stored at the beginning of the encrypted file, which is a standard practice that allows for correct decryption.

Project Level: Intermediate

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE).



# file_encryption_tool.py

import os
import base64
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
import getpass # Used for securely getting the password

def derive_key(password, salt):
    """
    Derives a cryptographic key from a password and salt using PBKDF2.

    Args:
        password (bytes): The user's password in bytes.
        salt (bytes): A randomly generated salt in bytes.

    Returns:
        bytes: The derived key suitable for use with Fernet.
    """
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    key = base64.urlsafe_b64encode(kdf.derive(password))
    return key

def encrypt_file(file_path, password):
    """
    Encrypts a file using a key derived from a password.

    Args:
        file_path (str): The path to the file to encrypt.
        password (str): The password to use for encryption.
    """
    try:
        # Generate a random salt for security
        salt = os.urandom(16)

        # Derive the key from the password and salt
        key = derive_key(password.encode(), salt)
        f = Fernet(key)

        # Read the original file data
        with open(file_path, "rb") as file:
            file_data = file.read()

        # Encrypt the data
        encrypted_data = f.encrypt(file_data)

        # Create a new file name for the encrypted file
        encrypted_file_path = f"{file_path}.encrypted"

        # Write the salt and encrypted data to the new file
        # The salt is needed to decrypt the file later
        with open(encrypted_file_path, "wb") as file:
            file.write(salt + encrypted_data)

        print(f"File encrypted successfully: {encrypted_file_path}")
    except FileNotFoundError:
        print(f"Error: The file at path '{file_path}' was not found.")
    except Exception as e:
        print(f"An unexpected error occurred during encryption: {e}")

def decrypt_file(file_path, password):
    """
    Decrypts an encrypted file using a key derived from a password.

    Args:
        file_path (str): The path to the file to decrypt.
        password (str): The password to use for decryption.
    """
    try:
        # Read the salt and encrypted data from the file
        with open(file_path, "rb") as file:
            salt = file.read(16)
            encrypted_data = file.read()

        # Derive the key from the password and the stored salt
        key = derive_key(password.encode(), salt)
        f = Fernet(key)

        # Decrypt the data
        decrypted_data = f.decrypt(encrypted_data)

        # Create a new file name for the decrypted file
        if file_path.endswith(".encrypted"):
            decrypted_file_path = file_path[:-10]
        else:
            decrypted_file_path = f"{file_path}.decrypted"

        # Write the decrypted data to the new file
        with open(decrypted_file_path, "wb") as file:
            file.write(decrypted_data)

        print(f"File decrypted successfully: {decrypted_file_path}")
    except FileNotFoundError:
        print(f"Error: The file at path '{file_path}' was not found.")
    except Exception as e:
        print(f"An unexpected error occurred during decryption: {e}")
        print("Please check if the password is correct.")

def main():
    """
    Main function to run the File Encryption Tool with a user interface.
    """
    print("--- Python File Encryption Tool ---")

    while True:
        action = input("\nDo you want to (E)ncrypt or (D)ecrypt a file? ('q' to quit): ").strip().lower()

        if action == 'q':
            print("Exiting. Goodbye!")
            break

        if action not in ['e', 'd']:
            print("Invalid choice. Please enter 'e' or 'd'.")
            continue

        file_path = input("Enter the path to the file: ").strip()

        if not os.path.exists(file_path):
            print(f"Error: File '{file_path}' not found.")
            continue

        # Use getpass to securely input the password without it being visible
        password = getpass.getpass("Enter the password: ")

        if action == 'e':
            encrypt_file(file_path, password)
        elif action == 'd':
            decrypt_file(file_path, password)

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()





← Back to Projects