Home > OS >  SHA256 on Terminal vs. Node.js giving two different hashes
SHA256 on Terminal vs. Node.js giving two different hashes

Time:03-03

I want to get a SHA256 Hash that gives me the same result as I get on the terminal

echo -n "hello world" | shasum -0 -a 256

e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

I tried two different scripts

const {Sha256} = require('@aws-crypto/sha256-js');

(async () => {
    const hash = new Sha256();
    hash.update('hello world');
    const result = await hash.digest();
    let hex = Buffer.from(result).toString('hex');
    console.log(hex);
})()

And

var hash = require('hash.js')

console.log(hash.sha256().update('hello world').digest('hex'))

They both give me the hash b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

How can I get the same hash from the shasum in my terminal?

CodePudding user response:

If you ask the man page of shasum you will see;

-0, --01          read in BITS mode
                           ASCII '0' interpreted as 0-bit,
                           ASCII '1' interpreted as 1-bit,
                           all other characters ignored

That reads only 0s and 1s from the file ( pipe in your case). Now remove the parameter -0 or better define the default

-t, --text read in text mode (default)

$ echo -n "hello world" | shasum -t -a 256 | cut -c -64 b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

Now we have the same output.

Note 1: that the cut is used to remove the space and dash in the end.

Not 2 : NIST has test vector in Cryptographic Algorithm Validation Program and SHA-256 value of empty string (length 0) is given as in the file SHA256ShortMsg.rsp;

Len = 0
Msg = 00
MD = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

CodePudding user response:

Different line endings and formatting causing the issue or tab space etc. Differences.

  • Related