Advertisement
Python253

openssl_toolkit

Apr 8th, 2024
627
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.55 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: openssl_toolkit.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. This script provides basic functionality for working with OpenSSL, including checking if OpenSSL is installed, installing it if necessary,
  9. encrypting and decrypting files using AES-256-CBC encryption, generating RSA private keys and self-signed certificates, and generating
  10. sample text files for testing purposes. Additionally, it allows viewing the content of an encrypted file without decrypting it, and prompts
  11. the user to select a file for encryption or decryption using a file dialog.
  12. """
  13.  
  14. import subprocess
  15. import shutil
  16. import sys
  17. from tkinter import filedialog, Tk
  18.  
  19. def check_openssl():
  20.     """
  21.    Check if OpenSSL is installed on the system. If not, prompt the user to install it.
  22.    """
  23.     try:
  24.         subprocess.run(['openssl', 'version'], check=True, timeout=10)
  25.     except FileNotFoundError:
  26.         print("\nOpenSSL is not installed on your system.\n")
  27.         choice = input("\nDo you want to install OpenSSL?\nOPTIONS:\n1: YES\2: NO\nMake Your Selection (1 or 2): ")
  28.         if choice.lower() == '1':
  29.             install_openssl()
  30.         else:
  31.             print("\nExiting Without Saving...\n")
  32.             sys.exit(1)
  33.     except subprocess.TimeoutExpired:
  34.         print("\nOpenSSL command timed out. Make sure OpenSSL is installed and try again.\n")
  35.         sys.exit(1)
  36.     except subprocess.CalledProcessError:
  37.         print("\nAn error occurred while checking OpenSSL version.\n")
  38.         sys.exit(1)
  39.  
  40. def install_openssl():
  41.     """
  42.    Install OpenSSL using Chocolatey on Windows or manually on other platforms.
  43.    """
  44.     if shutil.which('choco'):
  45.         try:
  46.             subprocess.run(['choco', 'install', 'openssl.light'], timeout=300, check=True)
  47.             print("\nOpenSSL installed successfully using Chocolatey.\n")
  48.         except subprocess.TimeoutExpired:
  49.             print("\nInstallation timed out. Try again later.\n")
  50.             sys.exit(1)
  51.         except subprocess.CalledProcessError:
  52.             print("\nError occurred during installation. Please try again or install manually.\n")
  53.             sys.exit(1)
  54.     else:
  55.         print("\nUnable to install OpenSSL automatically.\n")
  56.         if sys.platform == 'win32':
  57.             print("\nTo install OpenSSL on Windows, you'll need Chocolatey.\n")
  58.             print("\nPlease install Chocolatey from https://chocolatey.org/ and then run the following command in your command prompt:\n")
  59.             print("\nchoco install openssl.light\n")
  60.         else:
  61.             print("\nPlease install OpenSSL manually using your system's package manager or by downloading it from https://wiki.openssl.org/index.php/Binaries\n")
  62.  
  63. def encrypt_file(input_file, output_file):
  64.     """
  65.    Encrypt a file using AES-256-CBC encryption with salt and PBKDF2 key derivation.
  66.    
  67.    Parameters:
  68.        input_file (str): Path to the input file.
  69.        output_file (str): Path to the output encrypted file.
  70.    """
  71.     try:
  72.         subprocess.run(['openssl', 'enc', '-aes-256-cbc', '-salt', '-pbkdf2', '-in', input_file, '-out', output_file, '-k', 'password'], check=True)
  73.         print("\nFile encrypted successfully.\n")
  74.     except subprocess.CalledProcessError:
  75.         print("\nAn error occurred during encryption.\n")
  76.  
  77. def decrypt_file(input_file, output_file):
  78.     """
  79.    Decrypt a file encrypted with AES-256-CBC encryption using salt and PBKDF2 key derivation.
  80.    
  81.    Parameters:
  82.        input_file (str): Path to the input encrypted file.
  83.        output_file (str): Path to the output decrypted file.
  84.    """
  85.     try:
  86.         subprocess.run(['openssl', 'enc', '-d', '-aes-256-cbc', '-pbkdf2', '-in', input_file, '-out', output_file, '-k', 'password'], check=True)
  87.         print("\nFile decrypted successfully.\n")
  88.     except subprocess.CalledProcessError:
  89.         print("\nAn error occurred during decryption.\n")
  90.  
  91. def select_file():
  92.     """
  93.    Opens a file dialog to select a file for encryption or decryption.
  94.    
  95.    Returns:
  96.        str: The path to the selected file.
  97.    """
  98.     root = Tk()
  99.     root.withdraw()  # Hide the main window
  100.     file_path = filedialog.askopenfilename()  # Open file dialog
  101.     return file_path
  102.  
  103. def generate_test_files():
  104.     """
  105.    Generate sample text files for testing encryption and decryption.
  106.    """
  107.     with open("sample_e.txt", "w") as file:
  108.         file.write("This is a sample text file used for testing encryption.")
  109.     with open("sample_d.txt", "w") as file:
  110.         file.write("This is a sample text file used for testing decryption.")
  111.  
  112. def view_encrypted_content(input_file):
  113.     """
  114.    View the content of an encrypted file without decrypting it.
  115.    
  116.    Parameters:
  117.        input_file (str): Path to the input encrypted file.
  118.    """
  119.     try:
  120.         with open(input_file, "rb") as f:
  121.             encrypted_data = f.read()
  122.         print("\nEncrypted content:\n", encrypted_data)
  123.     except FileNotFoundError:
  124.         print("\nFile not found.\n")
  125.     except Exception as e:
  126.         print("\nAn error occurred:", e)
  127.  
  128. check_openssl()
  129.  
  130. print("\nWelcome To OpenSSL Fundamentals!\n")
  131.  
  132. while True:
  133.     print("\nPlease select an option:")
  134.     print("1. Generate a RSA private key")
  135.     print("2. Generate a self-signed certificate")
  136.     print("3. Encrypt a file")
  137.     print("4. Decrypt a file")
  138.     print("5. Generate test files")
  139.     print("6. View encrypted file content")
  140.     print("7. Exit")
  141.  
  142.     option = input()
  143.  
  144.     if option == '1':
  145.         print("\nGenerating RSA private key...\n")
  146.         try:
  147.             subprocess.run(['openssl', 'genrsa', '-out', 'private.key', '2048'], timeout=30, check=True)
  148.             print("\nRSA private key generated successfully.\n")
  149.         except subprocess.TimeoutExpired:
  150.             print("\nOperation timed out. Try again later.\n")
  151.         except subprocess.CalledProcessError:
  152.             print("\nAn error occurred during RSA key generation.\n")
  153.     elif option == '2':
  154.         print("\nGenerating self-signed certificate...\n")
  155.         try:
  156.             subprocess.run(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-keyout', 'private.key', '-out', 'certificate.crt', '-days', '365', '-nodes', '-subj', '/C=US'], timeout=30, check=True)
  157.             print("\nSelf-signed certificate generated successfully.\n")
  158.         except subprocess.TimeoutExpired:
  159.             print("\nOperation timed out. Try again later.\n")
  160.         except subprocess.CalledProcessError:
  161.             print("\nAn error occurred during certificate generation.\n")
  162.     elif option == '3':
  163.         input_file = select_file()
  164.         if input_file:
  165.             encrypted_file = input("\nEnter the output file name without extension (encrypted): ") + ".enc"
  166.             print("\nEncrypting file...\n")
  167.             encrypt_file(input_file, encrypted_file)
  168.     elif option == '4':
  169.         input_file = select_file()
  170.         if input_file:
  171.             output_file = input("\nEnter the output file name without extension (decrypted): ") + ".txt"
  172.             print("\nDecrypting file...\n")
  173.             decrypt_file(input_file, output_file)
  174.     elif option == '5':
  175.         print("\nGenerating test files...\n")
  176.         generate_test_files()
  177.         print("\nTest files generated successfully.\n")
  178.     elif option == '6':
  179.         input_file = select_file()
  180.         if input_file:
  181.             view_encrypted_content(input_file)
  182.     elif option == '7':
  183.         print("\nExiting...\n")
  184.         break
  185.     else:
  186.         print("\nInvalid option. Please select a valid option.\n")
  187.  
  188.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement