const crypto = require('crypto');
console.log('Basic Diffie-Hellman Key Exchange between Alice and Bob\n');
// Alice generates parameters and keys
console.log('Alice: Creating DiffieHellman instance...');
const alice = crypto.createDiffieHellman(2048);
const aliceKeys = alice.generateKeys();
// Bob also needs parameters from Alice
console.log('Alice: Sending parameters to Bob...');
const p = alice.getPrime();
const g = alice.getGenerator();
// Bob creates a DiffieHellman instance with the same parameters
console.log('Bob: Creating DiffieHellman instance with Alice\'s parameters...');
const bob = crypto.createDiffieHellman(p, g);
const bobKeys = bob.generateKeys();
// Exchange public keys (over an insecure channel)
console.log('Exchanging public keys...');
const alicePublicKey = alice.getPublicKey();
const bobPublicKey = bob.getPublicKey();
// Alice computes the shared secret using Bob's public key
console.log('Alice: Computing shared secret...');
const aliceSecret = alice.computeSecret(bobPublicKey);
// Bob computes the shared secret using Alice's public key
console.log('Bob: Computing shared secret...');
const bobSecret = bob.computeSecret(alicePublicKey);
// The shared secret should be the same
console.log('\nResults:');
console.log('Alice and Bob secrets match:', aliceSecret.equals(bobSecret));
console.log('Shared secret (first 16 bytes):', aliceSecret.toString('hex').substring(0, 32) + '...');