Node.js crypto.createDiffieHellman(primeLength, generator) 方法
crypto.createDiffieHellman() 方法用于创建 DiffieHellman 密钥交换对象。此外,在可选的特定数字生成器的帮助下创建primeLength位的素数。此外,如果未定义生成器,则使用值 2。
句法:
crypto.createDiffieHellman( primeLength, generator )
参数:此方法接受上面提到的两个参数,如下所述:
- primeLength:这个参数保存了一些primeLength。
- generator:它可以保存 number、 字符串、Buffer、TypedArray 或 DataView 类型的数据。它的默认值为 2。
返回值:返回 DiffieHellman 密钥交换对象。
下面的示例说明了在 Node.js 中使用crypto.createDiffieHellman() 方法:
示例 1:
// Node.js program to demonstrate the
// crypto.createDiffieHellman() method
// Includes crypto module
const crypto = require('crypto');
// Defining prime length
var prime_length = 60;
// Creating DiffieHellman keyexchange object
var diffHell = crypto.createDiffieHellman(prime_length);
// Displays keys which are encoded
console.log(diffHell.generateKeys('base64'));
输出:
CoWIWpiwbCE=
示例 2:
// Node.js program to demonstrate the
// crypto.createDiffieHellman() method
// Includes crypto module
const crypto = require('crypto');
// Defining prime length and generator
var prime_length = 21;
var generator = 12;
// Creating DiffieHellman keyexchange
// object with all its parameter
var diffHell = crypto.createDiffieHellman(
prime_length, generator);
// Displays keys which are encoded
console.log(diffHell.generateKeys('hex'));
// Displays public and private keys
console.log("Public Key : ",
diffHell.getPublicKey('base64'));
console.log("Private Key : ",
diffHell.getPrivateKey('base64'));
输出:
086501
Public Key : CGUB
Private Key : C1rL
参考: https://nodejs.org/api/crypto.html#crypto_crypto_creatediffiehellman_primelength_generator