index.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. var Buffer = require('safe-buffer').Buffer
  2. var MD5 = require('md5.js')
  3. /* eslint-disable camelcase */
  4. function EVP_BytesToKey (password, salt, keyBits, ivLen) {
  5. if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')
  6. if (salt) {
  7. if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')
  8. if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')
  9. }
  10. var keyLen = keyBits / 8
  11. var key = Buffer.alloc(keyLen)
  12. var iv = Buffer.alloc(ivLen || 0)
  13. var tmp = Buffer.alloc(0)
  14. while (keyLen > 0 || ivLen > 0) {
  15. var hash = new MD5()
  16. hash.update(tmp)
  17. hash.update(password)
  18. if (salt) hash.update(salt)
  19. tmp = hash.digest()
  20. var used = 0
  21. if (keyLen > 0) {
  22. var keyStart = key.length - keyLen
  23. used = Math.min(keyLen, tmp.length)
  24. tmp.copy(key, keyStart, 0, used)
  25. keyLen -= used
  26. }
  27. if (used < tmp.length && ivLen > 0) {
  28. var ivStart = iv.length - ivLen
  29. var length = Math.min(ivLen, tmp.length - used)
  30. tmp.copy(iv, ivStart, used, used + length)
  31. ivLen -= length
  32. }
  33. }
  34. tmp.fill(0)
  35. return { key: key, iv: iv }
  36. }
  37. module.exports = EVP_BytesToKey