browserHmac.js
1.42 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
var hashUtils = require('./browserHashUtils');
/**
* @api private
*/
function Hmac(hashCtor, secret) {
this.hash = new hashCtor();
this.outer = new hashCtor();
var inner = bufferFromSecret(hashCtor, secret);
var outer = new Uint8Array(hashCtor.BLOCK_SIZE);
outer.set(inner);
for (var i = 0; i < hashCtor.BLOCK_SIZE; i++) {
inner[i] ^= 0x36;
outer[i] ^= 0x5c;
}
this.hash.update(inner);
this.outer.update(outer);
// Zero out the copied key buffer.
for (var i = 0; i < inner.byteLength; i++) {
inner[i] = 0;
}
}
/**
* @api private
*/
module.exports = exports = Hmac;
Hmac.prototype.update = function (toHash) {
if (hashUtils.isEmptyData(toHash) || this.error) {
return this;
}
try {
this.hash.update(hashUtils.convertToBuffer(toHash));
} catch (e) {
this.error = e;
}
return this;
};
Hmac.prototype.digest = function (encoding) {
if (!this.outer.finished) {
this.outer.update(this.hash.digest());
}
return this.outer.digest(encoding);
};
function bufferFromSecret(hashCtor, secret) {
var input = hashUtils.convertToBuffer(secret);
if (input.byteLength > hashCtor.BLOCK_SIZE) {
var bufferHash = new hashCtor;
bufferHash.update(input);
input = bufferHash.digest();
}
var buffer = new Uint8Array(hashCtor.BLOCK_SIZE);
buffer.set(input);
return buffer;
}