gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:59:32 32 4
gpt4 key购买 nike

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

例如,如果我有

const string = "password";

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

const hash = hashFunction( string );

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

console.log( hash ); //5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

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

最佳答案

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

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

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

console.log(hash);
Output: 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

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

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

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

console.log(hash);
Output: 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

我希望这有帮助! :)

关于javascript - 如何在 JavaScript 中对字符串进行哈希处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74829667/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com