Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80644 views
1
var hmac = exports;
2
3
var hash = require('../hash');
4
var utils = hash.utils;
5
var assert = utils.assert;
6
7
function Hmac(hash, key, enc) {
8
if (!(this instanceof Hmac))
9
return new Hmac(hash, key, enc);
10
this.Hash = hash;
11
this.blockSize = hash.blockSize / 8;
12
this.outSize = hash.outSize / 8;
13
this.inner = null;
14
this.outer = null;
15
16
this._init(utils.toArray(key, enc));
17
}
18
module.exports = Hmac;
19
20
Hmac.prototype._init = function init(key) {
21
// Shorten key, if needed
22
if (key.length > this.blockSize)
23
key = new this.Hash().update(key).digest();
24
assert(key.length <= this.blockSize);
25
26
// Add padding to key
27
for (var i = key.length; i < this.blockSize; i++)
28
key.push(0);
29
30
for (var i = 0; i < key.length; i++)
31
key[i] ^= 0x36;
32
this.inner = new this.Hash().update(key);
33
34
// 0x36 ^ 0x5c = 0x6a
35
for (var i = 0; i < key.length; i++)
36
key[i] ^= 0x6a;
37
this.outer = new this.Hash().update(key);
38
};
39
40
Hmac.prototype.update = function update(msg, enc) {
41
this.inner.update(msg, enc);
42
return this;
43
};
44
45
Hmac.prototype.digest = function digest(enc) {
46
this.outer.update(this.inner.digest());
47
return this.outer.digest(enc);
48
};
49
50