Node.js diffieHellman.getPrime() Method
The diffieHellman.getPrime() method is an inbuilt application programming interface of class diffieHellman within the crypto module which is used to get the prime of DiffieHellman (dh) object.
Syntax:
diffieHellman.getPrime([encoding])
Parameters: This method takes encoding as a parameter.
Return Value: It returns the DiffieHellman prime value 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 dhPrime = dh.getPrime()
console.log('\nIs Buffer return ( encoding not specified ) : ' +
Buffer.isBuffer(dhPrime)) // true
console.log(' Return value : ')
console.log(dhPrime)
// Encoding specified
// Return String
dhPrime = dh.getPrime(' base64 ')
console.log(' \nIs Buffer return ( encoding specified ): ' +
Buffer.isBuffer(dhPrime)) // true
console.log(' Return value :')
console.log(dhPrime)
|
Run the index.js file using the following command:
node index.js
Output:
Is Buffer return ( encoding not specified ) : true
Return value :
<Buffer d9 10 5a 20 70 0e 9c 19 53 1d 74 bc 93 ac 9e 1d 00 65 cb 2b 7f
13 fd b5 67 cd ba 42 69 fc 2c 4c 44 5c 72 a7 45 26 2d d7 ff 2e
ee c1 a9 ad 21 bf c4 3a ... 14 more bytes>
Is Buffer return ( encoding specified ): false
Return value :
2RBaIHAOnBlTHXS8k6yeHQBlyyt/E/21Z826Qmn8LExEXHKnRSYt1/
8u7sGprSG/xDqF/zTVe5r9vQ+O0Q5PAw==
Example 2:
index.js
const { createDiffieHellman } = require( 'crypto' );
const alice = createDiffieHellman(512);
const alicePrime = alice.getPrime();
const aliceGenerator = alice.getGenerator()
const aliceKey = alice.generateKeys();
const bob = createDiffieHellman( alicePrime, aliceGenerator );
const bobPrime = bob.getPrime();
const bobGenerator = bob.getGenerator()
const bobKey = bob.generateKeys();
const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);
let isSymmetric =
aliceSecret.toString( 'hex' ) == bobSecret.toString( 'hex' )
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_getprime_encoding
Last Updated :
01 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...