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
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) {
const dh = crypto.createDiffieHellman(512)
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
const crypto = require( 'crypto' )
crypto.generateKeyPair(
'dh' ,
{ primeLength: 512 },
cb
)
function cb(err, publicKey, publicKey) {
publicKey = publicKey.export({ type: 'spki' , format: 'der' })
publicKey = publicKey.toString( 'base64' );
const dh = crypto.createDiffieHellman(512)
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
Share your thoughts in the comments
Please Login to comment...