Hash Object
Hash வகுப்பு Node.js இன் crypto தொகுதியின் ஒரு பகுதியாகும். இது தரவின் கிரிப்டோகிராஃபிக் ஹாஷ் டைஜெஸ்ட்களை உருவாக்க ஒரு வழியை வழங்குகிறது. Hash நிகழ்வுகள் crypto.createHash() முறையைப் பயன்படுத்தி உருவாக்கப்படுகின்றன.
ஹாஷ் செயல்பாடுகள் ஒரு-வழி செயல்பாடுகள் ஆகும், அவை தன்னிச்சையான அளவிலான தரவை டைஜெஸ்ட் என்று அழைக்கப்படும் நிலையான-அளவு மதிப்புக்கு மேப்பிங் செய்கின்றன. அவை கணக்கிட வேகமாக இருக்க வடிவமைக்கப்பட்டுள்ளன, ஆனால் நடைமுறையில் தலைகீழாக மாற்ற முடியாதவை.
Import Crypto Module
// Import the crypto module
const crypto = require('crypto');
// Create a hash object
const hash = crypto.createHash('sha256');
Hash Methods
| முறை | விளக்கம் |
|---|---|
| hash.update(data[, inputEncoding]) | கொடுக்கப்பட்ட தரவுடன் ஹாஷ் உள்ளடக்கத்தைப் புதுப்பிக்கிறது. inputEncoding வழங்கப்பட்டால், தரவு குறிப்பிட்ட குறியீட்டைப் பயன்படுத்தி ஒரு சரமாகும்; இல்லையெனில், தரவு ஒரு Buffer, TypedArray, அல்லது DataView ஆகும். இந்த முறை புதிய தரவுடன் பல முறை அழைக்கப்படலாம். |
| hash.digest([encoding]) | hash.update() ஐப் பயன்படுத்தி அனுப்பப்பட்ட அனைத்து தரவின் டைஜெஸ்டைக் கணக்கிடுகிறது. encoding வழங்கப்பட்டால், ஒரு சரம் திரும்பும்; இல்லையெனில், ஒரு Buffer திரும்பும். இந்த முறை அழைக்கப்பட்ட பிறகு, Hash பொருள் இனி பயன்படுத்தப்பட முடியாது. |
| hash.copy() | தற்போதைய Hash பொருளின் உள் நிலையின் ஆழமான நகலைக் கொண்ட ஒரு புதிய Hash பொருளை உருவாக்குகிறது. அதே பகுதி தரவின் அடிப்படையில் பல ஹாஷ்களை உருவாக்க விரும்பும் போது இது பயனுள்ளதாக இருக்கும். |
Supported Hash Algorithms
Node.js பல ஹாஷ் அல்காரிதம்களை ஆதரிக்கிறது. நீங்கள் ஆதரிக்கப்படும் அனைத்து அல்காரிதம்களின் பட்டியலைப் பெறலாம்:
const crypto = require('crypto');
// Get all supported hash algorithms
console.log(crypto.getHashes());
பொதுவான ஹாஷ் அல்காரிதம்கள் அடங்கும்:
| அல்காரிதம் | வெளியீடு அளவு | விளக்கம் | பரிந்துரைக்கப்பட்ட பயன்பாடு |
|---|---|---|---|
| md5 | 128 bits (16 bytes) | வேகமானது, ஆனால் கிரிப்டோகிராஃபிகலாக உடைந்தது | பாதுகாப்பு அல்லாத நோக்கங்களுக்கு மட்டும் (எ.கா., செக்சம்கள்) |
| sha1 | 160 bits (20 bytes) | வேகமானது, ஆனால் கிரிப்டோகிராஃபிகலாக உடைந்தது | பாதுகாப்பு அல்லாத நோக்கங்களுக்கு மட்டும் |
| sha256 | 256 bits (32 bytes) | SHA-2 குடும்பத்தின் ஒரு பகுதி | பொது கிரிப்டோகிராஃபிக் பயன்பாடு |
| sha512 | 512 bits (64 bytes) | SHA-2 குடும்பத்தின் ஒரு பகுதி | அதிக பாதுகாப்பு பயன்பாடுகள் |
| sha3-256 | 256 bits (32 bytes) | SHA-3 குடும்பத்தின் ஒரு பகுதி | நவீன கிரிப்டோகிராஃபிக் பயன்பாடுகள் |
| sha3-512 | 512 bits (64 bytes) | SHA-3 குடும்பத்தின் ஒரு பகுதி | அதிக பாதுகாப்பு நவீன பயன்பாடுகள் |
Basic Hash Example
பின்வரும் எடுத்துக்காட்டு ஒரு சரத்தின் ஹாஷ் டைஜெஸ்டை எவ்வாறு உருவாக்குவது என்பதை விளக்குகிறது:
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);
Comparing 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('------------------------------------');
}
});
Hashing with Multiple Updates
டைஜெஸ்டைக் கணக்கிடுவதற்கு முன் பல தரவுத் துண்டுகளுடன் ஒரு ஹாஷைப் புதுப்பிக்கலாம்:
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);
Hash with 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);
}
// 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');
File Hashing
நீங்கள் ஒரு கோப்பின் உள்ளடக்கங்களை ஹாஷ் செய்யலாம்:
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()
hash.copy() முறை ஒரு ஹாஷ் பொருளின் நகலை உருவாக்க உங்களை அனுமதிக்கிறது:
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
Hash Performance Comparison
இந்த எடுத்துக்காட்டு வெவ்வேறு ஹாஷ் அல்காரிதம்களின் செயல்திறனை ஒப்பிடுகிறது:
const crypto = require('crypto');
const { performance } = require('perf_hooks');
// Data to hash (1MB of random data)
const data = crypto.randomBytes(1024 * 1024);
// Function to measure hash algorithm performance
function measureHashPerformance(algorithm, iterations = 100) {
// Ensure the algorithm is supported
try {
crypto.createHash(algorithm);
} catch (error) {
return { algorithm, error: error.message };
}
const startTime = performance.now();
for (let i = 0; i < iterations; i++) {
const hash = crypto.createHash(algorithm);
hash.update(data);
hash.digest();
}
const endTime = performance.now();
const totalTime = endTime - startTime;
return {
algorithm,
iterations,
totalTimeMs: totalTime.toFixed(2),
timePerHashMs: (totalTime / iterations).toFixed(4),
hashesPerSecond: Math.floor(iterations / (totalTime / 1000))
};
}
// Test various hash algorithms
const algorithms = ['md5', 'sha1', 'sha256', 'sha512', 'sha3-256', 'sha3-512'];
const results = [];
console.log('Measuring hash performance for 1MB of data...');
algorithms.forEach(algorithm => {
results.push(measureHashPerformance(algorithm));
});
// Display results in a table format
console.table(results);
// Display relative performance (normalized to the fastest algorithm)
console.log('\nRelative Performance:');
// Find the fastest algorithm
const fastest = results.reduce((prev, current) => {
if (current.error) return prev;
return (prev && prev.hashesPerSecond > current.hashesPerSecond) ? prev : current;
}, null);
if (fastest) {
results.forEach(result => {
if (!result.error) {
const relativeSpeed = (result.hashesPerSecond / fastest.hashesPerSecond).toFixed(2);
console.log(`${result.algorithm}: ${relativeSpeed}x (${result.hashesPerSecond} hashes/sec)`);
} else {
console.log(`${result.algorithm}: Error - ${result.error}`);
}
});
}
Password Hashing
எச்சரிக்கை:
பின்வரும் எடுத்துக்காட்டு பொது-நோக்க ஹாஷ் செயல்பாடுகளுடன் கடவுச்சொல் ஹாஷிங்கை விளக்குகிறது. பாதுகாப்பான கடவுச்சொல் சேமிப்பிற்கு, கடவுச்சொல் ஹாஷிங்கிற்காக குறிப்பாக வடிவமைக்கப்பட்ட bcrypt, scrypt, அல்லது Argon2 போன்ற சிறப்பு அல்காரிதம்களைப் பயன்படுத்தவும், அவை உப்பு மற்றும் வேலை காரணிகளை உள்ளடக்கியவை.
இந்த எடுத்துக்காட்டு உப்புடன் கடவுச்சொற்களை எவ்வாறு ஹாஷ் செய்வது என்பதைக் காட்டுகிறது:
const crypto = require('crypto');
// Function to hash a password with a salt
function hashPassword(password, salt) {
// Create hash object
const hash = crypto.createHash('sha256');
// Update with salt and password
hash.update(salt);
hash.update(password);
// Return digest
return hash.digest('hex');
}
// Generate a random salt
function generateSalt() {
return crypto.randomBytes(16).toString('hex');
}
// Example usage
const password = 'mySecurePassword123';
// For a new user, generate a salt and hash the password
const salt = generateSalt();
const hashedPassword = hashPassword(password, salt);
console.log('Password:', password);
console.log('Salt:', salt);
console.log('Hashed Password:', hashedPassword);
// To verify a password, hash it with the same salt and compare
function verifyPassword(password, salt, storedHash) {
const hash = hashPassword(password, salt);
return hash === storedHash;
}
// Check correct password
console.log('Verification with correct password:',
verifyPassword(password, salt, hashedPassword));
// Check incorrect password
console.log('Verification with incorrect password:',
verifyPassword('wrongPassword', salt, hashedPassword));
// Note: For production, use crypto.pbkdf2, bcrypt, scrypt, or Argon2 instead
Better Password Hashing with crypto.pbkdf2
PBKDF2 ஐப் பயன்படுத்தி கடவுச்சொல் ஹாஷிங்கிற்கான மிகவும் பாதுகாப்பான அணுகுமுறை:
const crypto = require('crypto');
// Secure password hashing with PBKDF2
function hashPasswordSecure(password, salt, iterations = 100000) {
return new Promise((resolve, reject) => {
crypto.pbkdf2(
password,
salt,
iterations,
64, // Key length in bytes
'sha512', // Hash function
(err, derivedKey) => {
if (err) reject(err);
resolve(derivedKey.toString('hex'));
}
);
});
}
// Generate a random salt
function generateSalt() {
return crypto.randomBytes(16).toString('hex');
}
// Example usage
async function example() {
try {
const password = 'mySecurePassword123';
// For a new user, generate a salt and hash the password
const salt = generateSalt();
const iterations = 100000; // Higher is more secure but slower
console.log('Password:', password);
console.log('Salt:', salt);
console.log('Iterations:', iterations);
const hashedPassword = await hashPasswordSecure(password, salt, iterations);
console.log('Hashed Password:', hashedPassword);
// To verify a password
const verifyCorrect = await hashPasswordSecure(password, salt, iterations) === hashedPassword;
console.log('Verification with correct password:', verifyCorrect);
const verifyWrong = await hashPasswordSecure('wrongPassword', salt, iterations) === hashedPassword;
console.log('Verification with incorrect password:', verifyWrong);
// For storage, you would save: salt, iterations, and hashedPassword
} catch (error) {
console.error('Error:', error.message);
}
}
example();
Hash Collisions
இரண்டு வெவ்வேறு உள்ளீடுகள் ஒரே ஹாஷ் மதிப்பை உருவாக்கும் போது ஹாஷ் மோதல்கள் ஏற்படுகின்றன. ஹாஷ் மோதல்களைச் சரிபார்க்க இந்த எடுத்துக்காட்டு எவ்வாறு விளக்குகிறது:
const crypto = require('crypto');
// Function to generate random string
function generateRandomString(length) {
return crypto.randomBytes(length).toString('hex').substring(0, length);
}
// Function to find a partial hash collision (first few characters match)
function findPartialCollision(targetLength) {
const hashMap = new Map();
let attempts = 0;
console.log(`Searching for partial SHA-256 collisions (first ${targetLength} characters)...`);
while (true) {
attempts++;
// Generate a random input
const input = generateRandomString(8);
// Hash the input
const hash = crypto.createHash('sha256').update(input).digest('hex');
// Get the target portion of the hash
const targetPortion = hash.substring(0, targetLength);
// Check if we've seen this target portion before
if (hashMap.has(targetPortion)) {
const previousInput = hashMap.get(targetPortion);
console.log(`Found a collision after ${attempts} attempts!`);
console.log(`Input 1: "${previousInput}"`);
console.log(`Input 2: "${input}"`);
console.log(`SHA-256 (Input 1): ${crypto.createHash('sha256').update(previousInput).digest('hex')}`);
console.log(`SHA-256 (Input 2): ${hash}`);
console.log(`Both hashes start with: ${targetPortion}`);
return {
attempts,
input1: previousInput,
input2: input,
collidingPrefix: targetPortion
};
}
// Store this hash
hashMap.set(targetPortion, input);
// Show progress
if (attempts % 100000 === 0) {
console.log(`Checked ${attempts} values, ${hashMap.size} unique prefixes found...`);
}
// Safety limit
if (attempts >= 1000000) {
console.log('Reached attempt limit without finding a collision.');
break;
}
}
return { attempts, collisionFound: false };
}
// Find a collision for the first few characters (increase for more challenge)
findPartialCollision(4);
// Note: Finding a full collision for SHA-256 is computationally infeasible
// This example only demonstrates partial collisions
Incremental Hash Processing
அதிக அளவு தரவுகளுடன் பணிபுரியும் போது, அதை படிப்படியாக செயலாக்கலாம்:
const crypto = require('crypto');
// Simulate processing a large file in chunks
function processLargeDataIncrementally() {
// Create a hash object
const hash = crypto.createHash('sha256');
// Simulate reading data in chunks
const totalChunks = 10;
console.log(`Processing data in ${totalChunks} chunks...`);
for (let i = 0; i < totalChunks; i++) {
// In a real scenario, this would be data read from a file or stream
const chunk = `Chunk ${i + 1} of data with some random content: ${crypto.randomBytes(10).toString('hex')}`;
console.log(`Processing chunk ${i + 1}/${totalChunks}, size: ${chunk.length} bytes`);
// Update the hash with this chunk
hash.update(chunk);
}
// Calculate final hash after all chunks are processed
const finalHash = hash.digest('hex');
console.log('Final SHA-256 hash:', finalHash);
}
// Run the example
processLargeDataIncrementally();
Security Best Practices
ஹாஷ் செயல்பாடுகளைப் பயன்படுத்தும் போது, இந்த பாதுகாப்பு சிறந்த நடைமுறைகளைக் கவனியுங்கள்: