-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathpassword-encryption.js
58 lines (46 loc) · 1.25 KB
/
password-encryption.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
import bcrypt from 'bcrypt';
function encryption (password, rounds, callback) {
if (!password || typeof password !== 'string') {
return setTimeout(() => callback(new Error('Invalid password argument')));
}
if (!rounds || typeof rounds !== 'number') {
return setTimeout(() => callback(new Error('Invalid rounds argument')));
}
generateSalt(password, rounds, callback);
}
function generateSalt (password, rounds, callback) {
bcrypt.genSalt(rounds, (error, salt) => {
if (error) {
return callback(error);
}
encrypt(password, salt, callback);
});
}
function encrypt (password, salt, callback) {
bcrypt.hash(password, salt, (error, hash) => {
if (error) {
return callback(error);
}
validate(password, hash, callback);
});
}
function validate (password, hash, callback) {
bcrypt.compare(password, hash, (error, valid) => {
if (error) {
return callback(error);
}
if (valid) {
callback(null, hash);
} else {
callback(new Error('An error occurred during validation'));
}
});
}
encryption('secret', 10, (error, hash) => {
if (error) {
return console.error(error);
}
console.log(hash);
});
// Async output:
// $2b$10$YdpHArdPZFMqbUqOcTAG..Vd9kVynRvIvL8Z7aLbfaZIipURY0dN6