Code Snippets – Hex to ASCII

Hello again!
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 🙂
Cheers!!!

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')[1])), content)

 print string # print the output

decode(sys.argv[1]) # commandline argument of file

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s