I am using crypto module of node js for exchanging key using diffie-hellman algorithm.


const crypto = require("crypto");

const alice = crypto.createDiffieHellman(512);

const aliceKey = alice.generateKeys();


const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());

const bobKey = bob.generateKeys();

const aliceSecret = alice.computeSecret(bobKey);

const bobSecret = bob.computeSecret(aliceKey);

The above example is taken from node.js documentation as shown the client uses servers prime number for generating the prime number.

my question is how should I securely send the prime number and the other parameter to client over internet? are there any other alternatives?

and another question is that I am generating keys using generate keys function but I have already generated private-key.pem and public-cert.pem file. can I use those if yes then how?, if no then what is difference between those keys?

  • 1) p and g are not secret, so you can embed both of these in client.js and server.js. 2) It sounds like you are using this scheme to create ephemeral keys for pfs. If so, use client.js and server.js to create the ephemeral keys (and shared secret), then use the keys in the pem files to sign those keys for authenticity.
    – mti2935
    May 21, 2020 at 16:20
  • Actually those pem files are genrated using openssl terminal. Can you tell me or point somewhere how can i edit those files? Also thanks for your answer May 21, 2020 at 16:45
  • You're welcome. You wouldn't normally edit pem files, as changing just one byte in these files can make them inoperable. But, you can easily use openssl to create pem files consisting of private and public keys. For RSA, use openssl genrsa. For DH, use openssl genpkey. For ECDH, use openssl ecparam.
    – mti2935
    May 21, 2020 at 17:35
  • You know that 512 bit DH is very insecure, right? It needs to be at least 2048. And you should switch from DH to ECDH (nodejs.org/api/crypto.html#crypto_class_ecdh), either Curve25519 (preferred) or P-256 (compatible).
    – Z.T.
    May 21, 2020 at 21:11


You must log in to answer this question.

Browse other questions tagged .