Node.js ecdh.setPrivateKey() Method
Last Updated :
27 Jul, 2021
The ecdh.getPrivateKey() method is an inbuilt application programming interface of class ECDH within the crypto module which is used to set the private key of the Elliptic Curve Diffie-Hellman (ECDH) object. The encoding of the key can be specified using the encoding parameter.
An error would be thrown if the private key is not valid for the specified curve. The setting of the private key using this method will automatically generate and set the corresponding public key in the ECDH object.
Syntax:
ecdh.setPrivateKey( privateKey, encoding )
Parameters: This method accepts two parameters as mentioned above and described below:
- privateKey: This is the private key that needs to be set. It can be given in the format of a string, ArrayBuffer, Buffer, TypedArray, or DataView.
- encoding: In encoding string value that specifies the encoding of the returned value. It is an optional parameter.
Return Value: It returns the Elliptic Curve DiffieHellman public key in the specified encoding. When the encoding is not provided, it is returned as a Buffer, otherwise, a String is returned.
The examples below demonstrate this method:
Example 1:
Javascript
const crypto = require( 'crypto' );
const geekA = crypto.createECDH( 'secp521r1' );
const geekB = crypto.createECDH( 'secp521r1' );
geekA.setPrivateKey( "thisisasecretkey!" );
geekB.setPrivateKey( "thisisanotherkey!" );
let geekAPrivateKey = geekA.getPrivateKey();
let geekBPrivateKey = geekB.getPrivateKey();
console.log( "Private Key of Geek A is:" ,
geekAPrivateKey);
console.log( "Private Key of Geek B is:" ,
geekBPrivateKey);
|
Output:
Private Key of Geek A is: <Buffer 74 68 69 73 69 73 61 73 65 63 72 65 74 6b 65 79 21>
Private Key of Geek B is: <Buffer 74 68 69 73 69 73 61 6e 6f 74 68 65 72 6b 65 79 21>
Example 2:
Javascript
const crypto = require( 'crypto' );
const geekA = crypto.createECDH( 'secp521r1' );
const geekB = crypto.createECDH( 'secp521r1' );
geekA.setPrivateKey( "68656c6c6f" , "hex" );
geekB.setPrivateKey( "d29ybGQ=" , "base64" );
let geekAPrivateKey =
geekA.getPrivateKey( 'utf-8' );
let geekBPrivateKey =
geekB.getPrivateKey( 'utf-8' );
console.log( "Private Key of Geek A is:" ,
geekAPrivateKey);
console.log( "Private Key of Geek B is:" ,
geekBPrivateKey);
|
Output:
Private Key of Geek A is: hello
Private Key of Geek B is: world
Reference: https://nodejs.org/api/crypto.html#crypto_ecdh_setprivatekey_privatekey_encoding
Share your thoughts in the comments
Please Login to comment...