Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
182 lines (163 loc) · 5.06 KB
/
Copy pathindex.js
File metadata and controls
182 lines (163 loc) · 5.06 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
const crypto = require('crypto');
const phc = require('@phc/format');
// Default options
const defaultOptions = {
hashlength: 32,
saltlength: 16,
pepper: '',
cost: 16384, // CPU/memory cost (N)
blockSize: 8, // Block size (r)
parallelization: 1, // Parallelization (p)
maxmem: 64 * 1024 * 1024, // Maximum memory in bytes (64 MB by default)
strict: false,
};
const shorthand = {
cost: 'N', // CPU/memory cost
blockSize: 'r', // Block size
parallelization: 'p', // Parallelization
};
let currentOptions = { ...defaultOptions };
/**
* Normalize the options, allowing shorthand values ('N', 'r', 'p')
* and merging with default options.
*
* @param {Object} [options={}] - The options to normalize.
* @returns {Object} - The normalized options merged with defaults.
*/
function normalize(options = {}) {
const opts = {...options};
for (const opt in shorthand) {
if (shorthand[opt] in opts) {
opts[opt] = opts[shorthand[opt]];
delete opts[shorthand[opt]];
}
}
for (const opt in opts) {
if (opts[opt] === undefined) {
opts[opt] = defaultOptions[opt];
}
}
return opts;
}
/**
* Get options by combining default options and user-provided ones.
*
* @param {Object} [options={}] - The user-provided options.
* @returns {Object} - The combined options.
*/
function getOptions(options = {}) {
return { ...currentOptions, ...normalize(options) };
}
/**
* Complement or get the current options.
*
* @param {Object} [options] - The new options to set.
* @returns {Object} - The current options.
*/
function opts(options) {
if (options) {
currentOptions = getOptions(options);
}
return currentOptions;
}
/**
* Hash a password using scrypt with a random salt.
*
* @param {string} password - The password to hash.
* @param {Object} [options={}] - Options to override defaults.
* @returns {Promise<string>} - The hashed password in format:
* `<base64(hash)>$<base64(salt)>$<cost>$<blockSize>$<parallelization>`.
*/
async function hash(password, options = {}) {
const combinedOptions = getOptions(options);
const salt = crypto.randomBytes(combinedOptions.saltlength);
const fullPassword = password + combinedOptions.pepper;
return new Promise((resolve, reject) => {
crypto.scrypt(fullPassword, salt, combinedOptions.hashlength, combinedOptions, (err, derivedKey) => {
if (err) reject(err);
resolve(phc.serialize({
id: 'scrypt',
hash: derivedKey,
salt: salt,
params: {
n: combinedOptions.cost,
r: combinedOptions.blockSize,
p: combinedOptions.parallelization
}
}));
});
});
}
/**
* Parse a hashed password string into its components.
*
* @param {string} hash - The hashed password.
* @param {Object} [options={}] - Options to override defaults.
* @returns {Object} - An object with `hashedPassword`, `salt`, `cost`, `blockSize`, and `parallelization`.
* @throws Will throw an error if the hash format is invalid.
*/
function parse(hash, options) {
const combinedOptions = getOptions(options);
const parsedHash = phc.deserialize(hash);
parsedHash.params.N = parsedHash.params.n
// parameters checks
if (combinedOptions.strict) {
if (parsedHash.hash.length !== combinedOptions.hashlength) {
throw new Error('Hash length does not match');
}
if (parsedHash.salt.length !== combinedOptions.saltlength) {
throw new Error('Salt length does not match');
}
for (const param in shorthand) {
if (parsedHash.params[shorthand[param]] !== combinedOptions[param]) {
throw new Error(`Parameter ${param}/${shorthand[param]} does not match`);
}
}
}
return parsedHash;
}
/**
* Check if a hash has the correct format and parameters.
*
* @param {string} hash - The hashed password.
* @param {Object} [options={}] - Options to override defaults.
* @returns {boolean} - Returns `true` if the hash looks valid, otherwise `false`.
*/
function needsRehash(hash, options = {}) {
try {
parse(hash, { ...options, strict: true });
return false;
} catch(err) {
return true;
}
}
/**
* Verify if a password matches a given hash.
*
* @param {string} password - The password to verify.
* @param {string} hash - The hash to compare with.
* @param {Object} [options={}] - Options to override defaults.
* @returns {Promise<boolean>} - Returns `true` if the password matches the hash, otherwise `false`.
*/
async function verify(password, hash, options = {}) {
const combinedOptions = getOptions(options);
try {
const parsedHash = parse(hash, options);
const fullPassword = password + combinedOptions.pepper;
return new Promise((resolve, reject) => {
crypto.scrypt(fullPassword, parsedHash.salt, parsedHash.hash.length, {
...parsedHash.params,
maxmem: combinedOptions.maxmem
}, (err, derivedKey) => {
if (err) {
reject(err);
return;
}
resolve(derivedKey.equals(parsedHash.hash));
});
});
} catch(err) {
return Promise.resolve(false);
}
}
module.exports = { opts, hash, verify, needsRehash, parse };