Cipher ma’lumotnomasi


ULASHISH

Shifrlash obyekti

Cipher klassi Node.js crypto modulining bir qismidir. Turli xil algoritmlar yordamida ma’lumotlarni shifrlash usulini taqdim etadi. Shifrlash misollari crypto.createCipheriv() usuli yordamida yaratiladi.

Eslatma: crypto.createCipher() usuli Node.js v10.0.0 dan beri xavfsizlik muammolari tufayli eskirgan. Buning o‘rniga har doim crypto.createCipheriv() dan foydalaning, bu aniq ishga tushirish vektorini (IV) talab qiladi.

Kripto modulini import qilish

// Import the crypto module
const crypto = require('crypto');

// Create a cipher with createCipheriv
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32); // 32 bytes for AES-256
const iv = crypto.randomBytes(16); // 16 bytes for AES
const cipher = crypto.createCipheriv(algorithm, key, iv);

Shifrlash usullari

Metod Tavsif
cipher.update(data[, inputEncoding][, outputEncoding]) Shifrni data bilan yangilaydi. Agar inputEncoding berilgan bo‘lsa, data belgilangan kodlashdan foydalanadigan stringdir. Agar outputEncoding belgilangan bo‘lsa, qaytarilgan qiymat belgilangan kodlashdan foydalangan holda string bo‘ladi. Aks holda, buffer qaytariladi.
cipher.final([outputEncoding]) Qolgan shifrlangan tarkibni qaytaradi. Agar outputEncoding belgilansa, string qaytariladi; aks holda buffer qaytariladi.
cipher.setAAD(buffer[, options]) AEAD algoritmidan (masalan, GCM yoki CCM) foydalanilganda qo‘shimcha autentifikatsiyalangan ma’lumotlarni (AAD) o‘rnatadi.
cipher.getAuthTag() AEAD algoritmidan foydalanganda, bu usul autentifikatsiya tegini o‘z ichiga olgan Buferni qaytaradi.
cipher.setAutoPadding([autoPadding]) autoPadding true bo‘lganda (standart holatda), to‘ldirish (padding) qo‘llaniladi. Ma’lumotlar qo‘lda to‘ldirilgan bo‘lsa, uni o‘chirib qo‘ying.


Asosiy shifrlash misoli

Quyidagi misol AES-256-CBC algoritmi yordamida ma’lumotlarni shifrlashni ko‘rsatadi:

const crypto = require('crypto');

// Generate encryption key and initialization vector
// In a real application, you would securely store and retrieve these values
const key = crypto.randomBytes(32); // Key for AES-256 (32 bytes)
const iv = crypto.randomBytes(16); // IV for AES (16 bytes)

// Create a cipher
const algorithm = 'aes-256-cbc';
const cipher = crypto.createCipheriv(algorithm, key, iv);

// Data to encrypt
const plainText = 'This is a secret message';

// Encrypt the data
let encrypted = cipher.update(plainText, 'utf8', 'hex');
encrypted += cipher.final('hex');

console.log('Original Text:', plainText);
console.log('Encrypted Text:', encrypted);
console.log('Key (hex):', key.toString('hex'));
console.log('IV (hex):', iv.toString('hex'));

// The encrypted message, key, and IV would be needed for decryption
O‘zingiz sinab ko‘ring »

Turli xil algoritmlar bilan shifrlash

Node.js ko‘plab shifrlash algoritmlarini qo‘llab-quvvatlaydi. Turli xillardan qanday foydalanish kerak:

const crypto = require('crypto');

// The data to encrypt
const plainText = 'Hello, this is a test message';

// Function to encrypt data with different algorithms
function encryptWithAlgorithm(algorithm, keySize, ivSize, plainText) {
  // Generate key and IV
  const key = crypto.randomBytes(keySize);
  const iv = crypto.randomBytes(ivSize);
  
  // Create cipher
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  
  // Encrypt data
  let encrypted = cipher.update(plainText, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  
  return {
    algorithm,
    encrypted,
    key: key.toString('hex'),
    iv: iv.toString('hex')
  };
}

// Test different algorithms
const algorithms = [
  { name: 'aes-128-cbc', keySize: 16, ivSize: 16 },
  { name: 'aes-192-cbc', keySize: 24, ivSize: 16 },
  { name: 'aes-256-cbc', keySize: 32, ivSize: 16 },
  { name: 'aes-256-gcm', keySize: 32, ivSize: 16 }
];

algorithms.forEach(algo => {
  try {
    const result = encryptWithAlgorithm(algo.name, algo.keySize, algo.ivSize, plainText);
    console.log(`Encrypted with ${result.algorithm}: ${result.encrypted}`);
  } catch (error) {
    console.error(`Error with ${algo.name}: ${error.message}`);
  }
});
O‘zingiz sinab ko‘ring »

Ikkilik ma’lumotlarni shifrlash

Ikkilik ma’lumotlarni, shuningdek matnni shifrlashingiz mumkin:

const crypto = require('crypto');
const fs = require('fs');

// Generate key and IV
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

// Create read and write streams
const readStream = fs.createReadStream('input.jpg');
const writeStream = fs.createWriteStream('encrypted.jpg.enc');

// Create cipher stream
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);

