Python253

encoding_identifier_utility

May 18th, 2024
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.13 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: encoding_identifier_utility.py
  4. # Version: 1.0.1
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - This script identifies and decodes various types of encoded or obfuscated data.
  10.    - It supports Base64, hexadecimal, binary, and ASCII encoding.
  11.    - Additionally, it offers to try Caesar Shift decryption (ROT 1-26) if the input data does not match any of the other encoding types.
  12.  
  13. Functions:
  14.    - decode_base64(data):
  15.        Decodes Base64 encoded data.
  16.    - decode_hexadecimal(data):
  17.        Decodes hexadecimal encoded data.
  18.    - decode_binary(data):
  19.        Decodes binary encoded data.
  20.    - decode_ascii(data):
  21.        Decodes ASCII encoded data.
  22.    - caesar_shift_decrypt(data, shift):
  23.        Decrypts data encoded with a Caesar Shift cipher.
  24.    - is_printable(text):
  25.        Checks if the text contains only printable ASCII characters.
  26.    - line():
  27.        Prints a line separator.
  28.    - main():
  29.        Main function to run the encoding identification utility.
  30.  
  31. Requirements:
  32.    - Python 3.x
  33.    - base64 module (Part of Python's standard library)
  34.  
  35. Usage:
  36.    - Run the script and input the encoded/obfuscated data when prompted. The script will attempt to identify and decode the data, and if no match is found, it will offer to try Caesar Shift decryption.
  37.  
  38. Additional Notes:
  39.    - If the script does not find a matching encoding type, it suggests trying other decoding methods like URL encoding, Morse code, Base32 encoding, XOR encryption, etc.
  40.    - The script includes error handling to manage invalid inputs and unexpected errors gracefully.
  41. """
  42.  
  43. import base64
  44.  
  45. def decode_base64(data):
  46.     """
  47.    Decodes Base64 encoded data.
  48.  
  49.    Args:
  50.        data (str): The Base64 encoded data string.
  51.  
  52.    Returns:
  53.        bytes or None: The decoded data if successful, otherwise None.
  54.    """
  55.     try:
  56.         decoded_data = base64.b64decode(data)
  57.         decoded_data.decode("utf-8")  # Verify if it's valid UTF-8 text
  58.         return decoded_data
  59.     except Exception:
  60.         return None
  61.  
  62. def decode_hexadecimal(data):
  63.     """
  64.    Decodes hexadecimal encoded data.
  65.  
  66.    Args:
  67.        data (str): The hexadecimal encoded data string.
  68.  
  69.    Returns:
  70.        bytes or None: The decoded data if successful, otherwise None.
  71.    """
  72.     try:
  73.         hex_values = data.split()
  74.         decoded_data = bytes(int(value, 16) for value in hex_values)
  75.         decoded_data.decode("utf-8")  # Verify if it's valid UTF-8 text
  76.         return decoded_data
  77.     except Exception:
  78.         return None
  79.  
  80. def decode_binary(data):
  81.     """
  82.    Decodes binary encoded data.
  83.  
  84.    Args:
  85.        data (str): The binary encoded data string.
  86.  
  87.    Returns:
  88.        str or None: The decoded data if successful, otherwise None.
  89.    """
  90.     try:
  91.         if all(bit in "01" for bit in data.replace(" ", "")):
  92.             decoded_data = "".join(chr(int(chunk, 2)) for chunk in data.split())
  93.             return decoded_data
  94.         else:
  95.             return None
  96.     except Exception:
  97.         return None
  98.  
  99. def decode_ascii(data):
  100.     """
  101.    Decodes ASCII encoded data.
  102.  
  103.    Args:
  104.        data (str): The ASCII encoded data string.
  105.  
  106.    Returns:
  107.        str or None: The decoded data if successful, otherwise None.
  108.    """
  109.     try:
  110.         ascii_values = [int(sub) for sub in data.split()]
  111.         if all(0 <= value <= 127 for value in ascii_values):
  112.             decoded_data = "".join(chr(value) for value in ascii_values)
  113.             return decoded_data
  114.         else:
  115.             return None
  116.     except Exception:
  117.         return None
  118.  
  119. def caesar_shift_decrypt(data, shift):
  120.     """
  121.    Decrypts data encoded with a Caesar Shift cipher.
  122.  
  123.    Args:
  124.        data (str): The Caesar Shift encoded data string.
  125.        shift (int): The ROT value (1-26) for decryption.
  126.  
  127.    Returns:
  128.        str: The decrypted data.
  129.    """
  130.     decrypted_data = ""
  131.     for char in data:
  132.         if char.isalpha():
  133.             shifted_char = chr(
  134.                 ((ord(char) - ord("A" if char.isupper() else "a") - shift) % 26)
  135.                 + ord("A" if char.isupper() else "a")
  136.             )
  137.             decrypted_data += shifted_char
  138.         else:
  139.             decrypted_data += char
  140.     return decrypted_data
  141.  
  142. def is_printable(text):
  143.     """
  144.    Checks if the text contains only printable ASCII characters.
  145.  
  146.    Args:
  147.        text (str): The text to check.
  148.  
  149.    Returns:
  150.        bool: True if all characters are printable, False otherwise.
  151.    """
  152.     return all(32 <= ord(char) <= 126 for char in text)
  153.  
  154. def line():
  155.     """
  156.    Prints a line separator.
  157.    """
  158.     print("_" * 70, "\n")
  159.  
  160. def main():
  161.     """
  162.    Main function to run the encoding identification utility.
  163.    """
  164.     while True:
  165.         try:
  166.             while True:
  167.                 # User input
  168.                 encoded_data = input("\nEnter the encoded string or obfuscated data: ")
  169.                 line()
  170.  
  171.                 # Validate that the input is not empty
  172.                 if not encoded_data.strip():
  173.                     raise ValueError("\nInput cannot be empty!\n")
  174.  
  175.                 # ASCII decoding
  176.                 ascii_decoded = decode_ascii(encoded_data)
  177.                 ascii_match = ascii_decoded is not None
  178.                 print("\t   ASCII Match:      ", ascii_match)
  179.  
  180.                 # Base64 decoding
  181.                 base64_decoded = decode_base64(encoded_data)
  182.                 base64_match = base64_decoded is not None
  183.                 print("\t   Base64 Match:     ", base64_match)
  184.  
  185.                 # Binary decoding
  186.                 binary_decoded = decode_binary(encoded_data)
  187.                 binary_match = binary_decoded is not None
  188.                 print("\t   Binary Match:     ", binary_match)
  189.  
  190.                 # Hexadecimal decoding
  191.                 hex_decoded = decode_hexadecimal(encoded_data)
  192.                 hex_match = hex_decoded is not None
  193.                 print("\t   Hexadecimal Match:", hex_match)
  194.                 line()
  195.  
  196.                 # Determine the type of input
  197.                 input_type = None
  198.                 decoded_data = None
  199.                 if ascii_match:
  200.                     input_type = "ASCII"
  201.                     decoded_data = ascii_decoded
  202.                 elif base64_match:
  203.                     input_type = "Base64"
  204.                     decoded_data = base64_decoded.decode("utf-8")
  205.                 elif binary_match:
  206.                     input_type = "Binary"
  207.                     decoded_data = binary_decoded
  208.                 elif hex_match:
  209.                     input_type = "Hexadecimal"
  210.                     decoded_data = hex_decoded.decode("utf-8")
  211.  
  212.                 # Print the input type and decoded data
  213.                 if input_type:
  214.                     print(f"\nThe input string is being identified as - {input_type} -")
  215.                     print(f"Decoded {input_type} data: {decoded_data}")
  216.                 else:
  217.                     print("\t        Failed to identify the input type used!")
  218.                     line()
  219.  
  220.                 while True:  # Loop for Caesar Shift option
  221.                     # Ask user if they want to try Caesar Shift
  222.                     try_caesar = input(
  223.                         "Do you want to try Caesar Shift (ROT 1-26)?\n1: Yes\n2: No\nMake your selection (1 or 2):"
  224.                     )
  225.                     if try_caesar == "1":
  226.                         line()
  227.                         print("Caesar Shift (ROT 1-26) results:\n")
  228.                         caesar_results = []
  229.                         for shift in range(1, 27):
  230.                             caesar_decoded = caesar_shift_decrypt(encoded_data, shift)
  231.                             if is_printable(caesar_decoded):
  232.                                 caesar_results.append((shift, caesar_decoded))
  233.                                 print(f"ROT {shift:02}: {caesar_decoded}")
  234.                             else:
  235.                                 line()
  236.                                 print(
  237.                                     "\n\t        Invalid input! Please enter 1 or 2.\n"
  238.                                 )
  239.                                 line()
  240.                         break  # Exit the Caesar Shift loop
  241.  
  242.                     elif try_caesar == "2":
  243.                         print("Exiting program... \tGoodbye!\n")
  244.                         return
  245.  
  246.                     else:
  247.                         line()
  248.                         print("\n\t        Invalid input! Please enter 1 or 2.\n")
  249.                         line()
  250.                         break
  251.  
  252.                 while True:  # Loop for input validation
  253.                     line()
  254.                     found = input(
  255.                         "Did any of the Caesar Shift results return the expected data?\n1: Yes\n2: No\nMake your selection (1 or 2):"
  256.                     )
  257.                     if found == "1":
  258.                         while True:  # Loop for ROT value validation
  259.                             try:
  260.                                 rot_value = int(
  261.                                     input(
  262.                                         "\nPlease enter the ROT value that matched your expected result: "
  263.                                     )
  264.                                 )
  265.                                 if 1 <= rot_value <= 26:
  266.                                     matching_result = next(
  267.                                         (
  268.                                             result
  269.                                             for shift, result in caesar_results
  270.                                             if shift == rot_value
  271.                                         ),
  272.                                         None,
  273.                                     )
  274.                                     if matching_result is not None:
  275.                                         line()
  276.                                         print(
  277.                                             "\t        Congratulations on finding a match!"
  278.                                         )
  279.                                         line()
  280.                                         print(
  281.                                             f"The input string is being identified as Caesar Shift (ROT-{rot_value})"
  282.                                         )
  283.                                         print(
  284.                                             "\nDecoded Caesar Shift data:\n\n\t",
  285.                                             matching_result,
  286.                                         )
  287.                                         line()
  288.                                         continue_or_exit = input(
  289.                                             "Do you want to input another string?\n1: Yes\n2: No\nMake your selection (1 or 2):"
  290.                                         )
  291.                                         if continue_or_exit == "2":
  292.                                             print("\nExiting program... \tGoodbye!\n")
  293.                                             return
  294.                                         else:
  295.                                             break  # Exit the ROT value loop and go back to asking for another string
  296.                                     else:
  297.                                         line()
  298.                                         print(
  299.                                             "\n\tInvalid ROT value! Please enter a value between 1 and 26."
  300.                                         )
  301.                                         line()
  302.                                 else:
  303.                                     line()
  304.                                     print(
  305.                                         "\n\tInvalid ROT value! Please enter a value between 1 and 26."
  306.                                     )
  307.                                     line()
  308.                             except ValueError:
  309.                                 line()
  310.                                 print(
  311.                                     "\n\tInvalid input! Please enter a valid integer value."
  312.                                 )
  313.                                 line()
  314.                     elif found == "2":
  315.                         print(
  316.                             "\t        Sorry you could not find a match :(\n\nYou may want to try other decoding methods like URL encoding,\nMorse code, Base32 encoding, XOR encryption, or others."
  317.                         )
  318.                         line()
  319.                         print("Exiting program... \tGoodbye!\n")
  320.                         return
  321.                     else:
  322.                         line()
  323.                         print("\n\t        Invalid input! Please enter 1 or 2.\n")
  324.                         line()
  325.                         break  # Break from the input validation loop and go back to asking for another string
  326.                     break  # Break from the Caesar Shift loop and go back to asking for another string
  327.  
  328.         except ValueError as e:
  329.             line()
  330.             print(f"\n\tError: {e}\n")
  331.             line()
  332.         except Exception as e:
  333.             line()
  334.             print(f"\n\tAn unexpected error occurred: {e}\n")
  335.             line()
  336.  
  337. if __name__ == "__main__":
  338.     main()
  339.  
Add Comment
Please, Sign In to add comment