forked from zemirco/couch-pwd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (51 loc) · 1.58 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
52
53
54
55
56
57
58
59
60
61
62
63
64
var crypto = require('crypto');
var iterations = 10;
var keylen = 20;
var size = 16;
var encoding = 'hex';
var digest = 'SHA1';
// set iterations to `n`
exports.iterations = function(n){
if (0 === arguments.length) return iterations;
iterations = n;
};
// set keylen to `n`
exports.keylen = function(n){
if (0 === arguments.length) return keylen;
keylen = n;
};
// set size to `n`
exports.size = function(n){
if (0 === arguments.length) return size;
size = n;
};
// set encoding to `str`
exports.encoding = function(str){
if (0 === arguments.length) return encoding;
encoding = str;
};
exports.hash = function(pwd, salt, cb) {
if (arguments.length === 3) {
// create hash from plain text password and salt
// hash('secret', 'salt', function(err, hash) {})
if (typeof pwd !== 'string') return cb(new Error('password missing'));
if (typeof salt !== 'string') return cb(new Error('salt missing'));
crypto.pbkdf2(pwd, salt, iterations, keylen, digest, function(err, hash) {
if (err) return cb(err);
cb(null, hash.toString(encoding));
});
} else {
// generate salt and password hash from plain text password
// hash('secret', function(err, salt, hash) {})
cb = salt;
if (typeof pwd !== 'string') return cb(new Error('password missing'));
crypto.randomBytes(size, function(err, salt) {
if (err) return cb(err);
salt = salt.toString('hex');
crypto.pbkdf2(pwd, salt, iterations, keylen, digest, function(err, hash){
if (err) return cb(err);
cb(null, salt, hash.toString(encoding));
});
});
}
};