sync.js 1.2 KB

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