Skip to content
Related Articles

Related Articles

Improve Article

Node.js ecdh.generateKeys() Method

  • Last Updated : 22 Jul, 2021

The ecdh.generateKeys() method is an inbuilt application programming interface of class ECDH within the crypto module which is used to generate private and public key values of the Elliptic Curve Diffie-Hellman (ECDH) object. It returns only the public key in the given format and encoding.

Syntax:

ecdh.generateKeys( encoding, format )

Parameters: This method accepts two parameters as mentioned above and described below:

  • encoding: This is a string value that specifies the encoding of the return value.
  • format: It is a string that specifies the format of the keys. The value can be ‘compressed’ or ‘uncompressed’.

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');
  
// Generate an ECDH object for geekA
const geek = crypto.createECDH('secp521r1');
  
// Generate keys for geek and return
// the public key
const geekAPublicKey = geek.generateKeys();
  
console.log(
  "Public Key of Geek A is:", geekAPublicKey);
  
// Get the private key of geek
const geekAPrivateKey = geek.getPrivateKey();
console.log(
  "Private Key of Geek A is:", geekAPrivateKey);

Output:

Public Key of Geek A is: <Buffer 04 00 89 09 8f e4 14 ad d9 77 1d a4 8b 2b 82 a6 2c 64 9e 0c 37 75 e3 db 7d 92 3e 8d a9 dc 66 c8 c9 5a bb 8b 4d de 27 b7 9a 26 c4 59 78 c6 f9 e7 36 d9 … 83 more bytes>
Private Key of Geek A is: <Buffer 01 8f af 82 49 30 70 e0 47 1f 4f 46 7d d3 99 50 8b 14 47 97 04 9d 3e 46 c7 b1 8e d1 c1 ad 6f de ea c7 a0 bc a8 af f2 c3 e0 46 df 74 bf 07 a3 36 a2 ac … 16 more bytes>

Example 2:

Javascript




const crypto = require('crypto');
  
// Generate an ECDH object for geekA
const geekA = crypto.createECDH('secp521r1');
  
// Generate keys for geekA in base64 encoding
const geekAkey =
  geekA.generateKeys('base64');
  
console.log(
  "Public Key of Geek A is:", geekAkey);
  
// Generate an ECDH object for geekB
const geekB = crypto.createECDH('secp521r1');
  
// Generate keys for geekB in base64
// encoding and compressed
const geekBkey =
  geekB.generateKeys('base64', 'compressed');
  
console.log(
  "Public Key of Geek B is:", geekBkey);

Output:

Public Key of Geek A is: BAHbKH6Uv0hAZPhQer+bVA/GC8VRqTf0LTLpNWmWeOPh+pDkLhhHnE9/XYI2pjDQ1Nhum/GeHkOEJKSMEaD51Q0EhgE2y+IiHb2gSluy7ho0OosMLFrlM8YgPaXNV6skBqsbNGlYh/HEBIlilzNfGUrNsvsh4RuI0usEOh/v6NFrpEIfUA==
Public Key of Geek B is: AwCz/x81YIdVtPyy5B3YKwgR3hgzOXrFZsXi3M2WFcvRL2yh0VKza0/b8Mw1Z/p4Pnl1gGO2JMUfLNI4FFvzaxb9Og==

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :