Skip to content

Instantly share code, notes, and snippets.

@ericrange
Forked from bellbind/dh-usage.js
Created March 31, 2016 12:59
Show Gist options
  • Save ericrange/7efbc87f624e1c8e0f8ff70d388f2796 to your computer and use it in GitHub Desktop.
Save ericrange/7efbc87f624e1c8e0f8ff70d388f2796 to your computer and use it in GitHub Desktop.
[nodejs][javascript] Diffie-Hellman key exchange by nodejs-0.5
// node.js 0.5 Diffie-Hellman example
var assert = require("assert");
var crypto = require("crypto");
// the prime is shared by everyone
var server = crypto.createDiffieHellman(512);
var prime = server.getPrime();
// sharing secret key on a pair
var alice = crypto.createDiffieHellman(prime);
alice.generateKeys();
var alicePub = alice.getPublicKey();
var bob = crypto.createDiffieHellman(prime);
bob.generateKeys();
var bobPub = bob.getPublicKey();
var bobAliceSecret = bob.computeSecret(alicePub);
var aliceBobSecret = alice.computeSecret(bobPub);
// public keys are different, but secret is common.
assert.notEqual(bobPub, alicePub);
assert.equal(bobAliceSecret, aliceBobSecret);
// use common secret as shared encryption key...
// shared secret with 3rd person
var carol = crypto.createDiffieHellman(prime);
carol.generateKeys();
var carolPub = carol.getPublicKey();
var carolAliceSecret = carol.computeSecret(alicePub);
var aliceCarolSecret = alice.computeSecret(carolPub);
assert.notEqual(carolPub, alicePub);
assert.equal(carolAliceSecret, aliceCarolSecret);
// secret depends on pairs
assert.notEqual(aliceBobSecret, aliceCarolSecret);
var carolBobSecret = carol.computeSecret(bobPub);
assert.notEqual(carolAliceSecret, carolBobSecret);
Copy link

ghost commented Dec 4, 2020

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment