kelektiv / node.bcrypt.js

bcrypt for NodeJs
MIT License
7.43k stars 510 forks source link

Bcrypt causing CPU usage issue and consuming alot of time. #922

Closed sharmankita closed 2 years ago

sharmankita commented 2 years ago

Hi, I am using bcrpyt.js to generate password in our system. we have functionality of employee upload in this while inserting employees i am creating password for them as well.

so this process is working in loop.

but it taking a lot of time and CPU. like for 10000 employee my code took around 19 mins. attaching the sample code screenshot.

const crypto = require('crypto');
const bcrypt = require('bcryptjs');
let a = [];
console.time("dfsdf")
for(let i = 0 ; i < 10000 ; i++){
     a.push(createPassword())
}
console.timeEnd("dfsdf")

function createPassword () {
  let str = createRandomString(10);
  const saltRounds = 10;
  var enc_password = bcrypt.hashSync(str, saltRounds);
  return enc_password;
}

function createRandomString (len) {
  const buffer = crypto.randomBytes(len);
  var text = buffer.toString('hex');
  return text;
}

Screenshot 2022-03-14 at 6 28 26 PM

RenovatingDev commented 2 years ago

Although I am not a contributer to this project, I can give you the answer: Bcrypt is a hashing function with a so called "work factor" or "delay factor". It is intentionally "slow" (CPU- and memoryintensive). The slowness is what makes it secure as a hashing function for passwords. As per README.md, 10 salt rounds are roughly equivalent to about 10 hashes per second on a 2GHz core. 10,000 passwords / 10 passwords per second = 1000 seconds = ~16.7min.

For more information on why this is needed, I can suggest reading the OWASP Password Storage Cheat Sheet, especially the sections on How Attackers Crack Password Hashes and on Work Factors.

TLDR: to me this looks like working as intended.

recrsn commented 2 years ago

As said by @RSLak1, It is well within speed expectations and bcrypt is CPU heavy

Also, you are using bcryptjs (the pure-JS bcrypt implementation) which is about 20-25% slower.

sharmankita commented 2 years ago

@RSLak1 Thanks for the information.