ECDH Shared Secret via diffieHellman

Two ECDH P-256 key pairs derive identical shared bytes via diffieHellman, which a SHA-256 hash turns into a symmetric session key.

TypescriptSecurity Boundaries

Code

typescriptsnippet
16 lines
import { createHash, diffieHellman, generateKeyPairSync } from 'node:crypto';

// generateKeyPairSync creates an ECDH-capable key pair on the P-256 curve
const alice = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
const bob = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });

// Each side derives bits from the other's public key with its own private key
const fromAlice = diffieHellman({ privateKey: alice.privateKey, publicKey: bob.publicKey });
const fromBob = diffieHellman({ privateKey: bob.privateKey, publicKey: alice.publicKey });

console.log('same shared bytes:', fromAlice.equals(fromBob));
console.log('shared bits:', fromAlice.length * 8);

// Hash the raw secret into a symmetric key for AES
const sessionKey = createHash('sha256').update(fromAlice).digest('hex');
console.log('key length:', sessionKey.length, 'hex chars');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

same shared bytes: true
shared bits: 256
key length: 64 hex chars

How it works

The only import source is node:crypto, a Node.js built-in, exposing createHash, diffieHellman, generateKeyPairSync.

Top-level bindings alice, bob, fromAlice, fromBob hold the demo state — nothing sits inside a function scope.

What to watch for

  • node:crypto is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Putting it to use

The run prints same shared bytes:, shared bits:, key length: — each prefix names the step that produced it.

Core lines

const fromAlice = diffieHellman({ privateKey: alice.privateKey, publicKey: bob.publicKey });
const fromBob = diffieHellman({ privateKey: bob.privateKey, publicKey: alice.publicKey });
const sessionKey = createHash('sha256').update(fromAlice).digest('hex');

Interactive Tools for This Topic

FAQ

Does this require external packages?
No — `node:crypto` is a Node.js built-in module; nothing to install.