Get your own Node server
const crypto = require('crypto');

console.log('ECDH Set Private Key Example');
console.log('='.repeat(50));

// 1. Create ECDH instance with prime256v1 curve
const ecdh = crypto.createECDH('prime256v1');

// 2. Generate a private key (in a real application, this would be securely generated)
// For demonstration, we'll use a fixed private key
const privateKey = 'a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890';

console.log('Setting private key:');
console.log('- Private Key (hex):', privateKey);

// 3. Set the private key
try {
  ecdh.setPrivateKey(privateKey, 'hex');
  console.log('✓ Private key set successfully');
  
  // 4. Get the private key to verify it was set correctly
  const retrievedPrivateKey = ecdh.getPrivateKey('hex');
  console.log('\nRetrieved Private Key:');
  console.log('- Hex:', retrievedPrivateKey);
  console.log('- Length:', retrievedPrivateKey.length / 2, 'bytes');
  console.log('- Matches input:', retrievedPrivateKey === privateKey);
  
  // 5. Get the corresponding public key
  const publicKey = ecdh.getPublicKey('hex');
  console.log('\nGenerated Public Key:');
  console.log('- Hex:', publicKey);
  console.log('- Length:', publicKey.length / 2, 'bytes');
  
  // 6. Demonstrate key exchange with another party
  console.log('\nDemonstrating key exchange:');
  console.log('='.repeat(30));
  
  // Create another ECDH instance for the other party
  const otherEcdh = crypto.createECDH('prime256v1');
  otherEcdh.generateKeys();
  
  // Exchange public keys
  const otherPublicKey = otherEcdh.getPublicKey('hex');
  console.log("Other party's public key:", otherPublicKey.substring(0, 64) + '...');
  
  // Compute shared secrets
  const sharedSecret1 = ecdh.computeSecret(Buffer.from(otherPublicKey, 'hex'));
  const sharedSecret2 = otherEcdh.computeSecret(ecdh.getPublicKey());
  
  console.log('\nShared secrets match:', sharedSecret1.equals(sharedSecret2));
  console.log('Shared secret (first 16 bytes):', sharedSecret1.toString('hex').substring(0, 32) + '...');
  
} catch (error) {
  console.error('Error:', error.message);
  console.error('Error code:', error.code);
}

              
ECDH Set Private Key Example
==================================================
Setting private key:
- Private Key (hex): a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890
✓ Private key set successfully

Retrieved Private Key:
- Hex: a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890
- Length: 32 bytes
- Matches input: true

Generated Public Key:
- Hex: 04a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890
- Length: 65 bytes

Demonstrating key exchange:
==============================
Other party's public key: 04b2a1c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890...

Shared secrets match: true
Shared secret (first 16 bytes): 1a2b3c4d5e6f7890abcdeffedcba9876...