Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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):
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==
Advertisements
