A basic JavaScript string comparison question

Viewed 69

I am encountering a problem with a string comparison using Node.js and its built-in crypto module (in the context of some signature checking for an incoming payload). Consider this code example:

console.log(`
SIG   : '${signature}' - type: ${typeof signature}
HASH  : '${hmac.digest('hex')}' - type: ${typeof (hmac.digest('hex'))}
EQUALS: ${signature === hmac.digest('hex')}
`);

This is what I see in the console:

SIG   : '1406f5bfc078fa6a7feb5eca9c091a19c96926f6110272c04cd4cbd712be60c4' - type: string
HASH  : '1406f5bfc078fa6a7feb5eca9c091a19c96926f6110272c04cd4cbd712be60c4' - type: string
EQUALS: false

So, both are strings, as expected, and both are the same string. But why aren't they equal? I'm at my wits' end.

By the way, when using ==, I also get false as result of the comparison.

For information and h/t: I'm using this script as the basis: https://github.com/girliemac/slack-httpstatuscats/blob/master/src/verifySignature.js

2 Answers

You have this issue because you've called hmac.digest() twice, the second time it returns an empty string:

Try to save the result in a variable then compare:

const result = hmac.digest('hex')
console.log(`
SIG   : '${signature}' - type: ${typeof signature}
HASH  : '${result}' - type: ${typeof (result)}
EQUALS: ${signature === result}
`);

Try to use

var EQUALS = SIG.localeCompare(HASH);
Related