如何在Node.js中使用md5函数进行字符串哈希

如何在Node.js中使用md5函数进行字符串哈希

哈希 是将任何字符串作为键,并为其生成其他字符串作为值的过程。它就像映射或字典中的键值对。 md5 哈希是一种加密算法,它接受文件的各个位,并输出唯一的文本字符串。md5是一种单向加密算法,即没有直接的解密方式。使用md5哈希,您只能通过比较为它们生成的哈希字符串来判断两个字符串是否相等。为此,我们将使用 md5 npm包和prompt模块。md5是一个用于加密数据的JavaScript模块,prompt模块用于从终端接收输入。

使用md5函数对字符串进行哈希的步骤:

步骤1: 创建一个名为” app.js “的文件,并使用npm初始化项目。

npm init
JavaScript

步骤2: 使用npm install安装md5和prompt的npm包。

npm install md5
npm install prompt
JavaScript

项目结构:

如何在Node.js中使用md5函数进行字符串哈希

步骤3: 现在让我们编写“ app.js ”文件。我们从用户那里获取所需的字符串作为输入,然后使用 md5() 函数生成其哈希字符串。

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();
JavaScript

步骤4: 使用以下命令运行app.js文件:

node app.js
JavaScript

输出:

如何在Node.js中使用md5函数进行字符串哈希

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册