How to generate Diffie Hellman key pair in Node.JS

Super easy using crypto library. You can create a file called DiffieHellmanKeyPairGeneration.js for example and paste this code inside:

console.log('\n- --- ( Diffie Hellman Key Pair Generator ) --- -');

var crypto = require('crypto');

var bitSize = 2048;

var dh = crypto.createDiffieHellman(bitSize);

dh.generateKeys();

console.log('Private Key:\n' + dh.getPrivateKey('base64'));
console.log('\n');

console.log('Public Key:\n' + dh.getPublicKey('base64'));

console.log('--- End ---');

Then run it, wait…wait…wait…wait…wait…wait…, and you should get something similar to this:

E:\NodeJS>node DiffieHellmanKeyPairGeneration.js

- --- ( Diffie Hellman Key Pair Generator ) --- -
Private Key:
Wa5X1ExTrYqFbvKfobL4DghT/4KKweychPEqXUtlVZrCuKOiui74Ezroi+ScrE3KCHXMsnJVSXAe7+l0RAseEmL5/lAThgyBhaVS7D7LVZTivR7X5jU+4nRZLeWev4QXuGpwRqFsJFO7z8TCDhbmZ9lfq9l+KBr8RxzO1fmxRurwu2HkXevRx44XTo5ohH41rzUNCQosVkyo3xTbDB8S4B7gViRwXgwZLQvrTRkujfAMOI4pQcR19zJO77asQfoGBJdCzZwZVoIgT/OMvjpKvcYOi2nydmIPPORdK1zvGBwJ8r2WOjVIg+ysItnO4HA3C5yy4tYHtR7KIpL91cXyQA==


Public Key:
okVlXJES/hHPvCXT/b5YtDA7TFXP5rKcq9DAllXKCg+6vyKW/E50tFabq3fhOz4ex7kLjKEPnu3VwEODgCcIb4Me9VVLafd3OGfuGuKnjvmOtJBZJXz5DGHhYd4NLDvhzjOqMOF05E0UvZV0/ncIBMR+/xU9/agUlsgMMPH+52N/ozc91ASjW8Uq/wALlMcO7PnS2EVpCx0Dc9/PxHbkcyNNAtWg4pvpEiRtx86U1dx+so5wdDcAM3z1HkKehUDLHjsKuSybr7cc2H9Me+pLUUyyQ5EtGW3KStPRwSl/20/icHQa+KlQEkNHD4omF0C5r591iYUg6MgwAp9QCASn0Q==
--- End ---

That’s it.

Sources: