Node.js has an in-built crypto module and which can be used to run code using Javascript. This example implements the Diffie Hellman method and uses a randomly generated prime number (press the button to generate a new prime) [Fixed DH]:
Node.js Diffie Hellman with random prime |
Theory
Bob generates a random value (\(b\)) and Alice generates a random value (\(a\)). Alice passes \(A=G^a \pmod p\) and Bob passes \(B=G^b \pmod p\). The result is then \(B^a \pmod p\) and which should be the same as \(A^b \pmod p\)::
Prime number size: 128 Alice prime (p): e08d425a42a71f6512ac896870b18b7b Alice generator (G): 02 Alice private key: 49709c0831e05298d1c3fcaba86e5981 Bob private key: 47a9ef528d0b20914bed51da7ea57956 Alice public key: 53041cf15ea78f0bc3a634cf313b822e Bob public key: bdead016671bc670c9a127382d39fd51 Alice secret: df3c65e2e8424e76a20b5af22b15379f Bob secret: df3c65e2e8424e76a20b5af22b15379f
In this case the public key has 768 bits (192 hex characters). The following is some sample code
var crypto = require("crypto"); const args = process.argv.slice(3); type = parseInt(args[0],10); console.log("Prime number size:\t",type); const alice = crypto.createDiffieHellman(type); alice.generateKeys(); const bob= crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator()); bob.generateKeys(); console.log("Alice prime (p):",alice.getPrime().toString('hex'),"\nAlice generator (G):",alice.getGenerator().toString('hex')); console.log("\nAlice private key:",alice.getPrivateKey().toString('hex')); console.log("\nBob private key:",bob.getPrivateKey().toString('hex')); console.log("\nAlice public key:",alice.getPublicKey().toString('hex')); console.log("\nBob public key:",bob.getPublicKey().toString('hex')); var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); console.log("\nAlice secret:",alice_secret); console.log("\nBob secret:",bob_secret);