crypto.createDiffieHellman() Method in Node.js

Node.jsJavascriptWeb DevelopmentFront End Technology

The above method creates a DiffieHellman key exchange object with the help of the supplied prime value and an optional specific generator. The generator argument can hold either a string, number or Buffer value. Default value for generator is 2.

Syntax

crypto.createDiffieHelmmanGroup(prime, [primeEncoding], [generator], [generatorEncoding]

Parameters

The above parameters are described as below −

  • prime – The number of prime bits that will be generated. Input value is of type number.

  • primeEncoding – This parameter defines the encoding of the prime string. Possible input types are: string, buffer, TypedArray and DataView.

  • generator – Generator for generating the exchange key object. Default value: 2.

  • generatorEncoding – This parameter defines the generator string encoding.

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

Program Code

// crypto.createDiffieHelmmanGroup(prime, [primeEncoding],
[generator],[generatorEncoding])
// Demo Example

// Importing the crypto module
const crypto = require('crypto');

// Initializing and defining the prime value
const server = crypto.createDiffieHellman(20);

// Generating keys
server.generateKeys();

// Creating keys using server prime and generator
const client= crypto.createDiffieHellman(
   server.getPrime(), server.getGenerator());

client.generateKeys();

// Printing the server and client values
console.log("Server prime: ", server.getPrime().toString('hex'), "\nServer generator: ", server.getGenerator().toString('hex'));

console.log("Client prime: ", client.getPrime().toString('hex'), "\nClient generator: ", client.getGenerator().toString('hex'));

Output

C:\home\node>> node index.js
Server prime: 0fed0b
Server generator: 02
Client prime: 0fed0b
Client generator: 02

Since the arguments passed for both server and client are same. Therefore, the keys generated are also same.

Example

Let's take a look at one more example.

// crypto.createDiffieHelmmanGroup(prime, [primeEncoding],
[generator],[generatorEncoding])
// Demo Example

// Importing the crypto module
const crypto = require('crypto');

// Initializing and defining the prime value
const val = crypto.createDiffieHellman(12);

// Printing prime value for abve DiffieHellman
console.log(val.getPrime());

// Printing the generator value
console.log(val.getGenerator())

Output

C:\home\node>> node index.js
<Buffer 0f 6b>
<Buffer 02>
raja
Published on 20-May-2021 11:44:23
Advertisements