// Encrypt the file
readStream
  .pipe(cipher)
  .pipe(writeStream);

// Save the key and IV for decryption
fs.writeFileSync('encryption_key.txt', key.toString('hex'));
fs.writeFileSync('encryption_iv.txt', iv.toString('hex'));

writeStream.on('finish', () => {
  console.log('File encryption completed');
});
Misolni ishga tushirish »

AEAD shifrlashdan foydalanish

Bog‘langan ma’lumotlar bilan tasdiqlangan shifrlash (AEAD) ham maxfiylik, ham ma’lumotlar yaxlitligini ta’minlaydi:

const crypto = require('crypto');

// Data to encrypt
const plainText = 'Secret message';
const associatedData = 'Additional data to authenticate';

// Generate key and IV (nonce)
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(12); // 12 bytes (96 bits) is recommended for GCM

// Create cipher using AES-GCM (an AEAD algorithm)
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);

// Set the Additional Authenticated Data (AAD)
cipher.setAAD(Buffer.from(associatedData));

// Encrypt the data
let encrypted = cipher.update(plainText, 'utf8', 'hex');
encrypted += cipher.final('hex');

// Get the authentication tag
const authTag = cipher.getAuthTag();

console.log('Encrypted Text:', encrypted);
console.log('Auth Tag (hex):', authTag.toString('hex'));
console.log('Key (hex):', key.toString('hex'));
console.log('IV (hex):', iv.toString('hex'));
console.log('Associated Data:', associatedData);

// All this information is needed for decryption and verification
Misolni ishga tushirish »

Qo‘lda to‘ldirishni boshqarish

To‘ldirish harakatini qo‘lda boshqarishingiz mumkin:

const crypto = require('crypto');

// Generate key and IV
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

// Data to encrypt
const plainText = 'This is a test message';

