DiffieHellman ma’lumotnomasi


ULASHISH

DiffieHellman obyekti

DiffieHellman klassi Node.js crypto modulining bir qismidir. U Diffie-Hellman kalit almashish protokolini amalga oshiradi, bu ikki tomonga xavfsiz bo‘lmagan kanal orqali umumiy sirni ishonchli tarzda o‘rnatishga imkon beradi.

Kripto modulini import qilish

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

// Create a DiffieHellman instance
const dh = crypto.createDiffieHellman(2048); // 2048-bit prime length
Misolni ishga tushirish »

DiffieHellman usullari

Metod Tavsif
dh.generateKeys([encoding]) Shaxsiy va ommaviy Diffie-Hellman kalit qiymatlarini yaratadi. Agar encoding berilsa, string qaytariladi; aks holda buffer qaytariladi.
dh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding]) Boshqa tomonning ochiq kaliti yordamida umumiy sirni hisoblaydi. Agar inputEncoding berilgan bo‘lsa, otherPublicKey string bo‘lishi kutiladi; aks holda, Buffer, TypedArray yoki DataView. Agar outputEncoding berilsa, string qaytariladi; aks holda buffer qaytariladi.
dh.getPrime([encoding]) Diffie-Hellmanning asosiy qiymatini qaytaradi. Agar encoding berilsa, string qaytariladi; aks holda buffer qaytariladi.
dh.getGenerator([encoding]) Diffie-Hellman generatorini qaytaradi. Agar encoding berilsa, string qaytariladi; aks holda buffer qaytariladi.
dh.getPublicKey([encoding]) Diffie-Hellman ochiq kalitini qaytaradi. Agar encoding berilsa, string qaytariladi; aks holda buffer qaytariladi.
dh.getPrivateKey([encoding]) Diffie-Hellman shaxsiy kalitini qaytaradi. Agar encoding berilsa, string qaytariladi; aks holda buffer qaytariladi.
dh.setPublicKey(publicKey[, encoding]) Diffie-Hellman ochiq kalitini o‘rnatadi. Agar encoding berilgan bo‘lsa, publicKey string bo‘lishi kutiladi; aks holda, Buffer, TypedArray yoki DataView.
dh.setPrivateKey(privateKey[, encoding]) Diffie-Hellman shaxsiy kalitini o‘rnatadi. Agar encoding berilgan bo‘lsa, privateKey string bo‘lishi kutiladi; aks holda, Buffer, TypedArray yoki DataView.
dh.verifyError Boshlash yoki tekshirish paytida yuzaga kelgan xatolarni ko‘rsatuvchi bayroqlarning bit maydoni.


DiffieHellman misollarini yaratish

DiffieHellman misolini yaratishning bir necha yo‘li mavjud:

const crypto = require('crypto');

// Method 1: Generate a new DH group with specified prime length
const dh1 = crypto.createDiffieHellman(2048);
console.log('Generated prime length:', dh1.getPrime().length * 8, 'bits');

// Method 2: Create a DH group using a predefined prime
const prime = Buffer.from('prime-number-in-hex', 'hex');
const dh2 = crypto.createDiffieHellman(prime);

// Method 3: Create a DH group using a predefined prime and generator
const generator = Buffer.from('02', 'hex'); // Often 2, 5, or other small values
const dh3 = crypto.createDiffieHellman(prime, generator);

// Method 4: Using predefined groups with getDiffieHellman()
const predefinedGroupName = 'modp14'; // RFC 3526 2048-bit MODP Group
const dh4 = crypto.getDiffieHellman(predefinedGroupName);
Misolni ishga tushirish »

getDiffieHellman() usuli quyidagi oldindan belgilangan guruhlarni qo‘llab-quvvatlaydi:

Guruh nomi Tavsif Hajmi
modp1 RFC 2409 768 bitli MODP guruhi 768 bit
modp2 RFC 2409 1024 bitli MODP guruhi 1024 bit
modp5 RFC 3526 1536 bitli MODP guruhi 1536 bit
modp14 RFC 3526 2048 bitli MODP guruhi 2048 bit
modp15 RFC 3526 3072 bitli MODP guruhi 3072 bit
modp16 RFC 3526 4096 bitli MODP guruhi 4096 bit
modp17 RFC 3526 6144 bitli MODP guruhi 6144 bit
modp18 RFC 3526 8192 bitli MODP guruhi 8192 bit

Asosiy kalit almashinuvi misoli

