Thursday, July 05, 2012

Convert a Hex dump to Binary data with xxd

In my last blog post, I demonstarted how to dump a binary file, using either 'hexdump' or 'xxd'.
In summary, we can do this:
# ls -l hash-file.bin
-rw-r--r-- 1 root root 20 Jul 4 10:05 hash-file.bin
# xxd -p hash-file.bin

Ok, what if we want to do the reverse of this.
That is to take a string of hex characters and create a binary file!
The utility 'xxd' can also do this.

To demonstrate, lets first save the hex representation into a separate file:

# xxd -p hash-file.bin > hash-file.hex
# ls -l hash-file.hex
-rw-r--r-- 1 root root 41 Jul 4 12:04 hash-file.hex
# cat hash-file.hex

Ok, here's the clever part. Note we now pass the '-r' option to xdd to 'reverse' it's operation.
# xxd -p -r hash-file.hex > new-file.bin
# ls -l new-file.bin
-rw-r--r-- 1 root root 20 Jul 4 12:19 new-file.bin
# xxd -p new-file.bin
# cmp hash-file.bin new-file.bin

So we recreated the binary file, as 'new-file.bin' from the hex dump and we proved it is identical to the file we started with.

You can also feed into xdd from the pipeline, like this:

# cat hash-file.hex | xxd -p -r > new-file.bin
# xxd -p new-file.bin

..and here are some more examples:
# echo -n 'password' | xxd -p | xxd -p -r | hexdump -C
00000000  70 61 73 73 77 6f 72 64                           |password|

# echo -n 'c0a06003' | xxd -p -r | hexdump -C
00000000  c0 a0 60 03                                       |..`.|

No comments: