Open In App

Node.js crypto.getDiffieHellman() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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:




// 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);


Output:

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

Example 2:




// 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);


Output:

true

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



Last Updated : 11 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads