Advertisement
Advertisement


Generating a SHA-256 hash from the Linux command line


Question

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

However the command line shell:

[email protected] ~$ echo foobar | sha256sum
aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f  -

Generates a different hash. What am I missing?

2020/05/31
1
242
5/31/2020 12:04:14 PM

Accepted Answer

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

echo -n foobar | sha256sum
2015/06/03
372
6/3/2015 2:46:20 AM

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.

2014/04/12

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

2020/05/31

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

2010/07/28

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

/bin/echo -n foobar | sha256sum 
2020/05/31

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

2010/07/28

Source: https://stackoverflow.com/questions/3358420
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]