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.
Code
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 charsHow 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:cryptois 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
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
FAQ
- Does this require external packages?
- No — `node:crypto` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.