create a sha512 hash from a string in javascript

To create a SHA-512 hash from a string in JavaScript, we can use the built-in crypto module which provides cryptographic functionality. We can use the createHash method of this module to create the hash object and update method to update the hash with data. Finally, we can call the digest method to obtain the final hash value.

Here's an example code snippet to create a SHA-512 hash from a string in JavaScript:

index.tsx
const crypto = require('crypto');

function sha512(str) {
  const hash = crypto.createHash('sha512');
  hash.update(str);
  return hash.digest('hex');
}

const hashValue = sha512('my string to hash');
console.log(hashValue); // prints the SHA-512 hash value of the string
272 chars
11 lines

In this code, we first import the crypto module which provides the necessary functionality. We define a sha512 function which takes the string to be hashed as an argument. Inside the function, we create a sha512 hash object using the createHash method of crypto. We then update the hash object with the given string using the update method. Finally, we call the digest method to obtain the hash value in hexadecimal format.

We can call the sha512 function with any string that we want to hash and it will return the SHA-512 hash value of that string.

gistlibby LogSnag