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:
javascript
// Node.js program to demonstrate the// crypto.createDiffieHellman() method// Including crypto moduleconst crypto = require('crypto');// Creating DiffieHellman with primeconst alice = crypto.createDiffieHellman(20);// Generate keysalice.generateKeys();// Creating DiffieHellman to get// prime and generatorconst bob= crypto.createDiffieHellman( alice.getPrime(), alice.getGenerator());bob.generateKeys();// Prints prime and generator for// Alice with encodingconsole.log("Alice prime (p):", alice.getPrime().toString('hex'), "\nAlice generator (G):", alice.getGenerator().toString('hex')); |
Output:
Alice prime (p): 0a134b Alice generator (G): 02
Example 2:
javascript
// Node.js program to demonstrate the// crypto.createDiffieHellman() method// Including crypto moduleconst crypto = require('crypto');// Creating DiffieHellman with primeconst k = crypto.createDiffieHellman(30);// Accessing prime valueconst p = k.getPrime();// Accessing generator valueconst g = k.getGenerator();// Prints prime valueconsole.log(p);// Prints generator valueconsole.log(g); |
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


