Node.js theorytheory 0/50 · 0%
Web3 integration · hard

42. Signing and verifying data with crypto

HMACs, key pairs and message authentication.

`node:crypto` supports symmetric HMACs (shared-secret message authentication) and asymmetric key pairs (sign with a private key, verify with the public key) — the same pattern that underlies transaction signing on most blockchains, even though production wallet code typically uses a dedicated elliptic-curve library (secp256k1) rather than Node's generic crypto module.

js
import { createHmac, generateKeyPairSync, sign, verify } from "node:crypto";

// symmetric: both sides share a secret
const mac = createHmac("sha256", "shared-secret").update("payload").digest("hex");

// asymmetric: sign with private key, verify with public key
const { privateKey, publicKey } = generateKeyPairSync("ed25519");
const signature = sign(null, Buffer.from("payload"), privateKey);
const isValid = verify(null, Buffer.from("payload"), publicKey, signature);

The core idea to internalize: a signature proves the holder of a private key authorized a specific message, and anyone with the corresponding public key can verify that without ever seeing the private key.

Check your understanding

  1. 1. What does an HMAC require both parties to share?

  2. 2. In asymmetric signing, what key produces the signature?

  3. 3. What can anyone with the public key do?