crypto.createDiffieHellmanGroup() ใช้สำหรับสร้างวัตถุการแลกเปลี่ยนคีย์ DiffieHellmanGroup ที่กำหนดไว้ล่วงหน้า DiffieHellmanGroups ที่รองรับได้แก่:modp1, modp2, modp5, modp 14, modp16, modp17 เป็นต้น ประโยชน์ของการใช้วิธีนี้คือฝ่ายต่างๆ ไม่จำเป็นต้องสร้างหรือแลกเปลี่ยนโมดูลัสของกลุ่มซึ่งจะช่วยประหยัดเวลาในการประมวลผล
ไวยากรณ์
crypto.getDiffieHelmmanGroup(groupName)
พารามิเตอร์
พารามิเตอร์ข้างต้นอธิบายไว้ด้านล่าง −
-
ชื่อกลุ่ม – ใช้อินพุตสำหรับชื่อกลุ่ม อินพุตเป็นประเภท 'string'
ตัวอย่าง
สร้างไฟล์ที่มีชื่อ – getdiffieHellman.js และคัดลอกข้อมูลโค้ดด้านล่าง หลังจากสร้างไฟล์แล้ว ให้ใช้คำสั่งต่อไปนี้เพื่อเรียกใช้โค้ดนี้ดังแสดงในตัวอย่างด้านล่าง −
node getDiffieHellman.js
getdiffieHellman.js
// crypto.getDiffieHellman() Demo Example
// Importing the crypto module
const crypto = require('crypto');
const server = crypto.getDiffieHellman('modp1');
const client = crypto.getDiffieHellman('modp1');
// Printing DiffieHellman values
console.log(server);
console.log(client);
// Generating public and private keys
server.generateKeys();
client.generateKeys();
// Gettong public key
const serverSecret = server.computeSecret(client.getPublicKey(), null, 'hex');
const clientSecret = client.computeSecret(server.getPublicKey(), null, 'hex');
/* aliceSecret and bobSecret should be the same */
console.log(serverSecret === clientSecret); ผลลัพธ์
C:\home\node>> node getDiffieHellman.js
DiffieHellmanGroup { _handle: { verifyError: [Getter] }, verifyError: 0 }
DiffieHellmanGroup { _handle: { verifyError: [Getter] }, verifyError: 0 }
true ตัวอย่าง
ลองดูอีกตัวอย่างหนึ่ง
// crypto.getDiffieHellman() Demo Example
// Importing the crypto module
const crypto = require('crypto');
const dh1 = crypto.getDiffieHellman('modp17');
const dh2 = crypto.getDiffieHellman('modp14');
// Generating public and private keys
dh1.generateKeys();
dh2.generateKeys();
// Gettong public key
const dh1Key = dh1.computeSecret(dh2.getPublicKey(), null, 'hex');
const dh2Key = dh2.computeSecret(dh1.getPublicKey(), null, 'hex');
/* aliceSecret and bobSecret should be the same */
console.log(dh1Key === dh2Key); ผลลัพธ์
C:\home\node>> node getDiffieHellman.js internal/crypto/diffiehellman.js:102 const ret = this._handle.computeSecret(toBuf(key, inEnc)); ^ Error: Supplied key is too large at DiffieHellmanGroup.dhComputeSecret [as computeSecret] (internal/crypto/diffiehellman.js:102:28) at Object.<anonymous> (/home/node/test/getDiffieHellman .js:15:20) at Module._compile (internal/modules/cjs/loader.js:778:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function.Module._load (internal/modules/cjs/loader.js:585:3) at Function.Module.runMain (internal/modules/cjs/loader.js:831:12) at startup (internal/bootstrap/node.js:283:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)