Skip to content

Commit 4998553

Browse files
committed
simpler hmac - that doesn't do anything weird to objects
1 parent 3af762f commit 4998553

File tree

1 file changed

+21
-31
lines changed

1 file changed

+21
-31
lines changed

create-hmac.js

Lines changed: 21 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -3,49 +3,39 @@ var createHash = require('./create-hash')
33
var blocksize = 64
44
var zeroBuffer = new Buffer(blocksize); zeroBuffer.fill(0)
55

6-
function hmac(fn, key, data) {
7-
if(!Buffer.isBuffer(key)) key = new Buffer(key)
8-
if(!Buffer.isBuffer(data)) data = new Buffer(data)
6+
module.exports = Hmac
7+
8+
function Hmac (alg, key) {
9+
if(!(this instanceof Hmac)) return new Hmac(alg, key)
10+
this._opad = opad
11+
this._alg = alg
12+
13+
key = this._key = !Buffer.isBuffer(key) ? new Buffer(key) : key
914

1015
if(key.length > blocksize) {
11-
key = fn(key)
16+
key = createHash(alg).update(key).digest()
1217
} else if(key.length < blocksize) {
1318
key = Buffer.concat([key, zeroBuffer], blocksize)
1419
}
1520

16-
var ipad = new Buffer(blocksize), opad = new Buffer(blocksize)
21+
var ipad = this._ipad = new Buffer(blocksize)
22+
var opad = this._opad = new Buffer(blocksize)
23+
1724
for(var i = 0; i < blocksize; i++) {
1825
ipad[i] = key[i] ^ 0x36
1926
opad[i] = key[i] ^ 0x5C
2027
}
2128

22-
var hash = fn(Buffer.concat([ipad, data]))
23-
return fn(Buffer.concat([opad, hash]))
29+
this._hash = createHash(alg).update(ipad)
2430
}
2531

32+
Hmac.prototype.update = function (data, enc) {
33+
this._hash.update(data, enc)
34+
return this
35+
}
2636

27-
module.exports = createHmac
28-
29-
function createHmac (alg, key) {
30-
if(!Buffer.isBuffer(key)) key = new Buffer(key)
31-
// if(!Buffer.isBuffer(data)) data = new Buffer(data)
32-
33-
if(key.length > blocksize) {
34-
key = createHash(alg).update(key).digest()
35-
} else if(key.length < blocksize) {
36-
key = Buffer.concat([key, zeroBuffer], blocksize)
37-
}
38-
39-
var ipad = new Buffer(blocksize), opad = new Buffer(blocksize)
40-
for(var i = 0; i < blocksize; i++) {
41-
ipad[i] = key[i] ^ 0x36
42-
opad[i] = key[i] ^ 0x5C
43-
}
44-
hash = createHash(alg).update(ipad)//.update(data)
45-
var digest = hash.digest
46-
hash.digest = function (enc) {
47-
var h = digest.call(hash)
48-
return createHash(alg).update(opad).update(h).digest(enc)
49-
}
50-
return hash
37+
Hmac.prototype.digest = function (enc) {
38+
var h = this._hash.digest()
39+
return createHash(this._alg).update(this._opad).update(h).digest(enc)
5140
}
41+

0 commit comments

Comments
 (0)