Quyidagi misol ikki tomon (Elis va Bob) o‘rtasida asosiy Diffie-Hellman kalit almashinuvini ko‘rsatadi:

const crypto = require('crypto');

// Alice generates parameters and keys
console.log('Alice: Creating DiffieHellman instance...');
const alice = crypto.createDiffieHellman(2048);
const aliceKeys = alice.generateKeys();

// Bob also needs parameters from Alice
console.log('Alice: Sending parameters to Bob...');
const p = alice.getPrime();
const g = alice.getGenerator();

// Bob creates a DiffieHellman instance with the same parameters
console.log('Bob: Creating DiffieHellman instance with Alice\'s parameters...');
const bob = crypto.createDiffieHellman(p, g);
const bobKeys = bob.generateKeys();

// Exchange public keys (over an insecure channel)
console.log('Exchanging public keys...');
const alicePublicKey = alice.getPublicKey();
const bobPublicKey = bob.getPublicKey();

// Alice computes the shared secret using Bob's public key
console.log('Alice: Computing shared secret...');
const aliceSecret = alice.computeSecret(bobPublicKey);

// Bob computes the shared secret using Alice's public key
console.log('Bob: Computing shared secret...');
const bobSecret = bob.computeSecret(alicePublicKey);

// Both secrets should be the same
console.log('Alice\'s secret:', aliceSecret.toString('hex'));
console.log('Bob\'s secret:', bobSecret.toString('hex'));
console.log('Do they match?', aliceSecret.equals(bobSecret));

// This shared secret can now be used as a key for symmetric encryption
Misolni ishga tushirish »

Oldindan belgilangan guruhlardan foydalanish

Standartlashtirilgan ilovalar uchun oldindan belgilangan guruhlardan foydalanish muvofiqlikni ta’minlashi mumkin:

const crypto = require('crypto');

// Using the RFC 3526 MODP Group 14 (2048 bits)
console.log('Alice: Creating DiffieHellman using predefined group...');
const alice = crypto.getDiffieHellman('modp14');
alice.generateKeys();

// Bob also uses the same predefined group
console.log('Bob: Creating DiffieHellman using predefined group...');
const bob = crypto.getDiffieHellman('modp14');
bob.generateKeys();

// Exchange public keys (over an insecure channel)
console.log('Exchanging public keys...');
const alicePublicKey = alice.getPublicKey();
const bobPublicKey = bob.getPublicKey();

// Compute shared secrets
const aliceSecret = alice.computeSecret(bobPublicKey);
const bobSecret = bob.computeSecret(alicePublicKey);

// Verify that the shared secrets match
console.log('Do the shared secrets match?', aliceSecret.equals(bobSecret));

// Output information about the group
console.log('Group prime size:', alice.getPrime().length * 8, 'bits');
console.log('Generator value:', alice.getGenerator().toString('hex'));
Misolni ishga tushirish »

Diffie-Hellman shifrlash bilan

Ushbu misol AES shifrlash uchun umumiy kalitni yaratish uchun Diffie-Hellmandan foydalanishning to‘liq stsenariysini ko‘rsatadi:

const crypto = require('crypto');

// Create DiffieHellman instances for Alice and Bob
const alice = crypto.createDiffieHellman(2048);
alice.generateKeys();

// Bob uses Alice's parameters
const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());
bob.generateKeys();

// Exchange public keys
const alicePublicKey = alice.getPublicKey();
const bobPublicKey = bob.getPublicKey();

// Compute shared secrets
const aliceSecret = alice.computeSecret(bobPublicKey);
const bobSecret = bob.computeSecret(alicePublicKey);

// Use the shared secret as a key for encryption
// First, derive a suitable key using a hash function
function deriveKey(secret, salt, keyLength) {
  return crypto.pbkdf2Sync(secret, salt, 1000, keyLength, 'sha256');
}

// Alice sends an encrypted message to Bob
function encrypt(text, secret) {
  // Create a salt and derive a key
  const salt = crypto.randomBytes(16);
  const key = deriveKey(secret, salt, 32); // 32 bytes for AES-256
  const iv = crypto.randomBytes(16);
  
  // Encrypt the message
  const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  
  // Return everything Bob needs to decrypt
  return {
    salt: salt.toString('hex'),
    iv: iv.toString('hex'),
    encrypted
  };
}

