Node.js Reference ยท crypto
Node.js crypto.diffieHellman() and ECDH
Reference for crypto.diffieHellman() and crypto.createECDH() in Node.js: agreeing a shared secret over an open channel with X25519 and elliptic curves, plus HKDF use.
Key agreement lets two parties who have never shared a secret compute the same secret value while exchanging only public keys. Each side combines its own private key with the other side's public key and gets identical bytes. crypto.diffieHellman({ privateKey, publicKey }) does this with KeyObject handles for X25519, X448, EC and DH keys. crypto.createECDH(curve) is an older class-based API for elliptic-curve Diffie-Hellman.
The raw shared value is not a ready-to-use key. Run it through crypto.hkdf() to obtain encryption keys, and authenticate the public keys (with signatures or certificates), or a man in the middle can swap them.
import { generateKeyPairSync, diffieHellman } from 'node:crypto'; const alice = generateKeyPairSync('x25519'); const bob = generateKeyPairSync('x25519'); const secret = diffieHellman({ privateKey: alice.privateKey, publicKey: bob.publicKey });
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
crypto.diffieHellman({ privateKey, publicKey }, callback?): Buffer crypto.createECDH(curveName: string): ECDH ecdh.generateKeys(encoding?, format?): Buffer | string ecdh.computeSecret(otherPublicKey, inputEncoding?, outputEncoding?): Buffer | string ecdh.getPublicKey(encoding?, format?): Buffer | string ecdh.getPrivateKey(encoding?): Buffer | string ecdh.setPrivateKey(privateKey, encoding?): void
| Name | Description |
|---|---|
privateKey |
Your private KeyObject. |
publicKey |
The other party's public KeyObject, of the same type and curve. |
curveName |
A curve name such as 'prime256v1' (P-256), 'secp384r1', 'secp521r1' or 'secp256k1'. |
format |
For generateKeys() and getPublicKey(): 'uncompressed' (default), 'compressed' or 'hybrid'. |
Returns: diffieHellman() returns the shared secret as a Buffer (32 bytes for X25519 and P-256).
Errors: ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY when the peer's public key is not a valid point on the curve, ERR_CRYPTO_ECDH_INVALID_FORMAT for an unknown format, ERR_CRYPTO_INVALID_CURVE for an unknown curve name, and errors for mismatched key types.
Usage notes
- Derive, do not use directly. The secret has structure. Feed it to HKDF with a distinct
infostring, and include both public keys in theinfoor salt to bind the session. - Ephemeral keys give forward secrecy. Generate a fresh pair per session and discard the private key afterwards. TLS 1.3 does exactly this.
- Agreement is not authentication. Anyone can generate a key pair. Sign the public keys or verify them out of band, or an active attacker can sit in the middle.
- Prefer X25519 unless a standard requires a NIST curve; it is simple and avoids invalid-curve pitfalls. Use
createECDHonly with a legacy protocol that demands raw point encodings. - Validate input.
computeSecretrejects points that are not on the curve; never skip that error. - Classic finite-field DH exists as
crypto.createDiffieHellman()andgetDiffieHellman()with groups such as'modp14', but it is slower and needs large parameters. crypto.diffieHellman()was added in Node.js 13.9.0;createECDHin 0.11.14.
Related
crypto.hkdf(),KeyObject,crypto.generateKeyPair(), AES-GCM- Lessons: Encryption