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