Crypto.createDiffieHellmanGroup () được sử dụng để tạo đối tượng trao đổi khóa DiffieHellmanGroup được xác định trước. Một số DiffieHellmanGroups được hỗ trợ là:modp1, modp2, modp5, modp 14, modp16, modp17, v.v. Lợi ích của việc sử dụng phương pháp này là các bên không cần tạo hoặc trao đổi mô-đun nhóm do đó tiết kiệm thời gian xử lý.
Cú pháp
crypto.getDiffieHelmmanGroup(groupName)
Tham số
Các thông số trên được mô tả như bên dưới -
-
groupName - Nó lấy đầu vào cho tên nhóm. Đầu vào thuộc loại 'string'.
Ví dụ
Tạo một tệp có tên - getdiffieHellman.js và sao chép đoạn mã bên dưới. Sau khi tạo tệp, sử dụng lệnh sau để chạy mã này như được hiển thị trong ví dụ bên dưới -
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); Đầu ra
C:\home\node>> node getDiffieHellman.js
DiffieHellmanGroup { _handle: { verifyError: [Getter] }, verifyError: 0 }
DiffieHellmanGroup { _handle: { verifyError: [Getter] }, verifyError: 0 }
true Ví dụ
Hãy xem thêm một ví dụ.
// 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); Đầu ra
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)