Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fernandocanizo/608d842811b41b3122906d43164322e2 to your computer and use it in GitHub Desktop.
Save fernandocanizo/608d842811b41b3122906d43164322e2 to your computer and use it in GitHub Desktop.
Calculate proper number of required rounds for bcryptjs hashing on current hardware
'use strict';
const bcrypt = require('bcryptjs');
const getCost = async () => {
// This code will benchmark your server to determine how high of a cost
// you can afford. You want to set the highest cost that you can
// without slowing down you server too much. 8-10 is a good baseline,
// and more is good if your servers are fast enough. The code below
// aims for ≤ 50 milliseconds stretching time, which is a good baseline
// for systems handling interactive logins.
const clearPassword = 'String to encode';
const maxMilliseconds = 50;
// Note: bcryptjs has a setup time cost which is reflected on the first calculation
// if you choose a lower value, an insecure cost will pass the test
let cost = 10;
let start;
let end;
do {
try {
start = Date.now();
const salt = await bcrypt.genSalt(cost);
await bcrypt.hash(clearPassword, salt);
end = Date.now();
cost++;
} catch (e) {
console.log(e);
}
} while ((end - start) < maxMilliseconds);
// cost should be between 04 and 31
// Also since `bcryptjs` is 30% slower than its analogous C++ binding bcrypt,
// add that to the cost
cost = Math.round(cost * .3 + cost);
return (cost > 31) ? 31 : cost;
};
module.exports = getCost;
// TODO make it a memoizable function with a way to autoupdate each <configurable> month/s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment