Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80542 views
1
'use strict';
2
var createHash = require('create-hash/browser');
3
var inherits = require('inherits')
4
5
var Transform = require('stream').Transform
6
7
var ZEROS = new Buffer(128)
8
ZEROS.fill(0)
9
10
function Hmac(alg, key) {
11
Transform.call(this)
12
13
if (typeof key === 'string') {
14
key = new Buffer(key)
15
}
16
17
var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
18
19
this._alg = alg
20
this._key = key
21
22
if (key.length > blocksize) {
23
key = createHash(alg).update(key).digest()
24
25
} else if (key.length < blocksize) {
26
key = Buffer.concat([key, ZEROS], blocksize)
27
}
28
29
var ipad = this._ipad = new Buffer(blocksize)
30
var opad = this._opad = new Buffer(blocksize)
31
32
for (var i = 0; i < blocksize; i++) {
33
ipad[i] = key[i] ^ 0x36
34
opad[i] = key[i] ^ 0x5C
35
}
36
37
this._hash = createHash(alg).update(ipad)
38
}
39
40
inherits(Hmac, Transform)
41
42
Hmac.prototype.update = function (data, enc) {
43
this._hash.update(data, enc)
44
45
return this
46
}
47
48
Hmac.prototype._transform = function (data, _, next) {
49
this._hash.update(data)
50
51
next()
52
}
53
54
Hmac.prototype._flush = function (next) {
55
this.push(this.digest())
56
57
next()
58
}
59
60
Hmac.prototype.digest = function (enc) {
61
var h = this._hash.digest()
62
63
return createHash(this._alg).update(this._opad).update(h).digest(enc)
64
}
65
66
module.exports = function createHmac(alg, key) {
67
return new Hmac(alg, key)
68
}
69
70