unhex.awk: Convert hex encoded strings to ASCII characters

########################################################
# AWK script to convert hex encoded ASCII strings back #
# in to the printable ASCII characters that they       #
# represent.                                           #
# Non-printable characters are converted to a '?'.     #
#                                                      #
# unhex.awk v2013.04.01                                #
# https://malwaremusings.com/scripts/unhex-awk          #
#                                                      #
# usage: awk -f unhex.awk <inputfilename>              #
#   where inputfilename is a text file containing hex  #
#   encoded (0x...) strings.                           #
########################################################


/0x/ {
  while (s = match($0,"0[Xx][0-9A-Fa-f]+",matcharray) > 0) {
    chrstr = "";
    hexdigits = "0123456789abcdef";
    word = tolower(matcharray[0]);
    value = 0;
    for (nibble = 3;nibble <= length(word);nibble++) {
      char = substr(word,nibble,1);
      idx = index(hexdigits,char) - 1;
      value += idx * ((nibble % 2) == 1?16:1);
      if (idx == -1) printf("WARNING: Invalid hex digit %c\n",char) >"/dev/stderr";
      if (nibble % 2 == 0) {
        if ((value >= 0x20) && (value < 0x7f)) {
          chrstr = chrstr sprintf("%c",value);
        } else {
          chrstr = chrstr "?";
        }
        value = 0;
      }
    }
    $0 = substr($0,1,RSTART - 1) "0x\"" chrstr "\"" substr($0,RSTART + RLENGTH);
  }
  print;
}

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