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