9

I need to base64 encode a binary sha1 hash. What is the best way to do this? I imagine this would involve piping binary data into base64. Unfortunately sha1sum does not have a binary output option. Any ideas?

This is what I need to do:

echo mydata|sha1sum --binary-output|base64

sha1sum does not have a --binary-output option though.

2
  • 3
    How did binary creep into this?
    – tink
    Commented May 30, 2013 at 23:32
  • 2
    I believe that jcalfee314 is saying that he wants to base64 encode an actual SHA1 hash value, rather than the hex representation thereof that the sha1 program outputs. Commented May 30, 2013 at 23:47

3 Answers 3

4

Try converting hex to base64. This answer is one option. There are a number of other implementations.

How can I convert from hex to base64?

15

Maybe something like:

echo mydata | sha1sum | xxd -r -p | base64

... would solve your problem.

See https://unix.stackexchange.com/questions/82561/convert-a-hex-string-to-binary-and-send-with-netcat for similar question.

1
  • 2
    Beautiful! This also works flawlessly under macOS Big Sur Beta (in late 2020). Commented Oct 23, 2020 at 19:00
6

You can use the openssl to CalculateSHA-1 and -binary output the digest in binary form.

Last piping convert binary-digest to Base-64.

echo -n mydata | openssl dgst -binary -sha1 | openssl base64

Explanation

Sending data (mydata in this case) to STDOUT:
echo -n mydata

-n flag remove new line (\n) from output.

Calculating SHA-1 via OpenSSL:
 openssl dgst -sha1

However, this command displays the SHA-1 in HEX mode, and for binary, the -binary flag needs to be added:

openssl dgst -binary -sha1
Convert SHA-1 to Base-64:
openssl base64
1
  • 2
    Could you please edit your answer to give an explanation of why this code answers the question? Code-only answers are discouraged, because they don't teach the solution.
    – DavidPostill
    Commented Jun 8, 2021 at 12:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .