0
0
NodejsHow-ToBeginner · 3 min read

How to Use SHA256 Hash in Node.js: Simple Guide

In Node.js, you can create a SHA256 hash using the built-in crypto module by calling crypto.createHash('sha256'). Then, update the hash with your data and finalize it with digest('hex') to get the hash string.
📐

Syntax

To create a SHA256 hash in Node.js, use the crypto.createHash method with 'sha256' as the algorithm. Then, add data with update() and get the final hash string with digest().

  • crypto.createHash('sha256'): Initializes the SHA256 hash object.
  • update(data): Adds data to be hashed.
  • digest('hex'): Produces the hash output as a hexadecimal string.
javascript
const crypto = require('crypto');

const hash = crypto.createHash('sha256');
hash.update('your data here');
const result = hash.digest('hex');
console.log(result);
💻

Example

This example shows how to hash the string 'hello world' using SHA256 and print the hexadecimal hash.

javascript
import crypto from 'crypto';

const data = 'hello world';
const hash = crypto.createHash('sha256');
hash.update(data);
const sha256Hash = hash.digest('hex');
console.log(sha256Hash);
Output
b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
⚠️

Common Pitfalls

Common mistakes include:

  • Not calling digest() which finalizes the hash and returns the result.
  • Calling digest() multiple times on the same hash object, which throws an error.
  • Forgetting to specify the output format like 'hex', resulting in a Buffer output.
javascript
import crypto from 'crypto';

// Wrong: calling digest twice
const hash = crypto.createHash('sha256');
hash.update('data');
console.log(hash.digest('hex'));
// console.log(hash.digest('hex')); // This will throw an error

// Right: call digest only once
const hash2 = crypto.createHash('sha256');
hash2.update('data');
const result = hash2.digest('hex');
console.log(result);
📊

Quick Reference

StepDescriptionCode Example
1Import crypto moduleimport crypto from 'crypto';
2Create SHA256 hash objectconst hash = crypto.createHash('sha256');
3Add data to hashhash.update('your data');
4Get hash output as hex stringconst result = hash.digest('hex');

Key Takeaways

Use Node.js built-in crypto module to create SHA256 hashes easily.
Always call digest() once to finalize and get the hash output.
Specify 'hex' in digest() to get a readable string instead of a Buffer.
Avoid calling digest() multiple times on the same hash object.
Use update() to add all data before calling digest().