-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathdigest.js
75 lines (54 loc) · 1.52 KB
/
digest.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
'use strict';
let crypto = require('crypto');
let _ = require('underscore');
class Digest {
static Sha1hexdigest(privateKey, string) {
return new Digest().hmacSha1(privateKey, string);
}
static Sha256hexdigest(privateKey, string) {
return new Digest().hmacSha256(privateKey, string);
}
static secureCompare(left, right) {
return new Digest().secureCompare(left, right);
}
hmacSha256(key, data) {
let hmac = crypto.createHmac('sha256', this.sha256(key));
hmac.update(data, 'binary');
return hmac.digest('hex');
}
hmacSha1(key, data) {
let hmac = crypto.createHmac('sha1', this.sha1(key));
hmac.update(data, 'binary');
return hmac.digest('hex');
}
secureCompare(left, right) {
if (left == null || right == null) { return false; }
let leftBytes = this.unpack(left);
let rightBytes = this.unpack(right);
let result = 0;
for (let bytePair of _.zip(leftBytes, rightBytes)) {
let leftByte = bytePair[0];
let rightByte = bytePair[1];
result |= leftByte ^ rightByte;
}
return result === 0;
}
sha1(data) {
let hash = crypto.createHash('sha1');
hash.update(data, 'binary');
return hash.digest();
}
sha256(data) {
let hash = crypto.createHash('sha256');
hash.update(data, 'binary');
return hash.digest();
}
unpack(string) {
let bytes = [];
for (let index = 0; index < string.length; index++) {
bytes.push(string.charCodeAt(index));
}
return bytes;
}
}
module.exports = {Digest: Digest};