14

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

Toheeb
  • 1,217
  • 1
  • 14
  • 26
  • Most browsers have a Crypto API and [there's a SHA256 demo](https://jameshfisher.com/2017/10/30/web-cryptography-api-hello-world/) If you want to use a third-party library, you need to specify which library you used. – Filip Dimitrovski Apr 30 '19 at 17:54
  • 1
    sha512 github page says `This library is deprecated.` While browsing npm atleast check if it's actively maintained. https://github.com/cryptocoinjs/sha512 – 1565986223 Apr 30 '19 at 17:57
  • Yes I remembered I logged this deprecation error earlier and I was wondering why because I've tried different libraries on NPM. I'll try cryptocoinjs out. – Toheeb Apr 30 '19 at 18:02
  • @Lewis Apologies for the accusation! Yes it's a warning that breaks the API. The code literally stops running at that point and won't return anything. I'll have to make changes and restart the server to make it work again. Again I'm sorry for accusing you wrongly. – Toheeb May 01 '19 at 12:39
  • @Lewis thanks! I'll do the same – Toheeb May 01 '19 at 12:44

2 Answers2

44

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
Filip Dimitrovski
  • 1,576
  • 11
  • 15
-1

you can use this library npm.io/package/js-sha512

pabios
  • 9
  • 4
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/32641843) – Deenadhayalan Manoharan Sep 08 '22 at 09:30