Node.js Key Agreement
Key agreement can derive matching shared secret material from two key pairs. It does not by itself prove who owns the other public key or establish a complete secure channel.
How it works
This example exercises both a named finite-field Diffie-Hellman group and an elliptic-curve exchange. It compares the derived bytes inside the process without printing them. A real protocol needs authenticated peer identities, a key derivation function, transcript binding and replay protections. Prefer an established transport protocol such as correctly configured TLS rather than designing a new channel directly from these low-level primitives.
Run the code
Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as key-agreement.mjs in a separate empty exercises folder and run node key-agreement.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.
Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.
Example
import { getDiffieHellman, createECDH } from 'node:crypto';
const a = getDiffieHellman('modp14'),
b = getDiffieHellman('modp14');
a.generateKeys();
b.generateKeys();
console.log(
a.computeSecret(b.getPublicKey()).equals(b.computeSecret(a.getPublicKey())),
);
const x = createECDH('prime256v1'),
y = createECDH('prime256v1');
x.generateKeys();
y.generateKeys();
console.log(
x.computeSecret(y.getPublicKey()).equals(y.computeSecret(x.getPublicKey())),
);
Expected result
true true
Both controlled exchanges agree on bytes, which demonstrates the primitive API contracts. The public keys were passed directly between objects in one trusted program, so the fixture does not demonstrate resistance to an active network attacker or authenticate a remote participant.
Use the Node.js API reference for the precise version contract.