2017-05-24 15:10:37 +02:00
|
|
|
var sizes = {
|
|
|
|
md5: 16,
|
|
|
|
sha1: 20,
|
|
|
|
sha224: 28,
|
|
|
|
sha256: 32,
|
|
|
|
sha384: 48,
|
|
|
|
sha512: 64,
|
|
|
|
rmd160: 20,
|
|
|
|
ripemd160: 20
|
|
|
|
}
|
|
|
|
|
|
|
|
var createHmac = require('create-hmac')
|
|
|
|
var checkParameters = require('../lib/precondition')
|
|
|
|
var defaultEncoding = require('../lib/default-encoding')
|
|
|
|
var Buffer = require('safe-buffer').Buffer
|
2017-08-14 05:01:11 +02:00
|
|
|
|
2017-05-24 15:10:37 +02:00
|
|
|
function pbkdf2 (password, salt, iterations, keylen, digest) {
|
|
|
|
if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
|
|
|
|
if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
|
|
|
|
|
|
|
|
checkParameters(iterations, keylen)
|
|
|
|
digest = digest || 'sha1'
|
|
|
|
|
|
|
|
var DK = Buffer.allocUnsafe(keylen)
|
|
|
|
var block1 = Buffer.allocUnsafe(salt.length + 4)
|
|
|
|
salt.copy(block1, 0, 0, salt.length)
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
var destPos = 0
|
2017-05-24 15:10:37 +02:00
|
|
|
var hLen = sizes[digest]
|
|
|
|
var l = Math.ceil(keylen / hLen)
|
|
|
|
|
|
|
|
for (var i = 1; i <= l; i++) {
|
|
|
|
block1.writeUInt32BE(i, salt.length)
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
var T = createHmac(digest, password).update(block1).digest()
|
|
|
|
var U = T
|
2017-05-24 15:10:37 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
for (var j = 1; j < iterations; j++) {
|
2017-05-24 15:10:37 +02:00
|
|
|
U = createHmac(digest, password).update(U).digest()
|
|
|
|
for (var k = 0; k < hLen; k++) T[k] ^= U[k]
|
|
|
|
}
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
T.copy(DK, destPos)
|
|
|
|
destPos += hLen
|
2017-05-24 15:10:37 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return DK
|
|
|
|
}
|
2017-08-14 05:01:11 +02:00
|
|
|
|
|
|
|
module.exports = pbkdf2
|