1

What would be the easiest way to convert the text produced by utilities such as sha512sum into a binary file?

I'd like to convert hex string like 77f4de214a5423e3c7df8704f65af57c39c55f08424c75c0931ab09a5bfdf49f5f939f2caeff1e0113d9b3d6363583e4830cf40787100b750cde76f00b8cd3ec (example produced by sha512sum) 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 bash, sed or some utility from coreutils. I'd rather avoid xxd, 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.

5 Answers 5

4

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')"
Sign up to request clarification or add additional context in comments.

1 Comment

I managed to do that without a loop: sha512sum somefile.ext | grep -o '[0-9a-f]\{128\}' | echo -en $(sed 's/\([0-9a-f]\{2\}\)/\\x\1/g') > hash.bin. Seems a bit shorter than the looping construct.
2

How about perl:

<<<77f4de214a5423e3c7df8704f65af57c39c55f08424c75c0931ab09a5bfdf49f5f939f2caeff1e0113d9b3d6363583e4830cf40787100b750cde76f00b8cd3ec \
perl -e 'print pack "H*", <STDIN>' > hash.bin

Comments

2

If you have openssl in your system and want a sha512 hash in binary form, you can use this:

openssl dgst -sha512 -binary somefile.txt

Comments

1

If you have node:

node -e "var fs = require('fs'); fs.writeFileSync('binary', new Buffer('77f4de214a5423e3c7df8704f65af57c39c55f08424c75c0931ab09a5bfdf49f5f939f2caeff1e0113d9b3d6363583e4830cf40787100b750cde76f00b8cd3ec', 'hex'))"

Comments

0
s="77f4de214a5423e3c7df8704f65af57c39c55f08424c75c0931ab09a5bfdf49f5f939f2caeff1e0113d9b3d6363583e4830cf40787100b750cde76f00b8cd3ec"; 
echo -n $s | xxd -r -p > file.bin

 1 File(s)             64 bytes

Tested on Ubuntu 16.04.7

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.