Skip to content
Related Articles

Related Articles

Node.js diffieHellman.setPrivateKey() Method

Improve Article
Save Article
  • Last Updated : 28 Jun, 2021
Improve Article
Save Article

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

Syntax:

diffieHellman.setPrivateKey(privateKey[, encoding])

Parameters: This method accepts the following two parameters:

  • privateKey: It is used to denote the private Key.
  • encoding: It is used to denote the encoding of privateKey. If encoding is provided privateKey expected to be String otherwise Buffer, TypedArray, or DataView.

 

Example 1:

index.js




// Node.js program to demonstrate the
// diffieHellman.setPrivateKey() Method
  
const crypto = require('crypto')
  
// Generate DH Key pair
crypto.generateKeyPair('dh'
    {
        primeLength: 512,
         publicKeyEncoding: {
            type: 'spki',
            format: 'der'
        },
        privateKeyEncoding: {
            type: 'pkcs8',
            format: 'der'
        }
    },
    cb
)
  
function cb(err, publicKey, privateKey){
    // Create Diffie-Hellman instance
    const dh = crypto.createDiffieHellman(512)
    // Set the dh's privateKey
    dh.setPrivateKey(privateKey)
  
    if( privateKey.equals(dh.getPrivateKey()) )
        console.log("DH private Key is set successfully")
}


Run index.js file using the following command

node index.js

Output:

DH private Key is set successfully

Example 2 :

index.js




// Node.js program to demonstrate the
// diffieHellman.setPrivateKey() Method
  
const crypto = require( 'crypto' )
  
crypto.generateKeyPair( 
    'dh'
    { primeLength: 512 }, 
    cb 
)
  
function cb( err, publicKey, privateKey ){
    // Export key from KeyObject
    privateKey = privateKey.export( {type: 'pkcs8', format: 'der'} )
    // Encode key in base64
    privateKey = privateKey.toString('base64');
    // Create Diffie-Hellman instance
    const dh = crypto.createDiffieHellman( 512 )
    // Set the dh's privateKey
    dh.setPrivateKey( privateKey, 'base64' )
  
    if( privateKey === dh.getPrivateKey('base64')  )
        console.log( "DH private Key is set successfully" )
}


Run index.js file using the following command

node index.js

Output:

DH private Key is set successfully

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!