const crypto = require('crypto');
// Create ECDH instances for Alice and Bob
const alice = crypto.createECDH('prime256v1');
alice.generateKeys();
const bob = crypto.createECDH('prime256v1');
bob.generateKeys();
// Exchange public keys
const alicePublicKey = alice.getPublicKey();
const bobPublicKey = bob.getPublicKey();
// Compute shared secrets
const aliceSecret = alice.computeSecret(bobPublicKey);
const bobSecret = bob.computeSecret(alicePublicKey);
// Use the shared secret as a key for encryption
// First, derive a suitable key using a hash function
function deriveKey(secret, salt, keyLength) {
return crypto.pbkdf2Sync(secret, salt, 1000, keyLength, 'sha256');
}
// Alice sends an encrypted message to Bob
function encrypt(text, secret) {
// Create a salt and derive a key
const salt = Buffer.from('a1b2c3d4e5f67890', 'hex'); // Fixed salt for consistent output
const key = deriveKey(secret, salt, 32); // 32 bytes for AES-256
const iv = Buffer.from('1234567890abcdef1234567890abcdef', 'hex'); // Fixed IV for consistent output
// Encrypt the message
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
// Return everything Bob needs to decrypt
return {
salt: salt.toString('hex'),
iv: iv.toString('hex'),
encrypted
};
}
// Bob decrypts the message from Alice
function decrypt(encryptedInfo, secret) {
// Parse values
const salt = Buffer.from(encryptedInfo.salt, 'hex');
const iv = Buffer.from(encryptedInfo.iv, 'hex');
const encrypted = encryptedInfo.encrypted;
// Derive the same key
const key = deriveKey(secret, salt, 32);
// Decrypt the message
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// Alice encrypts a message using the shared secret
const message = 'Hello Bob, this is a secret message from Alice using ECDH!';
console.log('Original message:', message);
const encryptedMessage = encrypt(message, aliceSecret);
console.log('Encrypted message:');
console.log('- Salt:', encryptedMessage.salt);
console.log('- IV:', encryptedMessage.iv);
console.log('- Ciphertext:', encryptedMessage.encrypted);
// Bob decrypts the message using his shared secret
const decryptedMessage = decrypt(encryptedMessage, bobSecret);
console.log('\nDecrypted message:', decryptedMessage);
// Verify the result
console.log('\nVerification:');
console.log('- Secrets match:', aliceSecret.equals(bobSecret));
console.log('- Decryption successful:', message === decryptedMessage);