Node JS | Password Hashing with Crypto module
In real-life applications with User authentication functionality, storing the user passwords as the original string in the database is not practical. Still, it is good practice to hash the password and then store them in the database. Crypto module for Node JS helps developers to hash user passwords.
Examples:
Original Password : portalforgeeks
Hashed Password : bbf13ae4db87d475ca0ee5f97e397248a23509fc10c82f
1e3cf110b352c3ca6cc057955ace9d541573929cd7a74a
280a02e8cb549136b43df7704caaa555b38a
Password Hashing with Crypto module:
To demonstrate the use of the Crypto module, we can create a simple login and signup API and test it using Postman. We will use two functions:
- crypto.randomBytes(“length”): generates cryptographically strong data of given “length”.
- crypto.pbkdf2Sync(“password”, “salt”, “iterations”, “length”, “digest”): hashes “password” with “salt” with a number of iterations equal to given “iterations” (More iterations means more secure key) and uses algorithm given in “digest” and generates key of length equal to given “length”.
Project Dependencies:
- node JS: For Backend Server.
- express module for creating the server.
- mongoose module for MongoDB connection and queries.
- Crypto module for hashing.
- body-parser for parsing JSON data.
Let’s develop a simple nodejs server:
Step 1: Create a project folder
Step 2: Create package.json
Package.json will be created by typing the following command in the terminal or command prompt:
npm init -y
Project Directory:
hashApp
--model
----user.js
--route
----user.js
--server.js
Create model/user.js file which defines user schema
javascript
const mongoose = require( 'mongoose' );
const crypto = require( 'crypto' );
const UserSchema = mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
hash: String,
salt: String
});
UserSchema.methods.setPassword = function (password) {
this .salt = crypto.randomBytes(16).toString( 'hex' );
64 length and sha512 digest
this .hash = crypto.pbkdf2Sync(password, this .salt,
1000, 64, `sha512`).toString(`hex`);
};
UserSchema.methods.validPassword = function (password) {
var .hash = crypto.pbkdf2Sync(password,
this .salt, 1000, 64, `sha512`).toString(`hex`);
return this .hash === hash;
};
const User = module.exports = mongoose.model('User', UserSchema);
|
Create route/user.js file :
javascript
const express = require( 'express' );
const router = express.Router();
const User = require( '../model/user' );
router.post( '/login' , (req, res) => {
User.findOne({ email: req.body.email }, function (err, user) {
if (user === null ) {
return res.status(400).send({
message: "User not found." ;
});
}
else {
if (user.validPassword(req.body.password)) {
return res.status(201).send({
message: "User Logged In" ;,
})
}
else {
return res.status(400).send({
message: "Wrong Password" ;
});
}
}
});
});
router.post( '/signup' , (req, res, next) => {
let newUser = new User();
newUser.name = req.body.name,
newUser.email = req.body.email
newUser.setPassword(req.body.password);
newUser.save((err, User) => {
if (err) {
return res.status(400).send({
message: "Failed to add user."
});
}
else {
return res.status(201).send({
message: "User added successfully."
});
}
});
});
module.exports = router;
|
Create server.js file :
javascript
const express = require( 'express' );
const mongoose = require( 'mongoose' );
const bodyparser = require( 'body-parser' );
const app = express();
mongoose.connect(MONGODB_URI);
mongoose.connection.on( 'connected' , () => {
console.log( 'Connected to MongoDB @ 27017' );
});
app.use(bodyparser.json());
const user = require( './route/user' );
app.use( '/api/user' , user);
const port = 3000;
app.listen(port, () => {
console.log( "Server running at port:" + port);
});
|
Run the server.js file using the command node server.js from the hashApp directory
node server.js
If you have nodemon installed in your system then it can also be done by using the following link:
nodemon server.js
Open Postman and create a post request to localhost:3000/api/user/signup as below: You will get the response below:
User data is stored in the database as below:
{
"_id": {
"$oid": "5ab71ef2afb6db0148052f6f"
},
"name": "geeksforgeeks",
"email": "geek@geeksforgeeks.org",
"salt": "ddee18ef6a6804fbb919b25f790005e3",
"hash": "bbf13ae4db87d475ca0ee5f97e397248a23509fc10c82f1e3cf110
b352c3ca6cc057955ace9d541573929cd7a74a280a02e8cb549136b43df7704caaa555b38a",
"__v": 0
}
From Postman create a post request to localhost:3000/api/user/login as below:
You will get the response below:
Applications:
- Hashing password is necessary for practical application.
- Crypto module makes hashing easy to implement.
- Hashing passwords ensures user privacy.
References:
Last Updated :
27 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...