pass.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // check out https://github.com/tj/node-pwd
  2. /*jslint node: true */
  3. /*jshint node: true */
  4. /*jshint strict:false */
  5. /*jshint -W097 */
  6. /*jshint esversion: 6 */
  7. "use strict";
  8. // Module dependencies.
  9. const crypto = require('crypto');
  10. // Bytesize.
  11. const len = 128;
  12. // Iterations. ~300ms
  13. const iterations = 12000;
  14. /**
  15. * Hashes a password with optional `salt`, otherwise
  16. * generate a salt for `pass` and invoke `fn(err, salt, hash)`.
  17. *
  18. * @param {String} password to hash
  19. * @param {String} optional salt
  20. * @param {Function} callback
  21. * @api public
  22. */
  23. exports.hash = function (pwd, salt, fn, tag) {
  24. if (4 == arguments.length) {
  25. try {
  26. crypto.pbkdf2(pwd, salt, iterations, len, 'sha384', function (err, hash) { fn(err, hash.toString('base64'), tag); });
  27. } catch (e) {
  28. // If this previous call fails, it's probably because older pbkdf2 did not specify the hashing function, just use the default.
  29. crypto.pbkdf2(pwd, salt, iterations, len, function (err, hash) { fn(err, hash.toString('base64'), tag); });
  30. }
  31. } else {
  32. tag = fn;
  33. fn = salt;
  34. crypto.randomBytes(len, function (err, salt) {
  35. if (err) return fn(err);
  36. salt = salt.toString('base64');
  37. try {
  38. crypto.pbkdf2(pwd, salt, iterations, len, 'sha384', function (err, hash) { if (err) { return fn(err); } fn(null, salt, hash.toString('base64'), tag); });
  39. } catch (e) {
  40. // If this previous call fails, it's probably because older pbkdf2 did not specify the hashing function, just use the default.
  41. crypto.pbkdf2(pwd, salt, iterations, len, function (err, hash) { if (err) { return fn(err); } fn(null, salt, hash.toString('base64'), tag); });
  42. }
  43. });
  44. }
  45. };
  46. exports.iishash = function (type, pwd, salt, fn) {
  47. if (type == 0) {
  48. fn(null, pwd);
  49. } else if (type == 1) {
  50. const hash = crypto.createHash('sha1');
  51. hash.update(Buffer.concat([Buffer.from(salt, 'base64'), Buffer.from(pwd, 'utf16le')]));
  52. fn(null, hash.digest().toString('base64'));
  53. } else {
  54. fn('invalid type');
  55. }
  56. };