如何使用带有sha512算法的JavaScript来散列字符串

问题描述 投票:-3回答:1

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

如何在nodejs JavaScript上执行此任务

javascript node.js mean-stack server-side
1个回答
1
投票

如果您使用的是Node:

> crypto.createHash('sha256').update('my string for hashing').digest('hex');
'3826503473858f545663db472ae7d95281cd57dfd228cf2dd34d5ba64c444c81'

如果要使用浏览器Web Crypto API:

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

sha256("my string for hashing").then(x => console.log(x));
// prints: 3826503473858f545663db472ae7d95281cd57dfd228cf2dd34d5ba64c444c81
© www.soinside.com 2019 - 2024. All rights reserved.