-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
41 lines (36 loc) · 1.17 KB
/
auth.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
const crypto = require('crypto')
const Promise = require('bluebird')
Promise.promisifyAll(crypto)
const DEFAULTS = {
saltlen: 32,
iterations: 25000,
keylen: 512,
encoding: 'hex',
digestAlgorithm: 'sha256' // To get a list of supported hashes use crypto.getHashes()
}
class Auth {
constructor (opts = {}) {
this.opts = opts
this.options = Object.assign({}, DEFAULTS, opts.auth || opts)
}
pbkdf2 (password, salt) {
const { iterations, keylen, digestAlgorithm } = this.options
return crypto.pbkdf2Async(Buffer.from(password), salt, iterations, keylen, digestAlgorithm)
}
async hashPassword (password) {
const { saltlen, encoding } = this.options
const buf = await crypto.randomBytesAsync(saltlen)
const salt = buf.toString(encoding)
const rawHash = await this.pbkdf2(password, salt)
const hash = rawHash.toString(encoding)
return `${salt}.${hash}`
}
async verifyPassword (pass, proposed) {
const { encoding } = this.options
const [salt, hash] = pass.split('.')
const rawHash = await this.pbkdf2(proposed, salt)
const calcedHash = rawHash.toString(encoding)
return hash === calcedHash
}
}
module.exports = Auth