-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbcrypt.js
56 lines (52 loc) · 1.35 KB
/
bcrypt.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
const md5 = require("md5");
var fs = require('fs');
module.exports = {
getHashes(){
fs.readFile('./hash.text', (err, data) => {
if(err){
throw err;
return null;
}else{
return data.split("\n");
}
});
},
/**
*
*
* @param { string } rawPass - the password to be hashed
* @param { object } [options={}] - object containing salt and rounds
* @returns {string}
*/
hash(rawPassword, options = {}) {
/**
* salt is optional, if not provided it will be set to current timestamp
*/
const salt = options.salt ? options.salt : new Date().getTime();
/**
* rounds is optional, if not provided it will be set to 10
*/
const rounds = options.rounds ? options.rounds : 10;
let hashed = md5(rawPassword + salt);
for (let i = 0; i <= rounds; i++) {
hashed = md5(hashed);
}
return `${salt}$${rounds}$${hashed}`;
},
/**
*
*
* @param {string} rawPassword - the raw password
* @param { string } hashedPassword - the hashed password
* @returns
*/
compare(rawPassword, hashedPassword) {
try {
const [ salt, rounds ] = hashedPassword.split('$');
const hashedRawPassword = this.hash(rawPassword, { salt, rounds });
return hashedPassword === hashedRawPassword;
} catch (error) {
throw Error(error.message);
}
}
};