Hash ma’lumotnomasi
Xesh obyekti
Hash klassi Node.js crypto modulining bir qismidir. Bu ma’lumotlarning kriptografik xesh-dijestlarini yaratish usulini taqdim etadi. Xesh misollari crypto.createHash() usuli yordamida yaratiladi.
Xesh-funksiyalar - bu ixtiyoriy o‘lchamdagi ma’lumotlarni dayjest deb ataladigan qat’iy o‘lchamdagi qiymatga moslashtiradigan bir tomonlama funksiyalar. Ular tez hisoblash uchun mo‘ljallangan, ammo uni qaytarish deyarli mumkin emas.
Kripto modulini import qilish
// Import the crypto module
const crypto = require('crypto');
// Create a hash object
const hash = crypto.createHash('sha256');
Misolni ishga tushirish »
Xesh usullari
| Metod | Tavsif |
|---|---|
| hash.update(data[, inputEncoding]) | Xesh tarkibini berilgan data bilan yangilaydi. Agar inputEncoding ko‘rsatilgan bo‘lsa, data belgilangan kodlashdan foydalanadigan stringdir; aks holda, data buffer, TypedArray yoki DataView hisoblanadi. Ushbu metodni yangi ma’lumotlar bilan bir necha marta chaqirish mumkin. |
| hash.digest([encoding]) | hash.update() yordamida xeshga uzatilgan barcha ma’lumotlarning dayjestini hisoblaydi. Agar encoding berilsa, string qaytariladi; aks holda buffer qaytariladi. Ushbu usul chaqirilgandan so‘ng, Hash obyektini boshqa ishlatib bo‘lmaydi. |
| hash.copy() | Joriy Hash obyektining ichki holatining chuqur nusxasini o‘z ichiga olgan yangi Hash obyektini yaratadi. Bu bir xil qisman ma’lumotlarga asoslangan bir nechta xeshlarni yaratmoqchi bo‘lganingizda foydalidir. |
Qo‘llab-quvvatlanadigan hash algoritmlari
Node.js ko‘plab xesh algoritmlarini qo‘llab-quvvatlaydi. Siz barcha qo‘llab-quvvatlanadigan algoritmlar ro‘yxatini olishingiz mumkin:
const crypto = require('crypto');
// Get all supported hash algorithms
console.log(crypto.getHashes());
Misolni ishga tushirish »
Umumiy xesh algoritmlariga quyidagilar kiradi:
| Algoritm | Chiqish hajmi | Tavsif | Tavsiya etilgan foydalanish |
|---|---|---|---|
| md5 | 128 bits (16 bytes) | Tez, lekin kriptografik jihatdan buzilgan | Faqat xavfsizlik bilan bog‘liq bo‘lmagan maqsadlar uchun (masalan, nazorat yig‘indilari) |
| sha1 | 160 bits (20 bytes) | Tez, lekin kriptografik jihatdan buzilgan | Faqat xavfsizlik bo‘lmagan maqsadlar uchun |
| sha256 | 256 bits (32 bytes) | SHA-2 oilasining bir qismi | Umumiy kriptografik foydalanish |
| sha512 | 512 bits (64 bytes) | SHA-2 oilasining bir qismi | Yuqori darajadagi xavfsizlik dasturlari |
| sha3-256 | 256 bits (32 bytes) | SHA-3 oilasining bir qismi | Zamonaviy kriptografik ilovalar |
| sha3-512 | 512 bits (64 bytes) | SHA-3 oilasining bir qismi | Yuqori darajadagi xavfsiz zamonaviy ilovalar |
Asosiy xesh misoli
Quyidagi misol stringning xesh-dijestini qanday yaratishni ko‘rsatadi:
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);
Misolni ishga tushirish »
Turli xil xesh algoritmlarini solishtirish
Ushbu misol turli xil xesh algoritmlarini taqqoslaydi:
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('------------------------------------');
}
});
Misolni ishga tushirish »
Bir nechta yangilanishlar bilan xeshlash
Dijestni hisoblashdan oldin bir nechta ma’lumotlar bo‘laklari bilan xeshni yangilashingiz mumkin:
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);
Misolni ishga tushirish »
Turli kodlashlar bilan xesh
Xesh-dijestni turli xil kodlashlarda olishingiz mumkin:
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');
Misolni ishga tushirish »
Fayl xeshlash
Siz fayl mazmunini xeshlashingiz mumkin:
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);
});
Misolni ishga tushirish »
hash.copy()’dan foydalanish
hash.copy() usuli sizga xesh-obyektning nusxasini yaratishga imkon beradi:
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
Misolni ishga tushirish »
Xesh samaradorligini taqqoslash
Ushbu misol turli xil xesh algoritmlarining ishlashini taqqoslaydi:
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}`);
}
});
}
Misolni ishga tushirish »
Parolni xashing
Ogohlantirish: Quyidagi misolda umumiy maqsadli xesh funksiyalari bilan parol xeshlash ko‘rsatilgan. Parolni xavfsiz saqlash uchun bcrypt, scrypt yoki Argon2 kabi maxsus algoritmlardan foydalaning, ular parolni xeshlash uchun maxsus ishlab chiqilgan va tuz va ish omillarini o‘z ichiga oladi.
Ushbu misol parollarni tuz bilan qanday xeshlashni ko‘rsatadi:
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
Misolni ishga tushirish »
crypto.pbkdf2 yordamida parolni yaxshiroq xashing
PBKDF2 yordamida parolni xeshlash uchun xavfsizroq yondashuv:
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();
Misolni ishga tushirish »
Xesh to‘qnashuvlari
Ikki xil kirish bir xil xesh qiymatini hosil qilganda, xesh to‘qnashuvi sodir bo‘ladi. Ushbu misol hash to‘qnashuvlarini qanday tekshirishni ko‘rsatadi:
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
Misolni ishga tushirish »
Incremental hash ishlovi
Katta hajmdagi ma’lumotlar bilan ishlashda siz ularni bosqichma-bosqich qayta ishlashingiz mumkin:
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();
Misolni ishga tushirish »
Xavfsizlik bo‘yicha eng yaxshi amaliyotlar
Xesh-funksiyalardan foydalanganda xavfsizlikning eng yaxshi usullarini ko‘rib chiqing:
- Xavfsiz algoritmlarni tanlang: Xavfsizlik nuqtai nazaridan muhim ilovalar uchun SHA-256, SHA-512, SHA-3 yoki yangiroq xesh funksiyalaridan foydalaning. Xavfsizlik maqsadida MD5 va SHA-1 dan saqlaning.
- Maqsadga oid funksiyalardan foydalaning: Parolni xeshlash uchun umumiy maqsadli xesh funksiyalari o‘rniga bcrypt, scrypt yoki Argon2 kabi maxsus funksiyalardan foydalaning.
- Har doim parollar bilan tuzlardan foydalaning: Parol xeshlarini saqlashda har bir parol uchun har doim noyob tasodifiy tuzdan foydalaning.
- Xabar autentifikatsiyasi uchun HMAC-ni ko‘rib chiqing: Maxfiy kalit yordamida ma’lumotlar yaxlitligini tekshirishda oddiy xeshlar o‘rniga HMAC-dan foydalaning.
- Uzunlikni uzaytirish hujumlaridan xabardor bo‘ling: Ba’zi xesh-funksiyalar (SHA-256, SHA-512, lekin SHA-3 emas) xabar autentifikatsiyasi uchun sodda foydalanilganda, uzunlikni kengaytirish hujumlariga nisbatan zaifdir.
- Tobeliklarni yangilab turing: Kriptografik ilovalardagi xavfsizlik zaifliklari muntazam ravishda topiladi va tuzatiladi.
W3Schools Pathfinder
Yutuqlaringizni kuzating – bu bepul!
