當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js crypto.getDiffieHellman(groupName)用法及代碼示例

crypto.getDiffieHellman(groupName)

添加於:v0.7.5

參數

創建一個預定義的DiffieHellmanGroup key 交換對象。支持的組是:'modp1''modp2''modp5'(在 RFC 2412 中定義,但參見 Caveats)和 'modp14''modp15''modp16''modp17''modp18'(在 RFC 3526 中定義)。返回的對象模仿由 crypto.createDiffieHellman() 創建的對象的接口,但不允許更改鍵(例如,使用 diffieHellman.setPublicKey() )。使用這種方法的優點是雙方不必事先生成或交換組模數,從而節省了處理器和通信時間。

示例(獲取共享 key ):

const {
  getDiffieHellman
} = await import('node:crypto');
const alice = getDiffieHellman('modp14');
const bob = getDiffieHellman('modp14');

alice.generateKeys();
bob.generateKeys();

const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');

/* aliceSecret and bobSecret should be the same */
console.log(aliceSecret === bobSecret);const {
  getDiffieHellman,
} = require('node:crypto');

const alice = getDiffieHellman('modp14');
const bob = getDiffieHellman('modp14');

alice.generateKeys();
bob.generateKeys();

const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');

/* aliceSecret and bobSecret should be the same */
console.log(aliceSecret === bobSecret);

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 crypto.getDiffieHellman(groupName)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。