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"));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top