Open In App

Node.js diffieHellman.getPrivateKey() Method

Last Updated : 21 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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

Syntax:

diffieHellman.getPrivateKey([encoding])

Parameters: This method takes the encoding as a parameter.

Return Value: It returns the diffieHellman private 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.getPrivateKey() Method
  
const crypto = require( 'crypto' )
  
// Instance of  diffieHellman class
const dh = crypto.createDiffieHellman( 512 );
  
// Generate Keys
dh.generateKeys()
  
// Without encoding, return Buffer
let privateKey = dh.getPrivateKey()
let isBuffer = Buffer.isBuffer( privateKey )
  
console.log( 'Private Key : ', privateKey )
console.log( 'Return value is Buffer :', isBuffer )


Run the index.js file using the following command:

node index.js

Output:

Private Key :  <Buffer 4b 6a b1 c8 85 0e 94 dd d9 32 9d 59 a9 31 55 
b0 56 1c b2 6c 6d 37 90 17 15 72 4a a8 f4 01 45 7c 6f 27 2f 47 9d 
6d 5f c9 a6 e0 bb e7 0d 33 84 44 13 12 ... 14 more bytes>
Return value is Buffer : true

Example 2:

index.js




// Node.js program to demonstrate the
// diffieHellman.getPrivateKey() Method
  
const crypto = require( 'crypto' )
  
// Instance of  diffieHellman class
const dh = crypto.createDiffieHellman( 512 );
  
// Generate Keys
dh.generateKeys()
  
// Pass 'base64' as encoding, return String
let privateKey = dh.getPrivateKey( 'base64' )
  
console.log( 'Private Key : ', privateKey )
console.log( 'Return value is :', typeof privateKey )


Run the index.js file using the following command:

node index.js

Output:

Private Key :  fG5wx60xqnulSgUaRM3J2IsBrtWN5ySbrph8mdzakZ/bMTfG+K
SY1P58sENdPjBbmoXHGy7RAfwFPa0kHHgslA==
Return value is : string

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads