const crypto = require('crypto');
// Create DiffieHellman instance
const dh = crypto.createDiffieHellman(1024);
// Generate keys
dh.generateKeys();
// Get keys and parameters with different encodings
const encodings = ['hex', 'base64', 'base64url'];
console.log('Different encodings for DiffieHellman values:');
console.log('='.repeat(60));
// Prime in different encodings
console.log('\nPrime:');
encodings.forEach(enc => {
console.log(`${enc.padEnd(10)}: ${dh.getPrime(enc).substring(0, 30)}...`);
});
// Generator in different encodings
console.log('\nGenerator:');
encodings.forEach(enc => {
console.log(`${enc.padEnd(10)}: ${dh.getGenerator(enc)}`);
});
// Public key in different encodings
console.log('\nPublic Key:');
encodings.forEach(enc => {
console.log(`${enc.padEnd(10)}: ${dh.getPublicKey(enc).substring(0, 30)}...`);
});
// Private key in different encodings
console.log('\nPrivate Key:');
encodings.forEach(enc => {
console.log(`${enc.padEnd(10)}: ${dh.getPrivateKey(enc).substring(0, 30)}...`);
});
// Example of using different encodings in key exchange
console.log('\nKey Exchange with Different Encodings:');
console.log('='.repeat(60));
// Alice generates keys with hex encoding
const alice = crypto.createDiffieHellman(1024);
alice.generateKeys();
// Bob gets Alice's prime and generator in base64
const primeBase64 = alice.getPrime('base64');
const generatorBase64 = alice.getGenerator('base64');
// Bob creates his instance using base64-encoded parameters
const bob = crypto.createDiffieHellman(
Buffer.from(primeBase64, 'base64'),
Buffer.from(generatorBase64, 'base64')
);
bob.generateKeys();
// Exchange public keys with different encodings
const alicePublicKey = alice.getPublicKey('hex');
const bobPublicKey = bob.getPublicKey('base64');
// Compute shared secrets (handling different encodings)
const aliceSecret = alice.computeSecret(
Buffer.from(bobPublicKey, 'base64'),
null,
'hex'
);
const bobSecret = bob.computeSecret(
Buffer.from(alicePublicKey, 'hex'),
'hex',
'base64'
);
// Convert both to hex for comparison
const aliceHex = Buffer.from(aliceSecret, 'hex').toString('hex');
const bobHex = Buffer.from(bobSecret, 'base64').toString('hex');
console.log('Alice\'s secret (hex):', aliceHex.substring(0, 30) + '...');
console.log('Bob\'s secret (hex): ', bobHex.substring(0, 30) + '...');
console.log('Secrets match:', aliceHex === bobHex);