[linux] Generating a SHA-256 hash from the Linux command line

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?

This question is related to linux shell sha256

The answer is


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

/bin/echo -n foobar | sha256sum 

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.


For the sha256 hash in base64, use:

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

Example

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

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


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


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


Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to sha256

PHP salt and hash SHA256 for login password Are there any SHA-256 javascript implementations that are generally considered trustworthy? Mismatch Detected for 'RuntimeLibrary' SHA-256 or MD5 for file integrity Hashing a string with Sha256 How to hash some string with sha256 in Java? Generating a SHA-256 hash from the Linux command line Hash String via SHA-256 in Java Generate sha256 with OpenSSL and C++ How long is the SHA256 hash?