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
Bufferoutput.
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
| Step | Description | Code Example |
|---|---|---|
| 1 | Import crypto module | import crypto from 'crypto'; |
| 2 | Create SHA256 hash object | const hash = crypto.createHash('sha256'); |
| 3 | Add data to hash | hash.update('your data'); |
| 4 | Get hash output as hex string | const 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().