Node.js | crypto.getDiffieHellman() Method

The crypto.getDiffieHellman() method is used to create a predefined DiffieHellmanGroup key exchange object. Here, the favored groups are ‘modp1’, ‘modp2’, ‘modp5’, which are defined in RFC 2412 and ‘modp14’, ‘modp15’, ‘modp16’, ‘modp17’, ‘modp18’, defined in RFC 3526.

Syntax:

crypto.getDiffieHellman( groupName )

Parameters: This method accept single parameter groupName which is of type string.

Return Type: It returns DiffieHellmanGroup key exchange object.

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



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the 
// crypto.getDiffieHellman() method
  
// Including crypto module
const crypto = require('crypto');
  
// Calling getDiffieHellman method
// with its parameter groupName
const diffiehellmangrp = crypto.getDiffieHellman('modp14');
  
// Prints DiffieHellmanGroup key exchange object
console.log("Key exchange object : ", diffiehellmangrp);

chevron_right


Output:

Key exchange object :  DiffieHellmanGroup 
{ _handle: { verifyError: [Getter] }, verifyError: 0 }

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the 
// crypto.getDiffieHellman() method
   
// Including crypto module
const crypto = require('crypto');
   
// Calling two getDiffieHellman method
// with its parameter, groupName
const diffiehellmangrp1 = crypto.getDiffieHellman('modp14');
const diffiehellmangrp2 = crypto.getDiffieHellman('modp14');
   
// Generating keys
diffiehellmangrp1.generateKeys();
diffiehellmangrp2.generateKeys();
   
// Computing secret
const diffiehellmangrp1sc = diffiehellmangrp1
.computeSecret(diffiehellmangrp2.getPublicKey(), null, 'hex');
   
const diffiehellmangrp2sc = diffiehellmangrp2
.computeSecret(diffiehellmangrp1.getPublicKey(), null, 'hex');
   
// Checking if both the secrets are same or not
console.log(diffiehellmangrp1sc === diffiehellmangrp2sc);

chevron_right


Output:

true

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




My Personal Notes arrow_drop_up

Image
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.