Home > Software engineering >  Interpret hex string as hex bytes for sha256 in bash
Interpret hex string as hex bytes for sha256 in bash

Time:10-09

Let's say I have a hex string

6c64f463a38c670e5622f58ceccad23d8b9db5c9fc2a1717fc50015325b4764a

When I use sha256sum or openssl dgst -sha256 I get this value:

52ad0981ad75e06084153fbe6d6e9363846b1cf14c9a84876d3504b957941fac

the problem here is that sha256sum thinks that this is text and therefor translates it into byte array which represents ASCII table, but I want it to calculate hash as it was a byte array.

For example this service can distinguish text format and hex format, so I get the right value:

4be5da7c50b521edb623936920044b1c546d3c38815ccc61c80b20fe171ff4cd

My actual question is:

  • Is there a way to calculate hash from byte string as if it is a hex byte array in bash?

CodePudding user response:

Convert hex to binary and then use sha256sum:

echo -n '6c64f463a38c670e5622f58ceccad23d8b9db5c9fc2a1717fc50015325b4764a' \
| xxd -r -p \
| sha256sum \
| cut -d ' ' -f 1

Output:

4be5da7c50b521edb623936920044b1c546d3c38815ccc61c80b20fe171ff4cd

See: convert a hex string to binary and send with netcat

  • Related