// Function to encrypt with different padding options
function encryptWithPadding(usePadding) {
  // Create cipher
  const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
  
  // Set padding option
  cipher.setAutoPadding(usePadding);
  
  try {
    // Encrypt data
    let encrypted = cipher.update(plainText, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return encrypted;
  } catch (error) {
    return `Error: ${error.message}`;
  }
}

// With default padding (true)
console.log('With padding:', encryptWithPadding(true));

// Without padding
// This will likely fail unless data length is a multiple of the block size
console.log('Without padding:', encryptWithPadding(false));

// Example with manual padding to block size (16 bytes for AES)
function manualPadding(text) {
  const blockSize = 16;
  const padLength = blockSize - (text.length % blockSize);
  return text + '\0'.repeat(padLength);
}

// Create cipher without auto padding
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
cipher.setAutoPadding(false);

// Manually pad the data
const paddedText = manualPadding(plainText);
console.log('Original length:', plainText.length);
console.log('Padded length:', paddedText.length);

// Encrypt manually padded data
let encrypted = cipher.update(paddedText, 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log('With manual padding:', encrypted);
Misolni ishga tushirish »

To‘liq shifrlash/deshifrlash misoli

Mana shifrlash va parolni hal qilishni ko‘rsatadigan to‘liq misol:

const crypto = require('crypto');

// The message to encrypt
const message = 'This is a secret message that needs to be encrypted';

// Generate encryption key and IV
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

// Encryption function
function encrypt(text) {
  // Create cipher
  const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
  
  // Encrypt data
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  
  return encrypted;
}

// Decryption function (using the Decipher class)
function decrypt(encryptedText) {
  // Create decipher with the same key and IV
  const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
  
  // Decrypt data
  let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  
  return decrypted;
}

// Encrypt the message
const encryptedMessage = encrypt(message);
console.log('Original Message:', message);
console.log('Encrypted Message:', encryptedMessage);

// Decrypt the message
const decryptedMessage = decrypt(encryptedMessage);
console.log('Decrypted Message:', decryptedMessage);

// Verify the result
console.log('Decryption successful:', message === decryptedMessage);
Misolni ishga tushirish »

Parol bilan shifrlash

Ko‘pgina ilovalar uchun paroldan shifrlash kalitini olishni xohlashingiz mumkin:

const crypto = require('crypto');

// Password and salt
const password = 'mysecretpassword';
const salt = crypto.randomBytes(16);

// Generate a key from the password
function getKeyFromPassword(password, salt) {
  // Use PBKDF2 to derive a key from the password
  return crypto.pbkdf2Sync(password, salt, 100000, 32, 'sha256');
}

// Password-based encryption
function encryptWithPassword(text, password) {
  // Generate key from password
  const key = getKeyFromPassword(password, salt);
  
  // Generate IV
  const iv = crypto.randomBytes(16);
  
  // Create cipher
  const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
  
  // Encrypt data
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  
  // Return encrypted data and IV (we'll need both for decryption)
  return {
    iv: iv.toString('hex'),
    salt: salt.toString('hex'),
    encryptedData: encrypted
  };
}

// Password-based decryption
function decryptWithPassword(encryptedInfo, password) {
  // Get the key from the password
  const key = getKeyFromPassword(
    password,
    Buffer.from(encryptedInfo.salt, 'hex')
  );
  
  // Get the IV from encryptedInfo
  const iv = Buffer.from(encryptedInfo.iv, 'hex');
  
  // Create decipher
  const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
  
  // Decrypt data
  let decrypted = decipher.update(encryptedInfo.encryptedData, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  
  return decrypted;
}

// Test encryption with password
const message = 'Secret message protected by a password';
const encryptedInfo = encryptWithPassword(message, password);

console.log('Encrypted:', encryptedInfo);

// Test decryption with password
const decryptedMessage = decryptWithPassword(encryptedInfo, password);
console.log('Decrypted:', decryptedMessage);

// Try with wrong password
try {
  const wrongPassword = 'wrongpassword';
  const failedDecryption = decryptWithPassword(encryptedInfo, wrongPassword);
  console.log('Decrypted with wrong password:', failedDecryption);
} catch (error) {
  console.log('Decryption failed with wrong password:', error.message);
}
Misolni ishga tushirish »

Qo‘llab-quvvatlanadigan shifrlash algoritmlari

Node.js ko‘plab shifrlash algoritmlarini qo‘llab-quvvatlaydi. Siz barcha qo‘llab-quvvatlanadigan algoritmlar ro‘yxatini olishingiz mumkin:

const crypto = require('crypto');

// Get all supported cipher algorithms
console.log(crypto.getCiphers());
Misolni ishga tushirish »

Umumiy algoritmlarga quyidagilar kiradi:

Algoritm Key Size (bytes) IV Size (bytes) Tavsif
aes-128-cbc 16 16 CBC rejimida 128 bitli kalit bilan AES
aes-192-cbc 24 16 CBC rejimida 192 bitli kalit bilan AES
aes-256-cbc 32 16 CBC rejimida 256 bitli kalit bilan AES
aes-128-gcm 16 12 GCM rejimida 128 bitli kalitli AES (AEAD)
aes-256-gcm 32 12 GCM rejimida 256 bitli kalitli AES (AEAD)
chacha20-poly1305 32 12 ChaCha20-Poly1305 (AEAD)

Xavfsizlik bo‘yicha eng yaxshi amaliyotlar

  • Eskirgan createCipher() o‘rniga createCipheriv() dan foydalaning : Bu IVni aniq taqdim etishingizni ta’minlaydi.
  • Xavfsiz tasodifiy kalitlar va IV-larni yarating: Ushbu qiymatlarni yaratish uchun har doim crypto.randomBytes() dan foydalaning.
  • Hech qachon bir xil kalit bilan IV-ni qayta ishlatmang: Bu shifrlashni sezilarli darajada zaiflashtirishi mumkin.
  • Autentifikatsiya qilingan shifrlashni (AEAD) afzal ko‘ring: AES-GCM yoki ChaCha20-Poly1305 kabi algoritmlar ham maxfiylik, ham yaxlitlikni ta’minlaydi.
  • Kalitlarni xavfsiz saqlash: Ilova kodingizdagi kalitlarni hech qachon qattiq kodlamang.
  • Kalitlarni hosil qilish funksiyalaridan foydalaning: Parollardan kalitlarni olishda tegishli parametrlarga ega PBKDF2, Scrypt yoki Argon2 dan foydalaning.
  • Node.js versiyasini yangilab turing: Kriptografik zaifliklar xavfsizlik yangilanishlarida tuzatilgan.

W3Schools Pathfinder

Yutuqlaringizni kuzating – bu bepul!