The crypto.createDiffieHellmanGroup(primeLength, [generator]) method is used for creating a key exchange object that generates a prime number of primeLength bits using a numeric generator. Default value is 2 when the generator is not defined.
Syntax
crypto.createDiffieHelmmanGroup(primeLength, [generator])
Parameters
The above parameters are described as below −
primeLength – The number of prime bits that will be generated. Input value is of type number.
generator – Generator for generating the exchange key object. Default value: 2.
Example
Create a file with name – index.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −
node index.js
index.js
// crypto.createDiffieHellman(primeLength, [generator]) Demo Example // Importing the crypto module const crypto = require('crypto'); // Initializing the variable primeLength var primeLength = 29; // Creating DiffieHellman keyexchange object var exchangeKey = crypto.createDiffieHellman(primeLength); // Printing the exchange keys console.log("DiffieHellman key is: " + exchangeKey.generateKeys('base64'));
Output
C:\home\node>> node index.js DiffieHellman key is: BaRoaA==
Example
Let's take a look at one more example.
// crypto.createDiffieHellman(primeLength, [generator]) Demo Example // Importing the crypto module const crypto = require('crypto'); // Initializing the variable primeLength var primeLength = 29; var generator = 3; //Default value is 2 // Creating DiffieHellman keyexchange object var exchangeKey = crypto.createDiffieHellman(primeLength, generator); // Printing the exchange keys console.log("DiffieHellman keys are: " + exchangeKey.generateKeys('hex')); // Displays public and private keys console.log("Public Key is: ", exchangeKey.getPublicKey('hex')); console.log("Private Key: ", exchangeKey.getPrivateKey('hex'));
Output
C:\home\node>> node index.js DiffieHellman keys are: 1a21670d Public Key is: 1a21670d Private Key: 0d4a1a3c