Freddie Chopin Freddie Chopin - 1 year ago 283
Bash Question

Convert hash string to binary file

What would be the easiest way to convert the text produced by utilities such as

into a binary file?

I'd like to convert hex string like
(example produced by
) into a binary file (64 bytes long), in which each byte's value would be equivalent to a pair of letters/digits from the string. I'm looking for a solution that would require minimal amount of tools, so I'd be happy if this can be done easily with
or some utility from coreutils. I'd rather avoid
, as this doesn't seem to handle such string anyway (I'd have to add "addresses" and some whitespace).

I need the hash as a binary file, to convert it into an object file and link with the application that I'm writing. If there's another way to embed such string (in a binary form!) into application (via an array or whatever) - it's also a solution for me.

Answer Source

A bit of sed and echo might do:

for i in $(echo 77f4de214a5423e3c7df8704f65af57c39c55f08424c75c0931ab09a5bfdf49f5f939f2caeff1e0113d9b3d6363583e4830cf40787100b750cde76f00b8cd3ec | sed 's/../& /g'); do
   echo -ne "\x$i"
done > output.bin

The sed command is splitting the hex string into bytes and the echo shows it as hexadecimal character.

Or in a shorter form with sha512sum output, as suggested in the comment:

echo -ne "$(sha512sum some-file.txt | sed 's/ .*$//; s/../\\x&/g')"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download