Node.js diffieHellman.setPrivateKey() Method
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
const crypto = require( 'crypto' )
crypto.generateKeyPair( 'dh' ,
{
primeLength: 512,
publicKeyEncoding: {
type: 'spki' ,
format: 'der'
},
privateKeyEncoding: {
type: 'pkcs8' ,
format: 'der'
}
},
cb
)
function cb(err, publicKey, privateKey){
const dh = crypto.createDiffieHellman(512)
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
const crypto = require( 'crypto' )
crypto.generateKeyPair(
'dh' ,
{ primeLength: 512 },
cb
)
function cb( err, publicKey, privateKey ){
privateKey = privateKey.export( {type: 'pkcs8' , format: 'der' } )
privateKey = privateKey.toString( 'base64' );
const dh = crypto.createDiffieHellman( 512 )
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
Last Updated :
28 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...