UNPKG

1.45 kBJavaScriptView Raw
1var hashUtils = require('./browserHashUtils');
2
3/**
4 * @api private
5 */
6function Hmac(hashCtor, secret) {
7 this.hash = new hashCtor();
8 this.outer = new hashCtor();
9
10 var inner = bufferFromSecret(hashCtor, secret);
11 var outer = new Uint8Array(hashCtor.BLOCK_SIZE);
12 outer.set(inner);
13
14 for (var i = 0; i < hashCtor.BLOCK_SIZE; i++) {
15 inner[i] ^= 0x36;
16 outer[i] ^= 0x5c;
17 }
18
19 this.hash.update(inner);
20 this.outer.update(outer);
21
22 // Zero out the copied key buffer.
23 for (var i = 0; i < inner.byteLength; i++) {
24 inner[i] = 0;
25 }
26}
27
28/**
29 * @api private
30 */
31module.exports = exports = Hmac;
32
33Hmac.prototype.update = function (toHash) {
34 if (hashUtils.isEmptyData(toHash) || this.error) {
35 return this;
36 }
37
38 try {
39 this.hash.update(hashUtils.convertToBuffer(toHash));
40 } catch (e) {
41 this.error = e;
42 }
43
44 return this;
45};
46
47Hmac.prototype.digest = function (encoding) {
48 if (!this.outer.finished) {
49 this.outer.update(this.hash.digest());
50 }
51
52 return this.outer.digest(encoding);
53};
54
55function bufferFromSecret(hashCtor, secret) {
56 var input = hashUtils.convertToBuffer(secret);
57 if (input.byteLength > hashCtor.BLOCK_SIZE) {
58 var bufferHash = new hashCtor;
59 bufferHash.update(input);
60 input = bufferHash.digest();
61 }
62 var buffer = new Uint8Array(hashCtor.BLOCK_SIZE);
63 buffer.set(input);
64 return buffer;
65}