Code Snippets - Hex to ASCII

22/02/2017 by 0xm4v3rick

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 :D

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 = #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(('x')[1])), content)

 print string # print the output

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

Coding python

Share on:  Diaspora*