Generating a Sha-256 Hash from the Linux Command Line

Generating a Sha-256 Hash from the Linux Command Line

I know the string "foobar" generates the SHA-256 hash c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2 using

However the command line shell:

hendry@x201 ~$ echo foobar | sha256sum
aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f  -

Generates a different hash. What am I missing?

3

8 Answers

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

echo -n foobar | sha256sum
7

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.

2

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

2

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".

0

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

/bin/echo -n foobar | sha256sum 

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=
1

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

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

printf foobar | sha256sum
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.