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 module const crypto = require( 'crypto' ); // Creating DiffieHellman with prime const alice = crypto.createDiffieHellman(20); // Generate keys alice.generateKeys(); // Creating DiffieHellman to get // prime and generator const bob= crypto.createDiffieHellman( alice.getPrime(), alice.getGenerator()); bob.generateKeys(); // Prints prime and generator for // Alice with encoding console.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 module const crypto = require( 'crypto' ); // Creating DiffieHellman with prime const k = crypto.createDiffieHellman(30); // Accessing prime value const p = k.getPrime(); // Accessing generator value const g = k.getGenerator(); // Prints prime value console.log(p); // Prints generator value console.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
Please Login to comment...