Node.js diffieHellman.generateKeys() Method
Last Updated :
10 Jun, 2021
The diffieHellman.generateKeys() method is an inbuilt application programming interface of class DiffieHellman within the crypto module which is used to generate private and public key value of DiffieHellman (dh) object.
Syntax:
diffieHellman.generateKeys([encoding])
Parameters: This method takes encoding as a parameter.
Return Value: Returns the DiffieHellman public key in the specified encoding. If encoding is not provided Buffer is returned else String is returned.
Example 1:
index.js
const { createDiffieHellman } = require( 'crypto' );
const dh = createDiffieHellman(512);
let dhKey = dh.generateKeys()
console.log('\nIs Buffer return ( encoding not specified ) : ' +
Buffer.isBuffer( dhKey ) ) // true
console.log(' Return value : ')
console.log( dhKey )
// Encoding specified
// Return String
dhKey = dh.generateKeys(' base64 ')
console.log(' \nIs Buffer return ( encoding specified ): ' +
Buffer.isBuffer( dhKey ) ) // true
console.log(' Return value :')
console.log( dhKey )
|
Run the index.js file using the following command:
node index.js
Output:
Is Buffer return ( encoding not specified ) : true
Return value :
<Buffer 6d 17 8c ea 74 27 5b f4 86 f8 72 f9 73 93 19 8b 27 90 86 e7
d8 1b 1c 50 b2 65 9a 66 bc 2c 4d 49 f6 46 3e b5 1c 09 e5 ef 5c b9 8e
fc 65 95 aa 40 3a 6c ... 14 more bytes>
Is Buffer return ( encoding specified ): false
Return value :
bReM6nQnW/SG+HL5c5MZiyeQhufYGxxQsmWaZrwsTUn2Rj61HAnl71y5jvxllapAO
mwITlF8/1Z67Nt7Lc8tqA==
Example 2 :
index.js
const { createDiffieHellman } = require( 'crypto' );
const alice = createDiffieHellman(512);
const alicePrime = alice.getPrime();
const aliceGenerator = alice.getGenerator()
const aliceKey = alice.generateKeys( 'base64' );
const bob = createDiffieHellman( alicePrime, aliceGenerator );
const bobPrime = bob.getPrime();
const bobGenerator = bob.getGenerator()
const bobKey = bob.generateKeys( 'base64' );
const aliceSecret = alice.computeSecret(bobKey, 'base64' , 'base64' );
const bobSecret = bob.computeSecret(aliceKey, 'base64' , 'base64' );
let isSymmetric = aliceSecret == bobSecret
console.log( `Is Symmetric key generation successful : ${ isSymmetric }` );
|
Run the index.js file using the following command:
node index.js
Output:
Is Symmetric key generation successful : true
Reference: https://nodejs.org/api/crypto.html#crypto_diffiehellman_generatekeys_encoding
Share your thoughts in the comments
Please Login to comment...