forked from oleksiyk/shacrypt
-
Notifications
You must be signed in to change notification settings - Fork 2
/
shacrypt.js
76 lines (60 loc) · 1.72 KB
/
shacrypt.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
65
66
67
68
69
70
71
72
73
74
75
76
"use strict";
var shacrypt = require('./build/Release/shacrypt');
var crypto = require('crypto');
var isString = function(obj) {
return Object.prototype.toString.call(obj) == '[object String]';
};
var isNumber = function(obj) {
return Object.prototype.toString.call(obj) == '[object Number]';
};
function validate(prefix, password, salt, rounds) {
var _salt = salt,
_rounds = rounds || 5000;
if (!isString(password)) {
throw new Error('password must be a String');
}
if (!isString(salt)) {
_salt = crypto.randomBytes(16).toString('hex');
if (isNumber(salt)) {
_salt = prefix + 'rounds=' + salt + '$' + _salt;
}
}
if (isNumber(_rounds) && _salt.indexOf(prefix) == -1) {
_salt = prefix + 'rounds=' + _rounds + '$' + _salt;
}
return _salt;
}
/**
* Generate SHA256-CRYPT hash
*
* @param {String} password
* @param {String} [salt]
* @param {Number} [rounds]
* @param {Function} [callback]
* @return {String}
*/
exports.sha256crypt = function(password, salt, rounds, callback) {
salt = validate('$5$', password, salt, rounds);
if (typeof callback === "function") {
shacrypt.sha256cryptasync(password, salt, callback);
} else {
return shacrypt.sha256crypt(password, salt);
}
};
/**
* Generate SHA512-CRYPT hash
*
* @param {String} password
* @param {String} [salt]
* @param {Number} [rounds]
* @param {Function} [callback]
* @return {String}
*/
exports.sha512crypt = function(password, salt, rounds, callback) {
salt = validate('$6$', password, salt, rounds);
if (typeof callback === "function") {
shacrypt.sha512cryptasync(password, salt, callback);
} else {
return shacrypt.sha512crypt(password, salt);
}
};