Skip to content

Instantly share code, notes, and snippets.

@durango
Forked from bellbind/dh-usage.js
Created February 5, 2012 17:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save durango/1746863 to your computer and use it in GitHub Desktop.
Save durango/1746863 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment