I'm trying to encrypt passwords in nodejs for a website using express.
Here is the function I use to encrypt the passwords:
const crypto = require('crypto');
// the problem
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
encrypt(str) {
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
let encrypted = cipher.update(str, 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted);
return encrypted;
}
The problem with this code is that if I were to restart this the key would be different and I would be getting different strings for the same password that's saved in the database. This wouldn't work out because I won't be able to test the password with the hash when a user submits when trying to log in.
How can I make it so that I will always receive the same encrypted string and is there a more secure way to do everything, maybe even other libraries that would do the job better?
Normally with nodejs bcryptjs is more suggested module for password encryption and decryption.
Follow below link to take an example of BcryptJs