Node.js – diffieHellman.getPublicKey() Method


The diffieHellman.getPublicKey() returns the Diffie-Hellman generated public key that is specified by the encoding passed. It will return a string in case the encoding is passed, else it will return a buffer.

Syntax

diffieHellman.getPublicKey([encoding])

Parameters

  • encoding – This parameter specifies the encoding of the return value.

Example 1

Create a file with the name "publicKey.js" and copy the following code snippet. After creating the file, use the command "node publicKey.js" to run this code.

// diffieHellman.getPublicKey() Demo Example

// Importing the crypto module
const crypto = require('crypto')

// Initializing the diffieHellman
const dh = crypto.createDiffieHellman(512);

// Taking default publicKey as null
let publicKey = null

// Generate Keys
dh.generateKeys()

// Getting string with base64 encoding
publicKey = dh.getPublicKey('base64')
console.log('Public Key (with base64 encoding): ', publicKey, '
') // Getting buffer without encoding publicKey = dh.getPublicKey() console.log('Public Key ( ithout encoding): ', publicKey, '
')

Output

Public Key (with base64 encoding): ZY0wKH6d7Te8OPeIgHr7OlwSiH8d7MLGya9wopMgt5/liiKwFTgXsGE/07BQ6u98kUJJbr8cRgtD02D2I21xsg==

Public Key ( ithout encoding): <Buffer 65 8d 30 28 7e 9d ed 37 bc 38 f7 88 80 7a fb 3a 5c 12 88 7f 1d ec c2 c6 c9 af 70 a2 93 20 b7 9f e5 8a 22 b0 15 38 17 b0 61 3f d3 b0 50 ea ef 7c 91 42 ... >

Example 2

Let’s take a look at one more example.

// diffieHellman.getPublicKey() Demo Example

// Importing the crypto module
const crypto = require('crypto')

// Initializing the diffieHellman
const a = crypto.createDiffieHellman(512);
const b = crypto.createDiffieHellman(
   a.getPrime(), a.getGenerator() );

// Generating Keys
a.generateKeys()
b.generateKeys()

// Generating public key for a
let keyA = a.getPublicKey('base64')

// Generating public key for b
let keyB = b.getPublicKey('base64')

// Computing secret
let secretA = a.computeSecret(keyB, 'base64', 'base64')
let secretB = b.computeSecret(keyA, 'base64', 'base64')

if(secretA === secretB)
   console.log('Symmetric key A:', secretA)
   console.log('Symmetric key B:', secretB)

Output

Symmetric key A: shrRZLrIF/Uz52T4XCjALAuRgJ+1luVSesG2Q4bhW2+59qcWu5SI8P3XjSUXRMIcvIGQc2gzv/ENirozxU+iwA==
Symmetric key B: shrRZLrIF/Uz52T4XCjALAuRgJ+1luVSesG2Q4bhW2+59qcWu5SI8P3XjSUXRMIcvIGQc2gzv/ENirozxU+iwA==

Updated on: 29-Oct-2021

206 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements