Open In App

How to hash string with md5 function in Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

Hashing means taking any string as a key and generating some other string for it as a value. It’s like key-value pair in maps or dictionaries. md5 hash is an encryption algorithm that takes the various bits of a file and outputs a unique text string. md5 is a one-way encryption algorithm, i.e. there is no direct way of decryption. Using md5 hashing, you can only compare if two strings are equal or not by comparing the hash strings generated for them. For this purpose, we are going to use the md5 npm package and prompt module  md5 is a javascript module that is used to encrypt the data and the prompt module is used for taking the input from the terminal.

Steps to use md5 function to hash the string:

Step 1: create an “app.js” file and initialize the project using npm.

npm init

Step 2: Install md5 and prompt npm packages using npm install.

npm install md5
npm install prompt

Project structure:

Step 3: Now let’s code the “app.js” file. We take the required string as input from the user then use the md5() function to generate its hash string.

app.js

Javascript




// Prompt is used to take input from console
const prompt = require("prompt");
 
// md5 is used to hash the given string
const md5 = require("md5");
 
// Utility function to perform the operation
function hash() {
 
  // Start the prompt
  prompt.start();
 
  // Get string input as str from the console
  prompt.get(["str"], function (err, res) {
 
    // To handle any error if occurred
    if (err) {
      console.log(err);
    } else {
 
      // To generate the hashed string
      const hash = md5(res.str);
 
      // To print hashed string in the console
      console.log("hashed string is: ", hash);
    }
  });
}
 
// Calling the function
hash();


Step 4: Run app.js file using below command:

node app.js

Output:


Last Updated : 13 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads