crypto.createDiffieHellman() Method in Node.js

The crypto.createDiffieHellman() method in Node.js creates a Diffie-Hellman key exchange object using a specified prime value and an optional generator. This method enables secure key exchange between two parties over an insecure channel.

Syntax

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

Parameters

  • prime - The prime number used for the Diffie-Hellman exchange. Can be a number (bit length) or Buffer/string containing the prime value.

  • primeEncoding - Optional encoding for the prime string. Accepts 'hex', 'base64', 'binary', etc.

  • generator - Generator value for the key exchange. Default is 2. Can be a number, string, or Buffer.

  • generatorEncoding - Optional encoding for the generator string when generator is a string.

Example 1: Basic Diffie-Hellman Key Exchange

// Importing the crypto module
const crypto = require('crypto');

// Create server Diffie-Hellman instance with 20-bit prime
const server = crypto.createDiffieHellman(20);

// Generate server keys
server.generateKeys();

// Create client using same prime and generator as server
const client = crypto.createDiffieHellman(
    server.getPrime(), 
    server.getGenerator()
);

// Generate client keys
client.generateKeys();

// Display prime and generator values
console.log("Server prime:", server.getPrime().toString('hex'));
console.log("Server generator:", server.getGenerator().toString('hex'));
console.log("Client prime:", client.getPrime().toString('hex')); 
console.log("Client generator:", client.getGenerator().toString('hex'));
Server prime: 0fed0b
Server generator: 02
Client prime: 0fed0b
Client generator: 02

Example 2: Accessing Prime and Generator

// Importing the crypto module
const crypto = require('crypto');

// Create Diffie-Hellman instance with 12-bit prime
const dh = crypto.createDiffieHellman(12);

// Get prime value as Buffer
console.log("Prime as Buffer:", dh.getPrime());

// Get generator value as Buffer  
console.log("Generator as Buffer:", dh.getGenerator());

// Convert to hex strings for readability
console.log("Prime (hex):", dh.getPrime().toString('hex'));
console.log("Generator (hex):", dh.getGenerator().toString('hex'));
Prime as Buffer: <Buffer 0f 6b>
Generator as Buffer: <Buffer 02>
Prime (hex): 0f6b
Generator (hex): 02

Key Points

  • Both parties must use the same prime and generator values
  • Prime bit length affects security - larger values are more secure
  • The default generator value is 2, which works for most use cases
  • Keys are generated using generateKeys() after creating the instance

Conclusion

The crypto.createDiffieHellman() method provides the foundation for secure key exchange protocols. Both parties must share the same prime and generator values to establish a shared secret key.

Updated on: 2026-03-15T23:19:00+05:30

431 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements