javascriptnode.jsmean-stackserver-side

How do I hash a string using JavaScript with sha512 algorithm


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


Solution

  • 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