Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: fernet_cipher_tool.py
- # Version: 1.1.0
- # Author: Jeoi Reqi
- """
- This script provides options to generate, delete, encrypt, and decrypt messages using the Fernet symmetric encryption algorithm.
- Requirements:
- - Python 3.x
- - cryptography library
- Functions:
- 1. generate_key():
- - Generates a new Fernet key and saves it to a file.
- 2. load_key():
- - Loads the Fernet key from the key file if it exists.
- 3. delete_key():
- - Deletes the key file if it exists.
- 4. encrypt_message(message, key):
- - Encrypts a message using the provided Fernet key.
- 5. decrypt_message(encrypted_message, key):
- - Decrypts an encrypted message using the stored Fernet key.
- 6. main():
- - Main function to run the Fernet Options Menu.
- Usage:
- 1. Run the script in a Python environment.
- 2. Follow the on-screen prompts to perform various actions such as generating a key,
- encrypting a message, decrypting a message, and deleting the key.
- Additional Notes:
- - The generated Fernet key is saved to a file named "key.txt" in the current working directory.
- - When encrypting or decrypting messages, the script automatically generates a key if none is found.
- - Users can delete the stored key if needed, and the script will inform if no key exists for deletion.
- - All input/output is done via the console, providing a user-friendly interface for interaction.
- """
- import os
- import base64
- from cryptography.fernet import Fernet
- # GENERATE KEY
- def generate_key():
- """
- Generate a new Fernet key and save it to a file.
- Returns:
- bytes: The generated Fernet key.
- """
- key = Fernet.generate_key()
- with open("key.txt", "wb") as key_file:
- key_file.write(key)
- return key
- # LOAD STORED KEY FROM FILE
- def load_key():
- """
- Load the Fernet key from the key file if it exists.
- Returns:
- bytes: The loaded Fernet key if exists, otherwise None.
- """
- if os.path.exists("key.txt"):
- with open("key.txt", "rb") as key_file:
- return key_file.read()
- else:
- print("\nNo saved key found!\n- Generating a new 32-byte Fernet key...")
- return generate_key()
- # DELETE STORED KEY
- def delete_key():
- """
- Delete the key file if it exists.
- """
- if os.path.exists("key.txt"):
- os.remove("key.txt")
- print("\nKey deleted!")
- else:
- print("\nNo key to delete!")
- # ENCRYPTION FUNCTION
- def encrypt_message(message, key):
- """
- Encrypt a message using the provided Fernet key.
- Args:
- message (str): The message to encrypt.
- key (bytes): The Fernet key used for encryption.
- Returns:
- bytes: The encrypted message.
- """
- fernet = Fernet(key)
- print(f"\nEncoding using the stored key:\n- {key.decode()}")
- return fernet.encrypt(message.encode())
- # DECRYPTION FUNCTION
- def decrypt_message(encrypted_message, key):
- """
- Decrypt an encrypted message using the provided Fernet key.
- Args:
- encrypted_message (bytes): The encrypted message to decrypt.
- key (bytes): The Fernet key used for decryption.
- Returns:
- str: The decrypted message.
- """
- fernet = Fernet(key)
- print(f"\nDecoding using the stored key:\n- {key.decode()}")
- return fernet.decrypt(encrypted_message).decode()
- # MAIN MENU
- def main():
- """
- Main function to run the Fernet Options Menu.
- """
- while True:
- print("\n" + "*" * 50)
- print("\t :: Fernet Options Menu ::")
- print("*" * 50 + "\n")
- print("\t 1. \tGenerate Key")
- print("\t 2. \tDelete Key")
- print("\t 3. \tEncrypt Message")
- print("\t 4. \tDecrypt Message")
- print("\t 5. \tExit Program\n")
- print("*" * 50)
- choice = input("Enter your choice (1-4) or... 5 to EXIT: ")
- if choice == "1":
- key = generate_key()
- print("\nGenerated Key:", key.decode())
- elif choice == "2":
- delete_key()
- elif choice == "3":
- message = input("\nEnter the message to encrypt: ")
- key = load_key()
- encrypted_message = encrypt_message(message, key)
- print("\nEncrypted Message:", encrypted_message.decode())
- elif choice == "4":
- encrypted_message = input("\nEnter the encrypted message: ")
- key = load_key()
- decrypted_message = decrypt_message(encrypted_message.encode(), key)
- print("\nDecrypted Message:", decrypted_message)
- elif choice == "5":
- print("\nExiting Program...\tGoodbye!\n")
- break
- else:
- print("\nInvalid choice! Please enter 1, 2, 3, 4, or 5.\n")
- if __name__ == "__main__":
- main()
Add Comment
Please, Sign In to add comment