Skip to content

Commit b1e6dad

Browse files
committed
do this once, instead of many times
1 parent e937629 commit b1e6dad

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

pbkdf2.js

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ module.exports = function (createHmac, exports) {
1919
})
2020
}
2121

22-
exports.pbkdf2Sync = function(password, salt, iterations, keylen) {
22+
exports.pbkdf2Sync = function(key, salt, iterations, keylen) {
2323
if('number' !== typeof iterations)
2424
throw new TypeError('Iterations not a number')
2525
if(iterations < 0)
@@ -29,6 +29,17 @@ module.exports = function (createHmac, exports) {
2929
if(keylen < 0)
3030
throw new TypeError('Bad key length')
3131

32+
//stretch key to the correct length that hmac wants it,
33+
//otherwise this will happen every time hmac is called
34+
//twice per iteration.
35+
var key = !Buffer.isBuffer(key) ? new Buffer(key) : key
36+
37+
if(key.length > blocksize) {
38+
key = createHash(alg).update(key).digest()
39+
} else if(key.length < blocksize) {
40+
key = Buffer.concat([key, zeroBuffer], blocksize)
41+
}
42+
3243
var HMAC;
3344
var cplen, p = 0, i = 1, itmp = new Buffer(4), digtmp;
3445
var out = new Buffer(keylen);
@@ -47,14 +58,14 @@ module.exports = function (createHmac, exports) {
4758
itmp[2] = (i >> 8) & 0xff;
4859
itmp[3] = i & 0xff;
4960

50-
HMAC = createHmac('sha1', password);
61+
HMAC = createHmac('sha1', key);
5162
HMAC.update(salt)
5263
HMAC.update(itmp);
5364
digtmp = HMAC.digest();
5465
digtmp.copy(out, p, 0, cplen);
5566

5667
for(var j = 1; j < iterations; j++) {
57-
HMAC = createHmac('sha1', password);
68+
HMAC = createHmac('sha1', key);
5869
HMAC.update(digtmp);
5970
digtmp = HMAC.digest();
6071
for(var k = 0; k < cplen; k++) {

0 commit comments

Comments
 (0)