https://github.com/sitegui/constant-equals
=== in constant time for strings
https://github.com/sitegui/constant-equals
Last synced: over 1 year ago
JSON representation
=== in constant time for strings
- Host: GitHub
- URL: https://github.com/sitegui/constant-equals
- Owner: sitegui
- License: mit
- Created: 2014-08-19T01:05:25.000Z (almost 12 years ago)
- Default Branch: master
- Last Pushed: 2015-07-28T19:20:58.000Z (almost 11 years ago)
- Last Synced: 2025-03-05T16:51:59.845Z (over 1 year ago)
- Language: JavaScript
- Size: 258 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: HISTORY.md
- License: LICENSE
Awesome Lists containing this project
README
# Constant Equals
[Timing attacks](http://codahale.com/a-lesson-in-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](https://github.com/sitegui/constant-equals/blob/master/bench.js) yourself.
## The solution
Make a for that checks every character. Don't try to be smart here :)
## Install
`npm install constant-equals --save`
## Usage
```javascript
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:
```javascript
eq(['a', 'array', 'of', 5, 'tags'], ['a', 'array', 'of', 5, 'tags']) === true
```
### indexOf and lastIndexOf
Like native `indexOf()` and `lastIndexOf()` for arrays:
```js
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](https://www.npmjs.org/package/bcrypt)