เมธอด crypto.getDiffieHellman() สร้าง DiffieHellmanGroup key exchange object ที่กำหนดไว้ล่วงหน้า (pre-determined) เช่น modp1, modp2, modp5, modp14, modp16, modp17 เป็นต้น ข้อดีคือไม่ต้องสร้างหรือแลกเปลี่ยน group modulus เอง ประหยัดเวลาประมวลผล
ไวยากรณ์
crypto.getDiffieHellman(groupName)
พารามิเตอร์
- groupName – ชื่อกลุ่ม (string)
ตัวอย่าง: กลุ่ม modp1 เดียวกัน (สร้าง shared secret ได้)
const crypto = require('crypto');
const server = crypto.getDiffieHellman('modp1');
const client = crypto.getDiffieHellman('modp1');
server.generateKeys();
client.generateKeys();
const serverSecret = server.computeSecret(client.getPublicKey(), null, 'hex');
const clientSecret = client.computeSecret(server.getPublicKey(), null, 'hex');
console.log(serverSecret === clientSecret); // true
ผลลัพธ์
true
ตัวอย่าง: กลุ่มต่างกัน (modp17 vs modp14) – จะเกิด error
const dh1 = crypto.getDiffieHellman('modp17');
const dh2 = crypto.getDiffieHellman('modp14');
dh1.generateKeys();
dh2.generateKeys();
const dh1Key = dh1.computeSecret(dh2.getPublicKey(), null, 'hex');
const dh2Key = dh2.computeSecret(dh1.getPublicKey(), null, 'hex');
console.log(dh1Key === dh2Key); // Error: Supplied key is too large
ผลลัพธ์
Error: Supplied key is too large
at DiffieHellmanGroup.dhComputeSecret ...
กลุ่มต่างกันไม่สามารถคำนวณ shared secret ร่วมกันได้