Skip to content
Related Articles

Related Articles

Node.js | crypto.createDiffieHellman(primeLength, generator) Method
  • Last Updated : 26 Mar, 2020

The crypto.createDiffieHellman() method is used to create a DiffieHellman key exchange object. Also, creates prime of primeLength bits with the help of an optional specific numeric generator. Moreover, if the generator is not defined, then the value 2 is used.

Syntax:

crypto.createDiffieHellman( primeLength, generator )

Parameters: This method accept two parameters as mentioned above and described below:

  • primeLength: This parameter holds a number of primeLength.
  • generator: It can hold number, string, Buffer, TypedArray, or DataView type of data. Its default value is 2.

Return Value: It returns DiffieHellman key exchange object.

Below examples illustrate the use of crypto.createDiffieHellman() method in Node.js:



Example 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'));

Output:

CoWIWpiwbCE=

Example 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'));

Output:

086501
Public Key :  CGUB
Private Key :  C1rL

Reference: https://nodejs.org/api/crypto.html#crypto_crypto_creatediffiehellman_primelength_generator

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :