crypto.createDiffieHellman(primeLength, [generator]) Method in Node.js


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

 Live Demo

// 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
ode>> node index.js DiffieHellman key is: BaRoaA==

Example

Let's take a look at one more example.

 Live Demo

// 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
ode>> node index.js DiffieHellman keys are: 1a21670d Public Key is: 1a21670d Private Key: 0d4a1a3c

Updated on: 20-May-2021

56 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements