How do I use SHA256 in Node.js?

How do I use SHA256 in Node.js?
----------------------------------------------

In Node.js, you can use the built-in `crypto` module to generate SHA256 hashes. Here's an example of how to use SHA256 in Node.js:

const crypto = require('crypto');

// Function to generate SHA256 hash
function generateSHA256Hash(data) {
  const hash = crypto.createHash('sha256');
  hash.update(data);
  return hash.digest('hex');
}

// Example usage
const inputString = 'Hello, World!';
const sha256Hash = generateSHA256Hash(inputString);

console.log(`Input String: ${inputString}`);
console.log(`SHA256 Hash: ${sha256Hash}`);

Explanation:

1. Import the `crypto` module using `require('crypto')`.
2. Create a function (`generateSHA256Hash`) that takes data as input, creates a SHA256 hash object, updates it with the provided data, and then generates the hash in hexadecimal format using `digest('hex')`.
3. Call the `generateSHA256Hash` function with your desired input data.
4. Print the input string and the corresponding SHA256 hash to the console.

Make sure to handle sensitive data securely and consider additional measures if you're working with passwords or other confidential information. Additionally, Node.js crypto module's documentation should be checked for any updates or changes: [Node.js crypto documentation](https://nodejs.org/api/crypto.html).

@coderuck

Categories: Java Script Tags: #NodeJs, #ES6, #JavaScript,

Newsletter Subcribe

Receive updates and latest news direct from our team. Simply enter your email.