Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 01 Oct, 2021

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 occured
    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:

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!