Generating a SHA-256 hash from the Linux command line

Viewed 409312

I know the string "foobar" generates the SHA-256 hash c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2 using http://hash.online-convert.com/sha256-generator

However the command line shell:

hendry@x201 ~$ echo foobar | sha256sum
aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f  -

Generates a different hash. What am I missing?

8 Answers

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

echo -n "foobar" | shasum -a 256

For the sha256 hash in base64, use:

echo -n foo | openssl dgst -binary -sha256 | openssl base64

Example

echo -n foo | openssl dgst -binary -sha256 | openssl base64
C+7Hteo/D9vJXQ3UfzxbwnXaijM=

Use printf instead of echo to avoid adding an extra newline.

printf foobar | sha256sum

For an arbitrary string, the %s format specifier should be used.

printf '%s' 'somestring' | sha256sum
Related