-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcryptoHasher.js
More file actions
74 lines (63 loc) · 2.18 KB
/
cryptoHasher.js
File metadata and controls
74 lines (63 loc) · 2.18 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
const HasherContract = require('@ostro/contracts/encryption/hasher');
const RuntimeException = require('@ostro/support/exceptions/runtimeException');
const crypto = require('crypto');
class CryptoHasher extends HasherContract {
$rounds = 0;
constructor($options = {}) {
super()
this.$rounds = $options['rounds'] || this.$rounds;
this.$verifyAlgorithm = $options['verify'] || this.$verifyAlgorithm;
}
supportedAlgorithm() {
return ['sha256', 'sha512']
}
make($value, $options = {}) {
let $salt = crypto.randomBytes(this.cost()).toString('ascii')
let $hash = crypto.createHmac('sha256', $salt).update($value).digest('ascii');
if ($hash === false) {
throw new RuntimeException('Crypto hashing not supported.');
}
return '$5a$' + this.$rounds + '$' + Buffer.from($salt + $hash).toString('base64');
}
check($value, $hashedValue, $options = {}) {
let passwordInfo = this.info($hashedValue);
if (!passwordInfo) {
return false;
}
if (this.$verifyAlgorithm && passwordInfo['algorithm'] !== 'sha256') {
throw new RuntimeException('This password does not use the sha256 algorithm.');
}
$hashedValue = Buffer.from($hashedValue.replace(passwordInfo.identifier, ''), 'base64').toString('utf-8')
let $rounds = (passwordInfo.cost * passwordInfo.costFactor)
let $salt = $hashedValue.substring(0, $rounds)
$hashedValue = $hashedValue.substr($rounds, $hashedValue.length)
return crypto.createHmac('sha256', $salt).update(String($value)).digest('ascii') == $hashedValue
}
setRounds($rounds) {
this.$rounds = $rounds;
return this;
}
info($hashedValue) {
$hashedValue = $hashedValue.match(/\$([0-9]+)([a-zA-Z])\$([0-9]+)\$/)
if (!$hashedValue) {
return false;
}
let [identifier, algorithm, unicode, cost] = $hashedValue
if (algorithm == 1) {
algorithm = 'md5'
} else if (algorithm == 2) {
algorithm = 'bcrypt'
} else if (algorithm == 'sha1') {
algorithm = 'sha1'
} else if (algorithm == 5) {
algorithm = 'sha256'
} else if (algorithm == 6) {
algorithm = 'sha512'
}
return { identifier, algorithm, cost: parseInt(cost), costFactor: 1 }
}
cost($options = {}) {
return $options['rounds'] || this.$rounds;
}
}
module.exports = CryptoHasher