UNPKG

969 BJavaScriptView Raw
1'use strict'
2var inherits = require('inherits')
3var Buffer = require('safe-buffer').Buffer
4
5var Base = require('cipher-base')
6
7var ZEROS = Buffer.alloc(128)
8var blocksize = 64
9
10function Hmac (alg, key) {
11 Base.call(this, 'digest')
12 if (typeof key === 'string') {
13 key = Buffer.from(key)
14 }
15
16 this._alg = alg
17 this._key = key
18
19 if (key.length > blocksize) {
20 key = alg(key)
21 } else if (key.length < blocksize) {
22 key = Buffer.concat([key, ZEROS], blocksize)
23 }
24
25 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
26 var opad = this._opad = Buffer.allocUnsafe(blocksize)
27
28 for (var i = 0; i < blocksize; i++) {
29 ipad[i] = key[i] ^ 0x36
30 opad[i] = key[i] ^ 0x5C
31 }
32
33 this._hash = [ipad]
34}
35
36inherits(Hmac, Base)
37
38Hmac.prototype._update = function (data) {
39 this._hash.push(data)
40}
41
42Hmac.prototype._final = function () {
43 var h = this._alg(Buffer.concat(this._hash))
44 return this._alg(Buffer.concat([this._opad, h]))
45}
46module.exports = Hmac