How do I hash a string using JavaScript with sha512 algorithm

…衆ロ難τιáo~ 提交于 2020-06-01 07:22:26

问题


I've tried using sha512 from NPM but it keeps hashing the wrong thing i.e I am supposed to get a string but it keeps returning object. So in PHP I know I can perform the task $hash = hash("sha512","my string for hashing");

How do I perform this task on nodejs JavaScript


回答1:


If you are using Node:

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

If you want to use the browser 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


来源:https://stackoverflow.com/questions/55926281/how-do-i-hash-a-string-using-javascript-with-sha512-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!