crypto.getDiffieHellman(groupName)
-
groupName<string> -
¥Returns: <DiffieHellmanGroup>
创建预定义的 DiffieHellmanGroup 密钥交换对象。DiffieHellmanGroup 的文档中列出了支持的组。
¥Creates a predefined DiffieHellmanGroup key exchange object. The
supported groups are listed in the documentation for DiffieHellmanGroup.
返回的对象模仿 crypto.createDiffieHellman() 创建的对象的接口,但不允许更改键(例如,使用 diffieHellman.setPublicKey())。使用这种方法的优点是双方不必事先生成或交换组模数,既节省了处理器时间又节省了通信时间。
¥The returned object mimics the interface of objects created by
crypto.createDiffieHellman(), but will not allow changing
the keys (with diffieHellman.setPublicKey(), for example). The
advantage of using this method is that the parties do not have to
generate nor exchange a group modulus beforehand, saving both processor
and communication time.
示例(获取共享密钥):
¥Example (obtaining a shared secret):
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);