Node.js | crypto.createDiffieHellman(prime, primeEncoding, generator, generatorEncoding) Method

The crypto.createDiffieHellman() method is used to create a DiffieHellman key exchange object by using the stated prime and an optional specified generator.

Syntax:

crypto.createDiffieHellman( prime, primeEncoding,
                        generator, generatorEncoding )

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

  • prime: It can hold string, Buffer, TypedArray, or DataView type of elements.
  • primeEncoding: It is the encoding of the prime string and is of type string.
  • generator: It can hold number, string, Buffer, TypedArray, or DataView type of data. Its default value is 2.
  • generatorEncoding: It is the encoding of the generator string and returns string.

Return Value: It returns DiffieHellman key exchange object.

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



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the 
// crypto.createDiffieHellman() method
  
// Including crypto module
const crypto = require('crypto');
  
// Creating DiffieHellman with prime
const alice = crypto.createDiffieHellman(20);
  
// Generate keys
alice.generateKeys();
  
// Creating DiffieHellman to get
// prime and generator
const bob= crypto.createDiffieHellman(
      alice.getPrime(), alice.getGenerator());
bob.generateKeys();
  
// Prints prime and generator for
// Alice with encoding
console.log("Alice prime (p):",
    alice.getPrime().toString('hex'), 
    "\nAlice generator (G):"
    alice.getGenerator().toString('hex')
);

chevron_right


Output:

Alice prime (p): 0a134b
Alice generator (G): 02

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the 
// crypto.createDiffieHellman() method
  
// Including crypto module
const crypto = require('crypto');
  
// Creating DiffieHellman with prime
const k = crypto.createDiffieHellman(30);
  
// Accessing prime value
const p = k.getPrime();
  
// Acessing generator value
const g = k.getGenerator();
  
// Prints prime value
console.log(p);
  
// Prints generator value
console.log(g);

chevron_right


Output:

// Buffer 22 4a 58 5b
// Buffer 02

Therefore, both prime and generator returns buffer.

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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.