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

如何在Node.js JavaScript上执行此任务

最佳答案

如果您使用的是Node:

> 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

10-01 09:56