Node.js diffieHellman.getGenerator() Method

The diffieHellman.getGenerator() method is an inbuilt application programming interface of class diffieHellman within the crypto module which is used to get the generator value of DiffieHellman (dh) object. 

Syntax: 

diffieHellman.getGenerator([encoding])

Parameters: This method takes encoding as a parameter.

Return Value: It returns the DiffieHellman generator value in the specified encoding. If no encoding provided Buffer is returned else String is returned. 

 

Example 1: 

index.js




// Node.js program to demonstrate the
// diffieHellman.getGenerator() method
  
// Destructure createDiffieHellman method from crypto
const { createDiffieHellman } = require('crypto');
  
// Instances of the DiffieHellman class
const dh = createDiffieHellman(512);
  
// Generate dh's Generator
  
// No encoding specified
// Return Buffer
let dhGenerator = dh.getGenerator()
console.log('\nIs Buffer return ( encoding not specified ) : ' +
    Buffer.isBuffer(dhGenerator)) // true
console.log('Return value :')
console.log(dhGenerator)
  
// Encoding specified 
// Return String
dhGenerator = dh.getGenerator('base64')
console.log('\nIs Buffer return ( encoding specified ): ' +
    Buffer.isBuffer(dhGenerator)) // true
console.log('Return value :')
console.log(dhGenerator)


Run the index.js file using the following command:

node index.js

Output:

Is Buffer return ( encoding not specified ) : true
Return value :
<Buffer 02>

Is Buffer return ( encoding specified ): false
Return value :
Ag==

Example 2: 

index.js




// Node.js program to demonstrate the
// diffieHellman.getGenerator() method
  
// Destructure createDiffieHellman method from crypto
const { createDiffieHellman } = require('crypto');
  
// Generate Alice's keys...
const alice = createDiffieHellman(512);
  
// Generate Alices's Prime
const alicePrime = alice.getPrime();
  
// Generate Alice's Generator
const aliceGenerator =  alice.getGenerator()
  
// Generate Alice's Key
const aliceKey = alice.generateKeys();
  
// Generate Bob's keys...
const bob = createDiffieHellman( alicePrime, aliceGenerator );
  
// Generate Bobs's Prime
const bobPrime = bob.getPrime();
  
// Generate Bob's Generator
const bobGenerator =  bob.getGenerator()
  
// Generate Bob's Key
const bobKey = bob.generateKeys();
  
// Exchange and generate the secret...
const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);
  
let isSymmetric = aliceSecret.toString('hex') == bobSecret.toString('hex')
  
console.log( `Is Symmetric key generation 
              successful : ${ isSymmetric }` ); // true


Run the index.js file using the following command:

node index.js

Output:

Is Symmetric key generation successful : true

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



Contact Us