Loading lesson path
Concept visual
Start from A
The Hash class is part of Node.js's crypto module. It provides a way to create cryptographic hash digests of data. Hash instances are created using the crypto.createHash() method. Hash functions are one-way functions that map data of arbitrary size to a fixed-size value called a digest. They are designed to be fast to compute but practically impossible to reverse.
// Import the crypto module const crypto = require('crypto');
// Create a hash object const hash = crypto.createHash('sha256');Description hash.update(data[, inputEncoding])
Updates the hash content with the given data. If inputEncoding is provided, data is a string using the specified encoding; otherwise, data is a Buffer, TypedArray, or DataView. This method can be called multiple times with new data.
hash.digest([encoding])
Calculates the digest of all the data passed to the hash using hash.update(). If encoding is provided, a string is returned; otherwise, a Buffer is returned. After this method is called, the Hash object can no longer be used.
hash.copy()Creates a new Hash object that contains a deep copy of the internal state of the current Hash object. This is useful when you want to generate multiple hashes based on the same partial data.
Node.js supports many hash algorithms. You can get a list of all supported algorithms with:
const crypto = require('crypto');
// Get all supported hash algorithms console.log(crypto.getHashes());128 bits (16 bytes) Fast, but cryptographically broken
Formula
Only for non - security purposes (e.g., checksums)sha1 160 bits (20 bytes) Fast, but cryptographically broken
256 bits (32 bytes)
512 bits (64 bytes)
256 bits (32 bytes)
512 bits (64 bytes)
The following example demonstrates how to create a hash digest of a string:
const crypto = require('crypto');
// Data to hash const data = 'Hello, World!';
// Create a hash object const hash = crypto.createHash('sha256');
// Update the hash with data hash.update(data);
// Get the digest in hex format const digest = hash.digest('hex');
console.log('Data:', data);
console.log('SHA-256 Hash:', digest);This example compares different hash algorithms:
const crypto = require('crypto');
// Data to hash const data = 'Node.js Crypto Hash Example';
// Function to hash data with different algorithms function hashWithAlgorithm(algorithm, data) {
const hash = crypto.createHash(algorithm);
hash.update(data);
return hash.digest('hex');
}
// Test various hash algorithms const algorithms = ['md5', 'sha1', 'sha256', 'sha512', 'sha3-256', 'sha3-512'];
console.log(`Data: "${data}"`);
console.log('------------------------------------');
algorithms.forEach(algorithm => {
try {
const digest = hashWithAlgorithm(algorithm, data);
console.log(`${algorithm}: ${digest}`);
console.log(`Length: ${digest.length / 2} bytes (${digest.length * 4} bits)`);
console.log('------------------------------------');
} catch (error) {
console.log(`${algorithm}: Not supported - ${error.message}`);
console.log('------------------------------------');
}
});You can update a hash with multiple pieces of data before calculating the digest:
const crypto = require('crypto');
// Create a hash object const hash = crypto.createHash('sha256');
// Update the hash with multiple pieces of data hash.update('First part of the data.');
hash.update(' Second part of the data.');
hash.update(' Third part of the data.');
// Calculate the final digest const digest = hash.digest('hex');
console.log('Combined data: First part of the data. Second part of the data. Third part of the data.');
console.log('SHA-256 Hash:', digest);
// You can achieve the same result with a single update const singleHash = crypto.createHash('sha256');
singleHash.update('First part of the data. Second part of the data. Third part of the data.');
const singleDigest = singleHash.digest('hex');
console.log('Single update hash matches multiple updates?', singleDigest === digest);You can get a hash digest in different encodings:
const crypto = require('crypto');
// Data to hash const data = 'Hello, Node.js!';
// Function to hash data and get digest in different encodings function hashWithEncoding(algorithm, data, encoding) {
const hash = crypto.createHash(algorithm);
hash.update(data);
return hash.digest(encoding);
}Formula
// Hash the data with SHA - 256 and display in different encodings console.log(`Data: "${data}"`);console.log(`SHA-256 (hex): ${hashWithEncoding('sha256', data, 'hex')}`);
console.log(`SHA-256 (base64): ${hashWithEncoding('sha256', data, 'base64')}`);
console.log(`SHA-256 (base64url): ${hashWithEncoding('sha256', data, 'base64url')}`);
console.log(`SHA-256 (binary): ${hashWithEncoding('sha256', data, 'binary')}`);
// Get the digest as a Buffer (no encoding)
const hash = crypto.createHash('sha256');
hash.update(data);
const buffer = hash.digest();
console.log('SHA-256 (Buffer):', buffer);
console.log('Buffer length:', buffer.length, 'bytes');You can hash the contents of a file:
const crypto = require('crypto');
const fs = require('fs');
// Function to hash a file using streams function hashFile(filePath, algorithm) {
return new Promise((resolve, reject) => {
// Create hash object const hash = crypto.createHash(algorithm);
// Create read stream const stream = fs.createReadStream(filePath);
// Handle stream events stream.on('data', (data) => {
hash.update(data);
});
stream.on('end', () => {
const digest = hash.digest('hex');
resolve(digest);
});
stream.on('error', (error) => {
reject(error);
});
});
}
// Example usage (adjust file path as needed)
const filePath = 'example.txt';
// Create a test file if it doesn't exist if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, 'This is a test file for hashing.\n'.repeat(100));
console.log(`Created test file: ${filePath}`);
}// Hash the file with different algorithms Promise.all([ hashFile(filePath, 'md5'), hashFile(filePath, 'sha1'), hashFile(filePath, 'sha256')
]).then(([md5Digest, sha1Digest, sha256Digest]) => {
console.log(`File: ${filePath}`);
console.log(`MD5: ${md5Digest}`);
console.log(`SHA-1: ${sha1Digest}`);
console.log(`SHA-256: ${sha256Digest}`);
}).catch(error => {
console.error('Error hashing file:', error.message);
});
Using hash.copy()
The hash.copy()method allows you to create a copy of a hash object:
const crypto = require('crypto');
// Create a hash object const hash = crypto.createHash('sha256');
// Update with common data hash.update('Common prefix data');
// Create a copy const hashCopy = hash.copy();
// Update the original hash with more data hash.update(' with additional data for original');
const originalDigest = hash.digest('hex');
// Update the copy with different data hashCopy.update(' with different data for copy');
const copyDigest = hashCopy.digest('hex');
console.log('Original hash:', originalDigest);
console.log('Copy hash:', copyDigest);
console.log('Are they different?', originalDigest !== copyDigest);// This is useful when you want to create multiple hash variations // from a common starting point, without recalculating the common portion