I'm trying to understand how the diffie hellman key exchange works and wrote a simple node.js program to make a test:
var crypto = require("crypto");
//create a public & private key for alice
var Alice = crypto.createDiffieHellman(512);
Alice.generateKeys();
//create a public & private key for bob
var Bob = crypto.createDiffieHellman(512);
Bob.generateKeys();
//let bob and alice compute the shared secret
console.log(Alice.computeSecret(Bob.getPublicKey()).toString("hex"));
console.log(Bob.computeSecret(Alice.getPublicKey()).toString("hex"));
If i understood the right graphics on this wikipedia article right, then both secrets should be the same. But they never are, why?
Ah well I already found the solution:
var crypto = require("crypto");
var prime = crypto.createDiffieHellman(512).getPrime();
//create a public & private key for alice
var Alice = crypto.createDiffieHellman(prime);
Alice.generateKeys();
//create a public & private key for bob
var Bob = crypto.createDiffieHellman(prime);
Bob.generateKeys();
//let bob and alice compute the shared secret
console.log(Alice.computeSecret(Bob.getPublicKey()).toString("hex"));
console.log(Bob.computeSecret(Alice.getPublicKey()).toString("hex"));