Converting Hex to Text - the Bash Way

carlyraejepsenstan

CarlyRaeJepsenStan

Posted on March 14, 2022

Converting Hex to Text - the Bash Way

Let's start by pretending someone gave us some pure plain-text bytes, like this:
68656c6c6f20776f726c64

What are we going to do to find the hidden message?

First, we know that hexadecimal bytes are always 2 characters - you can verify this by using man ascii in your terminal and checking out the tables it shows. Next, we know that you can convert a hex byte into ASCII (or text) by using echo like this:

echo -e "\x61"

# a
Enter fullscreen mode Exit fullscreen mode

What I thought we could do is split the hex string into an array of two-character pieces, and then use a loop to print them like above. So deciphering our hex string is actually pretty straightforwards!

You can use the command fold to first split up the string:

 ~
  ▲ echo $(echo 68656c6c6f20776f726c64 | fold -w2))
68 65 6c 6c 6f 20 77 6f 72 6c 64
Enter fullscreen mode Exit fullscreen mode

And here's a cool fact: by default, anything with spaces is automatically split into a loopable array by bash!

In case you forgot, you use arrays in bash using a rather odd notation: ${arrayname[location]}.

So if we call our previous output spaced:

for i in ${spaced[@]}; 
 do echo -n -e "\x$i";
done
Enter fullscreen mode Exit fullscreen mode

Easy! Thanks for reading my short tutorial, and have a great day. You never know when this might come in useful...

💖 💪 🙅 🚩
carlyraejepsenstan
CarlyRaeJepsenStan

Posted on March 14, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related