Python253

fernet_cipher_tool

May 7th, 2024
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.87 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: fernet_cipher_tool.py
  4. # Version: 1.1.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. This script provides options to generate, delete, encrypt, and decrypt messages using the Fernet symmetric encryption algorithm.
  9.  
  10. Requirements:
  11.    - Python 3.x
  12.    - cryptography library
  13.  
  14. Functions:
  15.    1. generate_key():
  16.       - Generates a new Fernet key and saves it to a file.
  17.    2. load_key():
  18.       - Loads the Fernet key from the key file if it exists.
  19.    3. delete_key():
  20.       - Deletes the key file if it exists.
  21.    4. encrypt_message(message, key):
  22.       - Encrypts a message using the provided Fernet key.
  23.    5. decrypt_message(encrypted_message, key):
  24.       - Decrypts an encrypted message using the stored Fernet key.
  25.    6. main():
  26.       - Main function to run the Fernet Options Menu.
  27.  
  28. Usage:
  29.    1. Run the script in a Python environment.
  30.    2. Follow the on-screen prompts to perform various actions such as generating a key,
  31.       encrypting a message, decrypting a message, and deleting the key.
  32.  
  33. Additional Notes:
  34.    - The generated Fernet key is saved to a file named "key.txt" in the current working directory.
  35.    - When encrypting or decrypting messages, the script automatically generates a key if none is found.
  36.    - Users can delete the stored key if needed, and the script will inform if no key exists for deletion.
  37.    - All input/output is done via the console, providing a user-friendly interface for interaction.
  38. """
  39.  
  40. import os
  41. import base64
  42. from cryptography.fernet import Fernet
  43.  
  44. # GENERATE KEY
  45. def generate_key():
  46.     """
  47.    Generate a new Fernet key and save it to a file.
  48.  
  49.    Returns:
  50.        bytes: The generated Fernet key.
  51.    """
  52.     key = Fernet.generate_key()
  53.     with open("key.txt", "wb") as key_file:
  54.         key_file.write(key)
  55.     return key
  56.  
  57. # LOAD STORED KEY FROM FILE
  58. def load_key():
  59.     """
  60.    Load the Fernet key from the key file if it exists.
  61.  
  62.    Returns:
  63.        bytes: The loaded Fernet key if exists, otherwise None.
  64.    """
  65.     if os.path.exists("key.txt"):
  66.         with open("key.txt", "rb") as key_file:
  67.             return key_file.read()
  68.     else:
  69.         print("\nNo saved key found!\n- Generating a new 32-byte Fernet key...")
  70.         return generate_key()
  71.  
  72. # DELETE STORED KEY
  73. def delete_key():
  74.     """
  75.    Delete the key file if it exists.
  76.    """
  77.     if os.path.exists("key.txt"):
  78.         os.remove("key.txt")
  79.         print("\nKey deleted!")
  80.     else:
  81.         print("\nNo key to delete!")
  82.  
  83. # ENCRYPTION FUNCTION
  84. def encrypt_message(message, key):
  85.     """
  86.    Encrypt a message using the provided Fernet key.
  87.  
  88.    Args:
  89.        message (str): The message to encrypt.
  90.        key (bytes): The Fernet key used for encryption.
  91.  
  92.    Returns:
  93.        bytes: The encrypted message.
  94.    """
  95.     fernet = Fernet(key)
  96.     print(f"\nEncoding using the stored key:\n- {key.decode()}")
  97.     return fernet.encrypt(message.encode())
  98.  
  99. # DECRYPTION FUNCTION
  100. def decrypt_message(encrypted_message, key):
  101.     """
  102.    Decrypt an encrypted message using the provided Fernet key.
  103.  
  104.    Args:
  105.        encrypted_message (bytes): The encrypted message to decrypt.
  106.        key (bytes): The Fernet key used for decryption.
  107.  
  108.    Returns:
  109.        str: The decrypted message.
  110.    """
  111.     fernet = Fernet(key)
  112.     print(f"\nDecoding using the stored key:\n- {key.decode()}")
  113.     return fernet.decrypt(encrypted_message).decode()
  114.  
  115. # MAIN MENU
  116. def main():
  117.     """
  118.    Main function to run the Fernet Options Menu.
  119.    """
  120.     while True:
  121.         print("\n" + "*" * 50)
  122.         print("\t  :: Fernet Options Menu ::")
  123.         print("*" * 50 + "\n")
  124.         print("\t   1. \tGenerate Key")
  125.         print("\t   2. \tDelete Key")
  126.         print("\t   3. \tEncrypt Message")
  127.         print("\t   4. \tDecrypt Message")
  128.         print("\t   5. \tExit Program\n")
  129.         print("*" * 50)
  130.         choice = input("Enter your choice (1-4) or... 5 to EXIT: ")
  131.  
  132.         if choice == "1":
  133.             key = generate_key()
  134.             print("\nGenerated Key:", key.decode())
  135.         elif choice == "2":
  136.             delete_key()
  137.         elif choice == "3":
  138.             message = input("\nEnter the message to encrypt: ")
  139.             key = load_key()
  140.             encrypted_message = encrypt_message(message, key)
  141.             print("\nEncrypted Message:", encrypted_message.decode())
  142.         elif choice == "4":
  143.             encrypted_message = input("\nEnter the encrypted message: ")
  144.             key = load_key()
  145.             decrypted_message = decrypt_message(encrypted_message.encode(), key)
  146.             print("\nDecrypted Message:", decrypted_message)
  147.         elif choice == "5":
  148.             print("\nExiting Program...\tGoodbye!\n")
  149.             break
  150.         else:
  151.             print("\nInvalid choice! Please enter 1, 2, 3, 4, or 5.\n")
  152.  
  153. if __name__ == "__main__":
  154.     main()
  155.  
Add Comment
Please, Sign In to add comment