Last active
June 27, 2018 21:07
-
-
Save fernandocanizo/608d842811b41b3122906d43164322e2 to your computer and use it in GitHub Desktop.
Calculate proper number of required rounds for bcryptjs hashing on current hardware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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