-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
51 lines (43 loc) · 1.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
var Promise = require('any-promise')
var crypto = require('mz/crypto')
var scmp = require('scmp')
module.exports = Password
function Password(options) {
if (!(this instanceof Password)) return new Password(options)
options = options || {}
this.length = options.length || 128
this.iterations = options.iterations || 12000
}
Password.prototype.salt = function (length) {
return crypto.randomBytes(length || this.length)
}
Password.prototype.hash = function (password, salt, iterations, length) {
iterations = iterations || this.iterations
length = length || this.length
return (salt ? Promise.resolve(salt) : this.salt().then(toBase64))
.then(function (_salt) {
return crypto.pbkdf2(password, salt = _salt, iterations, length, 'sha1')
})
.then(function (hash) {
return [
salt,
iterations,
length,
hash.toString('base64')
].join(';')
})
}
Password.prototype.compare = function (password, hash) {
var frags = hash.split(';')
return this.hash(
password,
frags[0],
parseInt(frags[1], 10),
parseInt(frags[2], 10)
).then(function (res) {
return scmp(hash, res)
})
}
function toBase64(x) {
return x.toString('base64')
}