create a sha1 hash from a string in javascript

To create a SHA1 hash from a string in JavaScript, you can use the crypto module that is available in both Node.js and modern web browsers. Here's an example code snippet:

const crypto = require('crypto');

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

const myString = 'hello world';
const myHash = sha1Hash(myString);
console.log(myHash); // Output: 2ef7bde608ce5404e97d5f042f95f89f1c232871
294 chars
12 lines

In this example, we first import the crypto module and define a function called sha1Hash that takes a string as input. Inside this function, we create a new SHA1 hash instance using crypto.createHash('sha1'), update it with the input string using sha1.update(str), and finally return the digest in hexadecimal format using sha1.digest('hex').

We then use this function to create a SHA1 hash of the "hello world" string and store it in myHash. Finally, we log the result to the console, which should be 2ef7bde608ce5404e97d5f042f95f89f1c232871.

gistlibby LogSnag