Generating a SHA-256 hash from the Linux command line

LinuxShellSha256

Linux Problem Overview


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?

Linux Solutions


Solution 1 - Linux

echo will normally output a newline, which is suppressed with -n. Try this:

echo -n foobar | sha256sum

Solution 2 - Linux

If you have installed openssl, you can use:

echo -n "foobar" | openssl dgst -sha256

For other algorithms you can replace -sha256 with -md4, -md5, -ripemd160, -sha, -sha1, -sha224, -sha384, -sha512 or -whirlpool.

Solution 3 - Linux

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

Solution 4 - Linux

echo -n works and is unlikely to ever disappear due to massive historical usage, however per recent versions of the POSIX standard, new conforming applications are "encouraged to use printf".

Solution 5 - Linux

echo produces a trailing newline character which is hashed too. Try:

/bin/echo -n foobar | sha256sum 

Solution 6 - Linux

I believe that echo outputs a trailing newline. Try using -n as a parameter to echo to skip the newline.

Solution 7 - Linux

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=

Solution 8 - Linux

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

printf foobar | sha256sum

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhendryView Question on Stackoverflow
Solution 1 - LinuxmvdsView Answer on Stackoverflow
Solution 2 - LinuxFarahmandView Answer on Stackoverflow
Solution 3 - LinuxSucrenoirView Answer on Stackoverflow
Solution 4 - LinuxNicholas KnightView Answer on Stackoverflow
Solution 5 - LinuxNordic MainframeView Answer on Stackoverflow
Solution 6 - LinuxThomas OwensView Answer on Stackoverflow
Solution 7 - LinuxstevecView Answer on Stackoverflow
Solution 8 - LinuxUnmitigatedView Answer on Stackoverflow