Advertisement
Python253

sha256_database_verify

May 17th, 2024
731
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.62 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: sha256_database_verify.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - This script allows users to verify SHA-256 hashes against a database.
  10.    - It loads a SHA-256 dictionary from a file, prompts the user to input a string & computes the SHA-256 hash of the input string.
  11.    - It then checks if the user input string already exists in the dictionary.
  12.    - If the string is not found, the user has the option to save it to the database.
  13.  
  14. Functions:
  15.    - sha256sum(string):
  16.        Returns the SHA-256 hash of a given string.
  17.    - load_sha256_database(filename):
  18.        Loads the SHA-256 dictionary from a file.
  19.    - save_sha256_database(sha256_dict, filename):
  20.        Saves the SHA-256 dictionary to a file.
  21.    - main():
  22.        Main function to execute the script.
  23.  
  24. Requirements:
  25.    - Python 3.x
  26.  
  27. Usage:
  28.    - Run the script and follow the prompts. Enter a string to look up its SHA-256 hash, or type 'exit' to quit.
  29.    - If the string is not found in the database, you will be prompted to save it.
  30.  
  31. Additional Notes:
  32.    - Make sure the database file exists and is accessible.
  33.    - The database file will be overwritten if any changes are made.
  34. """
  35.  
  36. import hashlib
  37.  
  38. def sha256sum(string):
  39.     """
  40.    Return the SHA-256 hash of a given string.
  41.  
  42.    Args:
  43.        string (str): The input string for which the SHA-256 hash will be calculated.
  44.  
  45.    Returns:
  46.        str: The SHA-256 hash of the input string.
  47.    """
  48.     return hashlib.sha256(string.encode()).hexdigest()
  49.  
  50. def load_sha256_database(filename):
  51.     """
  52.    Load the SHA-256 dictionary from a file.
  53.  
  54.    Args:
  55.        filename (str): The filename of the file containing the SHA-256 dictionary.
  56.  
  57.    Returns:
  58.        dict: The loaded SHA-256 dictionary.
  59.    """
  60.     sha256_dict = {}
  61.     with open(filename, 'r', encoding='utf-8') as infile:
  62.         for line in infile:
  63.             # Extract string and SHA-256 hash from each line
  64.             parts = line.strip().split(':', 1)
  65.             if len(parts) == 2:
  66.                 string, sha256_hash = parts
  67.                 # Remove quotes and whitespace from string
  68.                 string = string.strip().strip('"')
  69.                 # Remove quotes, whitespace, and trailing comma from SHA-256 hash
  70.                 sha256_hash = sha256_hash.strip().strip('"').strip(',')
  71.                 # Add to the dictionary
  72.                 sha256_dict[string] = sha256_hash
  73.     return sha256_dict
  74.  
  75. def save_sha256_database(sha256_dict, filename):
  76.     """
  77.    Save the SHA-256 dictionary to a file.
  78.  
  79.    Args:
  80.        sha256_dict (dict): The SHA-256 dictionary to be saved.
  81.        filename (str): The filename of the file where the SHA-256 dictionary will be saved.
  82.    """
  83.     with open(filename, 'w', encoding='utf-8') as outfile:
  84.         for string, sha256_hash in sorted(sha256_dict.items()):
  85.             outfile.write(f'"{string}": "{sha256_hash}",\n')
  86.  
  87. def main():
  88.     # Load the SHA-256 dictionary
  89.     database_filename = 'sum_sha256_dict.txt'
  90.     sha256_dict = load_sha256_database(database_filename)
  91.  
  92.     while True:
  93.         # Get user input
  94.         user_input = input("\nEnter a string to look up its SHA-256 hash (or type 'exit' to quit): ").strip()
  95.  
  96.         # Check if the user wants to exit
  97.         if user_input.lower() == 'exit':
  98.             print("\nExiting the program...\tGoodbye!\n")
  99.             break
  100.  
  101.         # Compute the SHA-256 hash of the user input
  102.         user_sha256 = sha256sum(user_input)
  103.  
  104.         print("\nComputed SHA-256 hash:")
  105.         print(user_sha256)
  106.  
  107.         # Check if the SHA-256 hash exists in the dictionary
  108.         if user_input in sha256_dict:
  109.             print(f"\nThe user string '{user_input}' was found in the database.")
  110.             print(f"\nUser string: {user_input}")
  111.             print(f"SHA-256 hash: {sha256_dict[user_input]}")
  112.         else:
  113.             print(f"\nThe user string '{user_input}' was not found in the database.")
  114.             # Ask the user if they want to save the string and its SHA-256 hash to the database
  115.             save_option = input("\nDo you want to save this string and its SHA-256 hash to the database?\n1: Yes\n2: No\n\nMake your selection (1 or 2): ").strip()
  116.             if save_option == '1':
  117.                 sha256_dict[user_input] = user_sha256
  118.                 save_sha256_database(sha256_dict, database_filename)
  119.                 print("\nString and its SHA-256 hash saved to the database.")
  120.             else:
  121.                 print("\nString and its SHA-256 hash not saved to the database!")
  122.  
  123. if __name__ == "__main__":
  124.     main()
  125.  
  126.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement