Search code examples
javascriptcryptographysha256cryptojs

why does digest and digest('hex') result in different outputs?


I have 2 piece of codes.

1ST ONE
const hash1 = (data) => createHash('sha256').update(data).digest('hex');
var a1 = hash1("A");
var b1 = hash1("B");
console.log(hash1(a1+b1));

2ND ONE
const hash2 = (data) => createHash('sha256').update(data).digest();
var a2 = hash2("A");
var b2 = hash2("B");
console.log(hash2(Buffer.concat([a2,b2])).toString('hex'));

Why do they print the different results ?

digest('hex') and digest() are the same , but in different kind of format, but still the same. So, why do I get different results in console ? is it the + operator when I sum up the hexes versus when i sum up buffers ? why ?


Solution

  • The default encoding for hash.digest([encoding]) is utf-8. utf-8 is a variable-length encoding system. It will only use as many bytes as necessary to represent each character (anywhere between 1-4 bytes).

    However, when you specify hex as the encoding, each character is stored as exactly 2 hexadecimal characters.

    When you call hash.toString('hex') on a utf-8 encoded hash, the resulting hex representation is equivalent to hashing with hex encoding in the first place (as in hash.digest('hex')).

    So, even though the hex representation is the same in each case, the actual data is different. i.e.:

    hash.digest() != hash.digest('hex'), but

    hash.digest().toString('hex') == hash.digest('hex').