Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
crypto.createDiffieHellman(primeLength, [generator]) Method in Node.js
The crypto.createDiffieHellman(primeLength, [generator]) method creates a Diffie-Hellman key exchange object by generating a prime number of specified bit length. This is commonly used for secure key exchange between parties.
Syntax
crypto.createDiffieHellman(primeLength, [generator])
Parameters
The parameters are described below:
-
primeLength - The number of prime bits to generate. Must be a number.
-
generator - Optional generator for creating the exchange key object. Default value is 2.
Example 1: Basic Diffie-Hellman Key Generation
// Importing the crypto module
const crypto = require('crypto');
// Initializing the prime length
var primeLength = 29;
// Creating DiffieHellman key exchange object
var exchangeKey = crypto.createDiffieHellman(primeLength);
// Generating and printing the exchange key
console.log("DiffieHellman key is: " + exchangeKey.generateKeys('base64'));
DiffieHellman key is: BaRoaA==
Example 2: Using Custom Generator
// Importing the crypto module
const crypto = require('crypto');
// Initializing parameters
var primeLength = 29;
var generator = 3; // Custom generator (default is 2)
// Creating DiffieHellman key exchange object
var exchangeKey = crypto.createDiffieHellman(primeLength, generator);
// Generating keys
console.log("DiffieHellman keys are: " + exchangeKey.generateKeys('hex'));
// Displaying public and private keys separately
console.log("Public Key is:", exchangeKey.getPublicKey('hex'));
console.log("Private Key:", exchangeKey.getPrivateKey('hex'));
DiffieHellman keys are: 1a21670d Public Key is: 1a21670d Private Key: 0d4a1a3c
Key Methods
Once created, the Diffie-Hellman object provides several methods:
-
generateKeys(encoding)- Generates public/private key pair -
getPublicKey(encoding)- Returns the public key -
getPrivateKey(encoding)- Returns the private key -
computeSecret(otherPublicKey)- Computes shared secret
Conclusion
The crypto.createDiffieHellman() method enables secure key exchange by generating prime-based cryptographic keys. Use appropriate prime lengths (typically 1024+ bits) for production security.
Advertisements
