如何在 JavaScript 中对字符串进行哈希处理?

Rol*_*zar 2 javascript hash node.js

我想对字符串进行哈希处理,但我不想实现哈希算法。是否有内置的 JavaScript 函数或可靠的 npm 包来哈希字符串?如果是这样,我如何使用它来哈希字符串?

例如,如果我有

const string = "password";
Run Code Online (Sandbox Code Playgroud)

我想通过某种现成的函数或方法来运行它,就像这样

const hash = hashFunction( string );
Run Code Online (Sandbox Code Playgroud)

然后从中获取哈希值,如下所示

console.log( hash ); //5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8
Run Code Online (Sandbox Code Playgroud)

注意:我知道这个问题与这个问题类似,但是那里选择的答案实现了哈希。我专门寻找现成的可靠函数或散列方法。

Ven*_*nse 5

我相信可以简单地使用内置对象。

它提供加密功能,包括散列字符串的能力。

const crypto = require('crypto');
const string = "password";
const hash = crypto.createHash('sha256').update(string).digest('hex'); 

console.log(hash);
Run Code Online (Sandbox Code Playgroud)
Output: 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8
Run Code Online (Sandbox Code Playgroud)

或者正如 @Spectric 所提到的,您可以使用 CryptoJS 库。

const CryptoJS = require("crypto-js");

const string = "password";
const hash = CryptoJS.SHA256(string).toString();

console.log(hash);
Run Code Online (Sandbox Code Playgroud)
Output: 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!:)