You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sync.js 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. var createHmac = require('create-hmac')
  12. var checkParameters = require('../lib/precondition')
  13. var defaultEncoding = require('../lib/default-encoding')
  14. var Buffer = require('safe-buffer').Buffer
  15. function pbkdf2 (password, salt, iterations, keylen, digest) {
  16. checkParameters(password, salt, iterations, keylen)
  17. if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
  18. if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
  19. digest = digest || 'sha1'
  20. var DK = Buffer.allocUnsafe(keylen)
  21. var block1 = Buffer.allocUnsafe(salt.length + 4)
  22. salt.copy(block1, 0, 0, salt.length)
  23. var destPos = 0
  24. var hLen = sizes[digest]
  25. var l = Math.ceil(keylen / hLen)
  26. for (var i = 1; i <= l; i++) {
  27. block1.writeUInt32BE(i, salt.length)
  28. var T = createHmac(digest, password).update(block1).digest()
  29. var U = T
  30. for (var j = 1; j < iterations; j++) {
  31. U = createHmac(digest, password).update(U).digest()
  32. for (var k = 0; k < hLen; k++) T[k] ^= U[k]
  33. }
  34. T.copy(DK, destPos)
  35. destPos += hLen
  36. }
  37. return DK
  38. }
  39. module.exports = pbkdf2