// Bob decrypts the message from Alice
function decrypt(encryptedInfo, secret) {
  // Parse values
  const salt = Buffer.from(encryptedInfo.salt, 'hex');
  const iv = Buffer.from(encryptedInfo.iv, 'hex');
  const encrypted = encryptedInfo.encrypted;
  
  // Derive the same key
  const key = deriveKey(secret, salt, 32);
  
  // Decrypt the message
  const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
  let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  
  return decrypted;
}

// Alice encrypts a message using the shared secret
const message = 'Hello Bob, this is a secret message from Alice!';
console.log('Original message:', message);

const encryptedMessage = encrypt(message, aliceSecret);
console.log('Encrypted message:', encryptedMessage);

// Bob decrypts the message using his shared secret
const decryptedMessage = decrypt(encryptedMessage, bobSecret);
console.log('Decrypted message:', decryptedMessage);
Misolni ishga tushirish »

Maxsus parametrlar bilan ishlash

Diffie-Hellman uchun maxsus parametrlar kerak bo‘lganda:

const crypto = require('crypto');

// Custom prime and generator values
// These would normally be carefully chosen for security
const primeHex = `
  ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74
  020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f1437
  4fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed
  ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf05
  98da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb
  9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3b
  e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf695581718
  3995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff
`.replace(/\s+/g, '');

const prime = Buffer.from(primeHex, 'hex');
const generator = Buffer.from('02', 'hex');

// Create DiffieHellman with custom parameters
const dh = crypto.createDiffieHellman(prime, generator);

// Generate keys
dh.generateKeys();

// Verify the parameters
console.log('Using custom prime of length:', prime.length * 8, 'bits');
console.log('Generator:', generator.toString('hex'));

// Validation
console.log('Verify error code:', dh.verifyError);
if (dh.verifyError) {
  console.error('The parameters did not pass validation!');
} else {
  console.log('The parameters passed validation.');
}

// Output public and private keys
console.log('Public key length:', dh.getPublicKey().length * 8, 'bits');
console.log('Private key length:', dh.getPrivateKey().length * 8, 'bits');
Misolni ishga tushirish »

Maxsus kodlash bilan kalitlarni yaratish

DiffieHellman kalitlari bilan ishlashda kodlashni belgilashingiz mumkin:

const crypto = require('crypto');

// Create DiffieHellman instance
const dh = crypto.createDiffieHellman(1024);

// Generate keys
dh.generateKeys();

// Get keys and parameters with different encodings
console.log('With Buffer (default):');
console.log('  - Prime:', dh.getPrime());
console.log('  - Generator:', dh.getGenerator());
console.log('  - Public Key:', dh.getPublicKey());
console.log('  - Private Key:', dh.getPrivateKey());

console.log('\nWith hex encoding:');
console.log('  - Prime:', dh.getPrime('hex'));
console.log('  - Generator:', dh.getGenerator('hex'));
console.log('  - Public Key:', dh.getPublicKey('hex'));
console.log('  - Private Key:', dh.getPrivateKey('hex'));

console.log('\nWith base64 encoding:');
console.log('  - Prime:', dh.getPrime('base64'));
console.log('  - Generator:', dh.getGenerator('base64'));
console.log('  - Public Key:', dh.getPublicKey('base64'));
console.log('  - Private Key:', dh.getPrivateKey('base64'));

// Set keys using specific encoding
const newPublicKey = crypto.randomBytes(dh.getPrime().length - 10);
dh.setPublicKey(newPublicKey);
console.log('\nAfter setting new public key:');
console.log('  - Public Key (hex):', dh.getPublicKey('hex'));
Misolni ishga tushirish »

Xato bilan ishlash

Kriptografik operatsiyalar bilan ishlashda xatolarni bartaraf etish muhim ahamiyatga ega:

const crypto = require('crypto');

