Skip to content
Related Articles

Related Articles

Improve Article

Node.js diffieHellman.setPublicKey() Method

  • Last Updated : 11 Aug, 2021

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

Syntax:

diffieHellman.setPublicKey(publicKey[, encoding])

Parameters: This method accepts the following two parameters:

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

 



Example 1:

index.js




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

Run index.js file using the following command

node index.js

Output:

DH public Key is set successfully

Example 2:

index.js




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

Run index.js file using the following command

node index.js

Output:

DH public Key is set successfully

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :