Coder Perfect

Using the Linux command line to generate a SHA-256 hash

Problem

Using http://hash.online-convert.com/sha256-generator, I know that the text “foobar” generates the SHA-256 hash c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2.

The command line shell, on the other hand:

hendry@x201 ~$ echo foobar | sha256sum
aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f  -

Generates a different hash. What am I missing?

Asked by hendry

Solution #1

A newline is ordinarily output by echo, but with -n, this is silenced. Consider the following:

echo -n foobar | sha256sum

Answered by mvds

Solution #2

If you have openssl installed, you can use:

echo -n "foobar" | openssl dgst -sha256

Replace -sha256 with -md4, -md5, -ripemd160, -sha, -sha1, -sha224, -sha384, -sha512, or -whirlpool for additional algorithms.

Answered by Farahmand

Solution #3

If the command sha256sum isn’t available (for example, on Mac OS X v10.9 (Mavericks), you can use:

shasum -a 256 | echo -n “foobar”

Answered by Sucrenoir

Solution #4

echo -n works and is unlikely to go away due to widespread historical use, however new conforming applications are “encouraged to utilize printf” according to recent revisions of the POSIX standard.

Answered by Nicholas Knight

Solution #5

echo generates a newline character at the end of the line, which is also hashed. Try:

/bin/echo -n foobar | sha256sum 

Answered by Nordic Mainframe

Post is based on https://stackoverflow.com/questions/3358420/generating-a-sha-256-hash-from-the-linux-command-line