1
|
var sizes = {
|
2
|
md5: 16,
|
3
|
sha1: 20,
|
4
|
sha224: 28,
|
5
|
sha256: 32,
|
6
|
sha384: 48,
|
7
|
sha512: 64,
|
8
|
rmd160: 20,
|
9
|
ripemd160: 20
|
10
|
}
|
11
|
|
12
|
var createHmac = require('create-hmac')
|
13
|
var checkParameters = require('../lib/precondition')
|
14
|
var defaultEncoding = require('../lib/default-encoding')
|
15
|
var Buffer = require('safe-buffer').Buffer
|
16
|
|
17
|
function pbkdf2 (password, salt, iterations, keylen, digest) {
|
18
|
checkParameters(password, salt, iterations, keylen)
|
19
|
|
20
|
if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
|
21
|
if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
|
22
|
|
23
|
digest = digest || 'sha1'
|
24
|
|
25
|
var DK = Buffer.allocUnsafe(keylen)
|
26
|
var block1 = Buffer.allocUnsafe(salt.length + 4)
|
27
|
salt.copy(block1, 0, 0, salt.length)
|
28
|
|
29
|
var destPos = 0
|
30
|
var hLen = sizes[digest]
|
31
|
var l = Math.ceil(keylen / hLen)
|
32
|
|
33
|
for (var i = 1; i <= l; i++) {
|
34
|
block1.writeUInt32BE(i, salt.length)
|
35
|
|
36
|
var T = createHmac(digest, password).update(block1).digest()
|
37
|
var U = T
|
38
|
|
39
|
for (var j = 1; j < iterations; j++) {
|
40
|
U = createHmac(digest, password).update(U).digest()
|
41
|
for (var k = 0; k < hLen; k++) T[k] ^= U[k]
|
42
|
}
|
43
|
|
44
|
T.copy(DK, destPos)
|
45
|
destPos += hLen
|
46
|
}
|
47
|
|
48
|
return DK
|
49
|
}
|
50
|
|
51
|
module.exports = pbkdf2
|