Node.js - diffieHellman.getPrivateKey() Method

Node.jsServer Side ProgrammingProgramming

The diffieHellman.getPrivateKey() returns the Diffie-Hellman generated private key that is specified by the encoding passed. A string is returned in case if encoding is passed, else a buffer will be returned.

Syntax

diffieHellman.getPrivateKey( [encoding] )

where, encoding is the parameter that specifies the encoding of the return value.

Example 1

Create a file with the name "privateKey.js" and copy the following code snippet. After creating the file, use the command "node privateKey.js" to run this code as shown in the example below −

// diffieHellman.getPriateKey() Demo Example

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

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

// Generating Keys
dh.generateKeys()

// Getting buffer since encoding is not passed
let privateKey = dh.getPrivateKey()

// Checking if the key is a buffer
let isBuffer = Buffer.isBuffer( privateKey )

// Printing values
console.log( 'Private Key : ', privateKey )
console.log( 'Return value is Buffer :', isBuffer )

Output

C:\home\node>> node publicKey.js
Private Key : <Buffer 60 38 6a c8 ec 31 f1 4e b7 10 87 4b 09 48 dd 45 bf 65 99 9e 05 fe ab 7f 1e 27 ee b3 7c a8 98 30 18 ee 9e 77 e5 be 65 39 f7 fa e1 bd b3 ce 5f c7 99 8e ... >
Return value is Buffer : true

Example 2

Let's take a look at one more example −

// diffieHellman.getPriateKey() Demo Example

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

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

// Generating Keys
dh.generateKeys()

// Getting buffer since encoding is not passed
let privateKey = dh.getPrivateKey()

// Checking the key Type and printing values
console.log( 'Private Key : ', privateKey )
console.log( 'Return value is :', typeof privateKey )

Output

C:\home\node>> node computeSecret.js
Private Key : <Buffer 44 05 93 8c b5 98 78 57 db 36 5c 27 ef 83 37 cb 76 dc b1 60 d7 8c 3f cc 20 d2 5f b2 71 71 c8 53 a2 ba e2 a2 73 10 7f 2f 0c b3 23 f3 b2 45 0e cd d6 86 ... >
Return value is: object
raja
Published on 17-Jan-2022 12:04:20

Advertisements