I am trying a POC in react , , I have used react + mysql , and for DB operation I am using sequelize.
My login ,registration etc. working fine , till now I am storing password as plain text in DB.
Now I want to store encrypted password in DB, I have seen couple of example in internet where people are using bcrypt but they are using it on node(server side), i feel it need to encrypted on client(react) side so when we transmit it into network no one can access my password.
I had tried bcrypt into react and able to store my encrypted password into DB. Follwing is the code I had used for same Generated Salt
const salt = bcrypt.genSaltSync(10);
formik.values.password = bcrypt.hashSync(formik.values.password, salt)
Now password is encrypted and saved in DB.
But when I am trying to login with the help of same password, either compareSync or comapreasync I am always getting false
const y = bcrypt.compareSync(response.data.password, bcrypt.hashSync(formik.values.password, salt));
bcrypt.compare(response.data.password, formik.values.password, (err, data) => {
//if error than throw error
if (err) throw err;
if (data) { navigate("DashBoard"); }
})
Any Idea what I am doing wrong? Or when we are using Bcrypt do salt need to be same for all?
From the docs:
bcrypt.compareSync()
's first param takes a plain text password:While
bcrypt.hashSync()
will compute and return a hash:As you submit hashed password from client:
The password data from server:
response.data.password
, is actually a hash, not a plain password:So all you need is to pass in plain text password for it to compare.
Technically the password is hashed not encrypted.
Difference between Hashing vs Encryption:
Hashing: A one-way summary of data, cannot be reversed, used to validate the integrity of data.
Encryption: A two-way encoding of data, can be reversed, used to protect confidentiality of data.
Bonus: hashing is like a meat grinder. You can turn a cow to a hamburger, but not the reverse.
Read more: Fundamental difference between Hashing and Encryption algorithms