Skip to content
Related Articles

Related Articles

Node.js diffieHellman.getPublicKey() Method

View Discussion
Improve Article
Save Article
  • Last Updated : 21 Jun, 2021

The diffieHellman.getPublicKey() method is an inbuilt application programming interface of class DiffieHellman within the crypto module which is used to return the public key of dh object. 

Syntax:

diffieHellman.getPublicKey([encoding])

Parameters: This method takes the encoding as a parameter.

Return Value: It returns the diffieHellman public key. If encoding is specified a string is returned, otherwise a Buffer is returned.

 

Example 1:

index.js




// Node.js program to demonstrate the
// diffieHellman.getPublicKey() Method
  
const crypto = require('crypto')
// Instance of  diffieHellman class
const dh = crypto.createDiffieHellman(512);
let publicKey = null
  
// Generate Keys
dh.generateKeys()
  
// Pass 'base64' as encoding, return String
publicKey = dh.getPublicKey('base64')
console.log('Public Key ( with encoding ): ', publicKey, '\n')
  
// Without encoding, return Buffer
publicKey = dh.getPublicKey()
console.log('Public Key ( without encoding ): ', publicKey, '\n')


Run the index.js file using the following command:

node index.js

Output:

Public Key ( with encoding ):  m/tuBRWr1mHOT4VzjRvcgZ+9Vtp925GS78Mdu
E7DfTxAm5750700EbWzVgLZWZ8N0AQoN1xQLlgDtBsdDo1wnQ== 

Public Key ( without encoding ):  <Buffer 9b fb 6e 05 15 ab d6 61 ce 
4f 85 73 8d 1b dc 81 9f bd 56 da 7d db 91 92 ef c3 1d b8 4e c3 7d 
3c 40 9b 9e f9 d3 bd 34 11 b5 b3 56 02 d9 59 9f 0d d0 04 ... >

Example 2:

index.js




// Node.js program to demonstrate the
// diffieHellman.getPublicKey() Method
  
const crypto = require('crypto')
  
// Instances of diffieHellman class
const alice = crypto.createDiffieHellman(512);
const bob = crypto.createDiffieHellman( 
    alice.getPrime(), alice.getGenerator() );
  
// Generate Keys
alice.generateKeys()
bob.generateKeys()
  
// Alice's publicKey
let aliceKey = alice.getPublicKey('base64')
  
// Bob's publicKey 
let bobKey = bob.getPublicKey('base64')
  
// Compute secret
let aliceSecret = alice.computeSecret(bobKey, 'base64', 'base64')
let bobSecret = bob.computeSecret(aliceKey, 'base64', 'base64')
  
if( aliceSecret === bobSecret )
    console.log('Symmetric key :', aliceSecret)


Run the index.js file using the following command:

node index.js

Output:

Symmetric key : VyeZOZm+hZQtZVp6HQdhWTkrHfZb8tR/yRiD99ljFWsnVHJNULdjnc
5oN5/mMSNqEWFqiJ0U14JYngJwXL008A==

Reference: https://nodejs.org/api/crypto.html#crypto_diffiehellman_getpublickey_encoding


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!