Open In App

Node.js crypto.createDiffieHellman(primeLength, generator) Method

Last Updated : 31 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The crypto.createDiffieHellman() method is used to create a Diffie-Hellman 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 accepts two parameters as mentioned above and described below:

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

Return Value: It returns Diffie-Hellman key exchange object. 

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

Example 1: 

javascript




// Node.js program to demonstrate the    
// crypto.createDiffieHellman() method
 
// Includes crypto module
const crypto = require('crypto');
 
// Defining prime length
const prime_length = 60;
 
// Creating DiffieHellman keyexchange object
let diffHell = crypto.createDiffieHellman(prime_length);
 
// Displays keys which are encoded
console.log(diffHell.generateKeys('base64'));


Output:

CoWIWpiwbCE=

Example 2: 

javascript




// Node.js program to demonstrate the   
// crypto.createDiffieHellman() method
 
// Includes crypto module
const crypto = require('crypto');
 
// Defining prime length and generator
const prime_length = 21;
const generator = 12;
 
// Creating DiffieHellman keyexchange
// object with all its parameter
let 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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads