Advertisement
Python253

md5_database_verify

May 17th, 2024 (edited)
536
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.42 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: md5_database_verify.py
  4. # Version: 1.0.2
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - This script allows users to verify MD5 sums against a database.
  10.    - It loads an MD5 dictionary from a file, prompts the user to input a string & computes the MD5 sum 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.    - md5sum(string):
  16.        Returns the MD5 sum of a given string.
  17.    - load_md5_database(filename):
  18.        Loads the MD5 dictionary from a file.
  19.    - save_md5_database(md5_dict, filename):
  20.        Saves the MD5 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 MD5 sum, 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. import json
  38. import os
  39.  
  40. def md5sum(string):
  41.     """
  42.    Return the MD5 sum of a given string.
  43.  
  44.    Args:
  45.        string (str): The input string for which the MD5 sum will be calculated.
  46.  
  47.    Returns:
  48.        str: The MD5 sum of the input string.
  49.    """
  50.     return hashlib.md5(string.encode()).hexdigest()
  51.  
  52. def load_md5_database(filename):
  53.     """
  54.    Load the MD5 dictionary from a file.
  55.  
  56.    Args:
  57.        filename (str): The filename of the file containing the MD5 dictionary.
  58.  
  59.    Returns:
  60.        dict: The loaded MD5 dictionary.
  61.    """
  62.     md5_dict = {}
  63.     with open(filename, 'r', encoding='utf-8') as infile:
  64.         for line in infile:
  65.             # Extract string and MD5 hash from each line
  66.             parts = line.strip().split(':', 1)
  67.             if len(parts) == 2:
  68.                 string, md5_hash = parts
  69.                 # Remove quotes and whitespace from string
  70.                 string = string.strip().strip('"')
  71.                 # Remove quotes, whitespace, and trailing comma from MD5 hash
  72.                 md5_hash = md5_hash.strip().strip('"').strip(',')
  73.                 # Add to the dictionary
  74.                 md5_dict[string] = md5_hash
  75.     return md5_dict
  76.  
  77. def save_md5_database(md5_dict, filename):
  78.     """
  79.    Save the MD5 dictionary to a file.
  80.  
  81.    Args:
  82.        md5_dict (dict): The MD5 dictionary to be saved.
  83.        filename (str): The filename of the file where the MD5 dictionary will be saved.
  84.    """
  85.     with open(filename, 'w', encoding='utf-8') as outfile:
  86.         for string, md5_hash in sorted(md5_dict.items()):
  87.             outfile.write(f'"{string}": "{md5_hash}",\n')
  88.  
  89. def main():
  90.     # Load the MD5 dictionary
  91.     database_filename = 'sum_md5_dict.txt'
  92.     md5_dict = load_md5_database(database_filename)
  93.  
  94.     while True:
  95.         # Get user input
  96.         user_input = input("\nEnter a string to look up its MD5 sum (or type 'exit' to quit): ").strip()
  97.  
  98.         # Check if the user wants to exit
  99.         if user_input.lower() == 'exit':
  100.             print("\nExiting the program...\tGoodBye!\n")
  101.             break
  102.  
  103.         # Compute the MD5 sum of the user input
  104.         user_md5 = md5sum(user_input)
  105.  
  106.         print("\nComputed MD5 sum:")
  107.         print(user_md5)
  108.  
  109.         # Check if the MD5 sum exists in the dictionary
  110.         if user_input in md5_dict:
  111.             print(f"\nThe user string '{user_input}' was found in the database.")
  112.             print(f"\nUser string: {user_input}")
  113.             print(f"MD5 sum: {md5_dict[user_input]}")
  114.         else:
  115.             print(f"\nThe user string '{user_input}' was not found in the database.")
  116.             # Ask the user if they want to save the string and its MD5 sum to the database
  117.             save_option = input("\nDo you want to save this string and its MD5 sum to the database?\n1: Yes\n2: No\n\nMake your selection (1 or 2): ").strip()
  118.             if save_option == '1':
  119.                 md5_dict[user_input] = user_md5
  120.                 save_md5_database(md5_dict, database_filename)
  121.                 print("\nString and its MD5 sum saved to the database.")
  122.             else:
  123.                 print("\nString and its MD5 sum not saved to the database!")
  124.  
  125. if __name__ == "__main__":
  126.     main()
  127.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement