constant-equals
v1.2.0
Published
=== in constant time for strings
Downloads
1
Readme
Constant Equals
Timing attacks are a real threat. A very common pitfall is to compare strings with ===
.
Why?
Simply because a === b
will take more time to execute if they share a bigger prefix. So checking the user input against a target password with ===
will leak how much the attacker got the password right:
You can run the code yourself.
The solution
Make a for that checks every character. Don't try to be smart here :)
Install
npm install constant-equals --save
Usage
var a = 'a-user-input',
g = 'target-password',
eq = require('constant-equals')
if (eq(a, b)) {
console.log('Welcome')
} else {
console.log('Go away!')
}
eq()
doesn't do any kind of type conversion, so eq('12', 12) === false
.
Arrays
eq()
also works for a pair of arrays:
eq(['a', 'array', 'of', 5, 'tags'], ['a', 'array', 'of', 5, 'tags']) === true
indexOf and lastIndexOf
Like native indexOf()
and lastIndexOf()
for arrays:
eq.indexOf(['ab', 'cd', 'cd'], 'cd') === 1
eq.indexOf(['ab', 'cd', 'cd'], 'x') === -1
eq.lastIndexOf(['ab', 'cd', 'cd'], 'cd') === 2
This will always search all elements in the array, using constant equals for each comparison
NOTE
You should never, ever, store user passwords in plain text. If you think about doing so, you should problably look for modules like bcrypt