crypto.getDiffieHellman(groupName)
groupName<string>- 返回: <DiffieHellmanGroup>
创建预定义的 DiffieHellmanGroup 密钥交换对象。
支持的组是:'modp1'、'modp2'、'modp5'(在 RFC 2412 中定义,但请参阅注意事项)和 'modp14'、'modp15'、'modp16'、'modp17'、'modp18'(在 RFC 3526 中定义)。
返回的对象模仿 crypto.createDiffieHellman() 创建的对象的接口,但不允许更改键(例如,使用 diffieHellman.setPublicKey())。
使用这种方法的优点是双方不必事先生成或交换组模数,既节省了处理器时间又节省了通信时间。
示例(获取共享密钥):
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 和 bobSecret 应该是一样的 */
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 和 bobSecret 应该是一样的 */
console.log(aliceSecret === bobSecret);groupName<string>- Returns: <DiffieHellmanGroup>
Creates a predefined DiffieHellmanGroup key exchange object. The
supported groups are: 'modp1', 'modp2', 'modp5' (defined in
RFC 2412, but see Caveats) and 'modp14', 'modp15',
'modp16', 'modp17', 'modp18' (defined in RFC 3526). 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);