It was some time since my last post, so I decided to write a post about a simple script which I had written recently while trying to decode an attack which was thrown at me 😀
Below script searches and converts each occurrence of the hex into its ASCII equivalent. e.g. \x0a will be converted to \n and \x7A will be converted to z. File contents need not be hex characters only, it can be anything random with some hex characters in it.
It can easily be edited to check and replace hex characters in format 0x7A, but i will leave that for you to do. 🙂
Script is written in python and uses inbuilt modules, re and binascii for regex and hex conversions respectively. Input to the script is filename via command line argument. The script can be made much more simple to understand by dividing the regex match and conversion into different functions but i chose to write it as short as possible. That helped me learn a couple of things on the way. For sure there will be better, shorter, smarter implementations of this out on the internet, but that should not stop you from writing your own. 😉
Below is the script. Hopefully, you will find it helpful 🙂
import sys, binascii, re def decode(filename): with open(filename, 'r') as file_content: #open file content = file_content.read() #read file content #regex for matching hex numbers eg \x0A pattern = re.compile(r'\\x[0-9A-Fa-f][0-9A-Fa-f]') # Substitute each occurance of hex numbers with ASCII equivalent string = re.sub(r'\\x[0-9A-Fa-f][0-9A-Fa-f]', lambda L: binascii.unhexlify((L.group().split('x'))), content) print string # print the output decode(sys.argv) # commandline argument of file