// Function to safely create DiffieHellman
function createDHSafely(options) {
  try {
    let dh;
    
    if (typeof options === 'number') {
      // Create with prime length
      dh = crypto.createDiffieHellman(options);
    } else if (options.group) {
      // Create with predefined group
      dh = crypto.getDiffieHellman(options.group);
    } else if (options.prime) {
      // Create with custom prime and optional generator
      const prime = Buffer.from(options.prime, options.encoding || 'hex');
      const generator = options.generator ?
        Buffer.from(options.generator, options.encoding || 'hex') :
        undefined;
      
      dh = generator ?
        crypto.createDiffieHellman(prime, generator) :
        crypto.createDiffieHellman(prime);
    } else {
      throw new Error('Invalid options for DiffieHellman creation');
    }
    
    // Check for errors
    if (dh.verifyError) {
      const errors = [];
      // Check specific error flags
      if (dh.verifyError & crypto.constants.DH_CHECK_P_NOT_SAFE_PRIME)
        errors.push('DH_CHECK_P_NOT_SAFE_PRIME');
      if (dh.verifyError & crypto.constants.DH_CHECK_P_NOT_PRIME)
        errors.push('DH_CHECK_P_NOT_PRIME');
      if (dh.verifyError & crypto.constants.DH_UNABLE_TO_CHECK_GENERATOR)
        errors.push('DH_UNABLE_TO_CHECK_GENERATOR');
      if (dh.verifyError & crypto.constants.DH_NOT_SUITABLE_GENERATOR)
        errors.push('DH_NOT_SUITABLE_GENERATOR');
      
      throw new Error(`DiffieHellman parameter validation failed: ${errors.join(', ')}`);
    }
    
    return dh;
  } catch (error) {
    console.error('Error creating DiffieHellman instance:', error.message);
    throw error;
  }
}

// Test with valid options
try {
  const dh1 = createDHSafely(2048);
  console.log('Successfully created DH with 2048-bit prime');
  
  const dh2 = createDHSafely({ group: 'modp14' });
  console.log('Successfully created DH with predefined group modp14');
} catch (error) {
  console.error('Error in valid tests:', error.message);
}

// Test with invalid options
try {
  // Invalid prime value
  const invalidPrime = '12345'; // Too short, not a prime
  const dh3 = createDHSafely({
    prime: invalidPrime,
    encoding: 'hex'
  });
} catch (error) {
  console.error('Expected error with invalid prime:', error.message);
}

try {
  // Invalid group name
  const dh4 = createDHSafely({ group: 'nonexistent-group' });
} catch (error) {
  console.error('Expected error with invalid group:', error.message);
}
Misolni ishga tushirish »

Xavfsizlik masalalari

Diffie-Hellman kalit almashinuvidan foydalanganda xavfsizlik bo‘yicha eng yaxshi amaliyotlarni ko‘rib chiqing:

  1. Tegishli kalit o‘lchamlaridan foydalaning: Zamonaviy ilovalar uchun kamida 2048-bitli asosiy qiymatlardan foydalaning.
  2. Tasdiqlangan guruhlardan foydalaning: Iloji bo‘lsa, RFClarda belgilangan standartlashtirilgan guruhlardan foydalaning.
  3. Shaxsiy kalitlarni himoya qiling: Hech qachon shaxsiy kalitlarni jurnallarda, debug chiqishida yoki mijoz kodida ko‘rsatmang.
  4. Autentifikatsiyani qo‘shish: Pure Diffie-Hellman o‘rtadagi odam hujumlariga qarshi himoyasiz. Raqamli imzolar bilan ECDHE kabi autentifikatsiya qilingan kalit almashish protokollaridan foydalanishni o‘ylab ko‘ring.
  5. Parametr tekshiruvini tekshirish: Parametrlarning haqiqiyligini tekshirish uchun har doim dh.verifyError belgilang.
  6. Efemer kalitlardan foydalaning: Har bir seans uchun yangi kalitlarni oldinga siljitish uchun yarating.
  7. Shifrlash kalitlarini to‘g‘ri oling: Umumiy sirdan bevosita shifrlash kaliti sifatida foydalanmang. HKDF yoki PBKDF2 kabi kalit hosil qilish funksiyasidan (KDF) foydalaning.

ECDH bilan solishtirish

Diffie-Hellman (DH) va Elliptic Curve Diffie-Hellman (ECDH) ikkalasi ham asosiy almashinuv protokollaridir, ammo ECDH afzalliklarni taqdim etadi:

Xususiyat DiffieHellman ECDH
Kalit hajmi Odatda 2048-4096 bit Odatda 256-384 bit
Ishlash Sekinroq, ko‘proq hisoblashni talab qiladi Tezroq, samaraliroq
Xavfsizlik darajasi 2048-bitli DH ≈ 112-bitli xavfsizlik 256-bitli ECDH ≈ 128-bitli xavfsizlik
Xotiradan foydalanish Yuqori Pastroq
Zamonaviy foydalanish Yangi dizaynlarda kamroq tarqalgan Yangi protokollarda keng tarqalgan

Ko‘pgina zamonaviy ilovalar uchun ECDH yaxshi ishlashi va kichikroq kalit o‘lchamlari tufayli afzallik beriladi.


W3Schools Pathfinder

Yutuqlaringizni kuzating – bu bepul!