Skip to content

Commit 9699045

Browse files
committed
hmac ourselves
1 parent 5b33204 commit 9699045

File tree

1 file changed

+45
-3
lines changed

1 file changed

+45
-3
lines changed

lib/sync.js

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,47 @@
1-
var createHmac = require('create-hmac')
1+
var createHash = require('create-hash')
22
var checkParameters = require('./precondition')
33
var defaultEncoding = require('./default-encoding')
44
var Buffer = require('safe-buffer').Buffer
5+
var ZEROS = Buffer.alloc(128)
6+
var sizes = {
7+
md5: 16,
8+
sha1: 20,
9+
sha224: 28,
10+
sha256: 32,
11+
sha384: 48,
12+
sha512: 64,
13+
rmd160: 20,
14+
ripemd160: 20
15+
}
16+
function computePad (alg, key) {
17+
var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
18+
if (key.length > blocksize) {
19+
key = hash(alg, key)
20+
} else if (key.length < blocksize) {
21+
key = Buffer.concat([key, ZEROS], blocksize)
22+
}
23+
var ipad = Buffer.allocUnsafe(blocksize)
24+
var opad = Buffer.alloc(blocksize + sizes[alg])
25+
26+
for (var i = 0; i < blocksize; i++) {
27+
ipad[i] = key[i] ^ 0x36
28+
opad[i] = key[i] ^ 0x5C
29+
}
30+
return {
31+
ipad: ipad,
32+
opad: opad,
33+
alg: alg,
34+
blocksize: blocksize
35+
}
36+
}
37+
function hash (algo, buffer) {
38+
return createHash(algo).update(buffer).digest()
39+
}
40+
function hmac (pad, data) {
41+
var h = hash(pad.alg, Buffer.concat([pad.ipad, data]))
42+
h.copy(pad.opad, pad.blocksize)
43+
return hash(pad.alg, pad.opad)
44+
}
545
module.exports = function (password, salt, iterations, keylen, digest) {
646
if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
747
if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
@@ -10,6 +50,8 @@ module.exports = function (password, salt, iterations, keylen, digest) {
1050

1151
digest = digest || 'sha1'
1252

53+
var pad = computePad(digest, password)
54+
1355
var hLen
1456
var l = 1
1557
var DK = Buffer.allocUnsafe(keylen)
@@ -21,7 +63,7 @@ module.exports = function (password, salt, iterations, keylen, digest) {
2163

2264
for (var i = 1; i <= l; i++) {
2365
block1.writeUInt32BE(i, salt.length)
24-
var U = createHmac(digest, password).update(block1).digest()
66+
var U = hmac(pad, block1)
2567

2668
if (!hLen) {
2769
hLen = U.length
@@ -33,7 +75,7 @@ module.exports = function (password, salt, iterations, keylen, digest) {
3375
U.copy(T, 0, 0, hLen)
3476

3577
for (var j = 1; j < iterations; j++) {
36-
U = createHmac(digest, password).update(U).digest()
78+
U = hmac(pad, U)
3779
for (var k = 0; k < hLen; k++) T[k] ^= U[k]
3880
}
3981

0 commit comments

Comments
 (0)