Skip to content

Instantly share code, notes, and snippets.

@brendtumi
Created July 29, 2016 12:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brendtumi/41a60b848367d2cfddabf1d60d7e9a54 to your computer and use it in GitHub Desktop.
Save brendtumi/41a60b848367d2cfddabf1d60d7e9a54 to your computer and use it in GitHub Desktop.
[nodejs][javascript] Diffie-Hellman key exchange - nodejs v6
"use strict";
const assert = require("assert");
const crypto = require("crypto");
let server = crypto.createDiffieHellman(1024);
let prime = server.getPrime();
console.log("Generate Alice's keys...");
let alice = crypto.createDiffieHellman(prime);
let alicePublicKey = alice.generateKeys("base64");
console.log("Generate Bob's keys...");
let bob = crypto.createDiffieHellman(prime);
let bobPublicKey = bob.generateKeys("base64");
console.log("Generate David's keys...");
let david = crypto.createDiffieHellman(prime);
let davidPublicKey = david.generateKeys("base64");
console.log("Exchange and generate the secret...");
let aliceBobSecret = alice.computeSecret(bobPublicKey, "base64");
let bobAliceSecret = bob.computeSecret(alicePublicKey, "base64");
let davidAliceSecret = david.computeSecret(alicePublicKey, "base64");
let aliceDavidSecret = alice.computeSecret(davidPublicKey, "base64");
// console.log("alicePublicKey", alicePublicKey);
// console.log("bobPublicKey", bobPublicKey);
assert.notEqual(alicePublicKey, bobPublicKey);
console.log("alicePublicKey and bobPublicKey NOT equal");
// console.log("aliceBobSecret", aliceBobSecret.toString("base64"));
// console.log("bobAliceSecret", bobAliceSecret.toString("base64"));
assert.equal(aliceBobSecret.toString("hex"), bobAliceSecret.toString("hex"));
console.log("aliceBobSecret and bobAliceSecret equal");
console.log("----- Shared secret with 3rd person -----");
// console.log("alicePublicKey", alicePublicKey);
// console.log("davidPublicKey", davidPublicKey);
assert.notEqual(alicePublicKey, davidPublicKey);
console.log("alicePublicKey and davidPublicKey NOT equal");
// console.log("aliceDavidSecret", aliceDavidSecret.toString("base64"));
// console.log("davidAliceSecret", davidAliceSecret.toString("base64"));
assert.equal(aliceDavidSecret.toString("hex"), davidAliceSecret.toString("hex"));
console.log("aliceDavidSecret and davidAliceSecret equal");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment