Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phương thức crypto.getDiffieHellman() trong Node.js

Mô tả

Phương thức crypto.createDiffieHellmanGroup() dùng để tạo đối tượng trao đổi khóa DiffieHellmanGroup xác định trước. Một số DiffieHellmanGroups được hỗ trợ: modp1, modp2, modp5, modp14, modp16, modp17, v.v. Lợi ích của phương thức này là các bên không cần sinh hoặc trao đổi group modulus, tiết kiệm thời gian xử lý.

Cú pháp

crypto.getDiffieHelmmanGroup(groupName)

Tham số

  • groupName – Nhận đầu vào cho tên group. Kiểu đầu vào là 'string'.

Ví dụ

Tạo file tên getdiffieHellman.js và sao chép đoạn mã dưới. Sau khi tạo file, dùng lệnh sau để chạy:

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(); // Getting 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ụ khác

Xem thêm một ví dụ nữa.

// 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(); // Getting 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. (/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)