【问题标题】:How do I hash a string using JavaScript with sha512 algorithm如何使用带有 sha512 算法的 JavaScript 对字符串进行哈希处理
【发布时间】:2019-09-19 10:20:41
【问题描述】:

我尝试使用 NPM 的 sha512,但它一直在散列错误的东西,即我应该得到一个字符串,但它一直返回对象。 所以在 PHP 中我知道我可以执行任务$hash = hash("sha512","my string for hashing");

如何在 nodejs JavaScript 上执行此任务

【问题讨论】:

  • 大部分浏览器都有 Crypto API 和there's a SHA256 demo 如果要使用第三方库,需要指定使用的库。
  • sha512 github 页面显示 This library is deprecated. 在浏览 npm 时至少检查它是否得到积极维护。 github.com/cryptocoinjs/sha512
  • 是的,我记得我之前记录了这个弃用错误,我想知道为什么,因为我在 NPM 上尝试了不同的库。我会尝试cryptocoinjs。
  • @Lewis 为指控道歉!是的,这是一个破坏 API 的警告。代码从字面上停止运行,不会返回任何东西。我将不得不进行更改并重新启动服务器以使其再次工作。再次对不起,我错误地指责了你。
  • @Lewis 谢谢!我也会这样做

标签: javascript node.js mean-stack server-side


【解决方案1】:

如果您使用的是节点:

> crypto.createHash('sha512').update('my string for hashing').digest('hex');
'4dc43467fe9140f217821252f94be94e49f963eed1889bceab83a1c36ffe3efe87334510605a9bf3b644626ac0cd0827a980b698efbc1bde75b537172ab8dbd0'

如果你想使用浏览器的 Web Crypto API:

function sha512(str) {
  return crypto.subtle.digest("SHA-512", new TextEncoder("utf-8").encode(str)).then(buf => {
    return Array.prototype.map.call(new Uint8Array(buf), x=>(('00'+x.toString(16)).slice(-2))).join('');
  });
}

sha512("my string for hashing").then(x => console.log(x));
// prints: 4dc43467fe9140f217821252f94be94e49f963eed1889bceab83a1c36ffe3efe87334510605a9bf3b644626ac0cd0827a980b698efbc1bde75b537172ab8dbd0

【讨论】:

  • 当 OP 要求 sha512 时,为什么它说 sha256?
  • @BlueRineS 已编辑。
  • 注意:如果您不能为在您的 Intranet 上运行的事物创建 SSL 证书,Chrome 认为您不应该使用散列函数。 w3.org/2016/08/29-crypto-minutes.html
猜你喜欢
  • 2012-05-06
  • 2014-05-13
  • 2015-04-24
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 2021-07-31
  • 1970-01-01
  • 2017-01-15
相关资源
最近更新 更多