Encrypt & decrypt password | Node.js
Safety is one of the most part in development. We always need to think about users personal data.
In this post I want to show you how to make and keep passwords in safe.
Saving original passwords in databases is not a good security practice. Would be better to keep encrypted passwords in your storage and than decrypt it using secret key.
For example, image a situation when user is registering on your website. He enters his password which you should to save. How do this correctly ?
First of all, you have to encrypt users password with secret key (I use npm module — crypto-js) and than save it into your database.
import * as CryptoJS from 'crypto-js';
const secretKey = 'secretKey';
function encrypt(password: string) {
return CryptoJS.AES.encrypt(password, secretKey).toString();
}
const encryptedPass = encrypt(user.password);When user log in into your website you should check if this user exist in your database. If yes, try to compare password in your database with user’s entered password.
import * as CryptoJS from 'crypto-js';
const secretKey = 'secretKey';
function decrypt(hash: string) {
return CryptoJS.AES.decrypt(hash, secretKey).toString(CryptoJS.enc.Utf8);
}
const decryptedPass = decrypt(user.password);That’s all from me. Keep your credentials in safe.