Description
What is key management?
Key management is the discipline of controlling encryption keys across their whole life: generating them from a secure random source, storing them where applications cannot simply read them, allowing their use only by authorised services, rotating them on a schedule, and revoking or destroying them when they are no longer needed. In practice it runs in a key management service (KMS) or a hardware security module (HSM), which keeps the most important keys inside a tamper-resistant boundary and logs every use.
Most systems use envelope encryption. Each record, file or tenant is encrypted locally with a data encryption key (DEK), typically AES-256-GCM; the DEK is then encrypted, or wrapped, by a key encryption key (KEK), the master key held in the KMS. The database stores the ciphertext next to the wrapped DEK. To read, the application asks the KMS to unwrap the DEK, decrypts in memory and discards the plaintext key. The master key itself never leaves the KMS.
Key management is different from its neighbours. Encryption at Rest is the outcome (stored chat history, media and backups are unreadable without a key), while key management is how those keys are controlled. Secrets Management stores credentials such as an App Secret or a system user token, and Token Rotation replaces those credentials on a schedule; a KMS holds cryptographic keys and performs operations with them without handing them out. Enterprise customers increasingly ask for bring-your-own-key (BYOK), where the master key lives in their own KMS and disabling it makes their data unreadable to the provider.
Key takeaways
- Key management is lifecycle control of encryption keys: generation, storage, use, rotation, revocation and destruction.
- Envelope encryption seals data with a data key, then wraps that data key with a master key that never leaves the KMS or HSM.
- Rotating a master key does not re-encrypt your data; older key versions stay available for decryption until you retire them.
- Whoever holds decrypt rights on the key controls the data, so key policies matter more than the choice of cipher.
- With random 96-bit IVs, NIST caps one AES-GCM key at 2^32 encryptions, another reason to use fresh data keys.
Why it matters
Why does key management matter?
Encryption is only as strong as the control over its keys. A database dump encrypted with a key sitting in the same server's .env file protects nothing; the same dump encrypted under a KMS key that only the API's runtime role may use is worthless to a thief. For a WhatsApp or CPaaS business holding chat history, phone numbers, media and consent records, key management is what answers the hard questions in a DPDP Act or ISO/IEC 27001 review: who can decrypt customer data, how would we know, and how fast can we cut that access off?
Mechanics
How does key management work?
step 1 — Create a master key per purpose
Create a KEK in the KMS or HSM for each data class or tenant (chat history, media, exports) instead of one key for everything, and write a key policy that names exactly which runtime roles may encrypt and decrypt.
step 2 — Generate a data key per record or batch
Ask the KMS for a fresh 256-bit DEK. It returns the key twice: in plaintext, and wrapped under the KEK. Encrypt locally with AES-256-GCM and a unique 96-bit IV, then wipe the plaintext key from memory.
step 3 — Store ciphertext beside the wrapped key
Persist the ciphertext, IV, authentication tag, wrapped DEK and the KEK's ID and version together, so any record can still be decrypted after the master key has been rotated.
step 4 — Decrypt through the KMS
To read, send the wrapped DEK to the KMS. It checks the caller's permission, logs the call and returns the plaintext DEK. Cache unwrapped keys only briefly and only in memory.
step 5 — Rotate, disable and destroy
Rotate KEKs on a schedule (yearly is common) and immediately after a suspected exposure. Disabling a key cuts access at once; destroy it only when nothing needs the data, because destroyed keys mean unrecoverable data.
Usage
Key management in code
import crypto from "node:crypto";import { kms } from "./kms-client.js"; // thin wrapper over your KMS or HSM SDKconst KEK_ID = "support-history"; // master key alias: it never leaves the KMSexport async function sealRecord(plaintext) {// 1. Ask the KMS for a fresh 256-bit data key, in plaintext and wrapped.const { plaintextKey, wrappedKey, keyVersion } = await kms.generateDataKey(KEK_ID);// 2. Encrypt locally with AES-256-GCM and a unique 96-bit IV.const iv = crypto.randomBytes(12);const cipher = crypto.createCipheriv("aes-256-gcm", plaintextKey, iv);const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);const tag = cipher.getAuthTag();plaintextKey.fill(0); // 3. Drop the plaintext key as soon as it is used.// 4. Keep everything needed to decrypt later, including the key version.return { ciphertext, iv, tag, wrappedKey, kek: KEK_ID, keyVersion };}export async function openRecord(rec) {// The KMS checks the caller's role, logs the call and unwraps the data key.const key = await kms.decryptDataKey(rec.kek, rec.wrappedKey);const decipher = crypto.createDecipheriv("aes-256-gcm", key, rec.iv);decipher.setAuthTag(rec.tag); // tampered ciphertext fails hereconst out = Buffer.concat([decipher.update(rec.ciphertext), decipher.final()]);key.fill(0);return out.toString("utf8");}
kms.generateDataKey and kms.decryptDataKey stand for your KMS SDK's generate-data-key and decrypt calls; the AES-256-GCM part is standard Node.js crypto.
Properties
Key management: key facts and limits
- Typical data cipher
- AES-256-GCM with a unique 96-bit IV
- AES-GCM limit per key (random IVs)
- 2^32 encryptions (NIST SP 800-38D)
- Key hierarchy
- Data key (DEK) wrapped by a master key (KEK)
- Where the master key lives
- Inside the KMS or HSM; never exported
- HSM validation standard
- FIPS 140-3
- Key lifecycle guidance
- NIST SP 800-57 Part 1 (key states, cryptoperiods)
- Common master-key rotation
- Yearly, and at once after suspected exposure
Caveats
Common mistakes with key management
Keeping the key next to the data
A key in the same .env file, config map or database as the ciphertext turns encryption into decoration. Keep master keys in a KMS or HSM and grant decrypt rights only to the runtime roles that need them.
Reusing an IV with AES-GCM
Two encryptions under the same key and IV leak the XOR of the plaintexts and break GCM's integrity protection. Generate a random 12-byte IV for every encryption, and use fresh data keys so no single key nears the 2^32 limit.
Destroying a key before the data it protects
Deleting a key is crypto-shredding: everything wrapped under it, backups included, becomes permanently unreadable. Disable first, confirm nothing breaks, and schedule destruction only after your retention period ends.
Rotating without recording key versions
If records do not store which key version wrapped their data key, rotation becomes guesswork. Store the KEK ID and version with every record; most KMSs keep older versions available for decryption.
Logging key material or decrypted payloads
A debug log that prints a data key or a decrypted transcript undoes the whole scheme. Log key IDs and versions, never key bytes, and mask personal data before anything reaches a log.
Example
Example: Encrypting support transcripts at a Chennai lender
A digital lending app in Chennai keeps two years of WhatsApp support transcripts for dispute handling. Each night's transcripts are encrypted per customer with a fresh data key, wrapped under a "support-history" master key in the company's KMS. Only the dispute-review service's role may call decrypt, and every call lands in the Audit Log. When a contractor's laptop holding a database snapshot is stolen, the security team confirms from the KMS log that no decrypt calls came from outside that role, so the snapshot exposes only ciphertext. Later, an enterprise partner asks for BYOK: the team re-wraps that partner's data keys under the partner's own master key, and the transcripts themselves are never re-encrypted.
Notes
Best practices for key management
- Use separate master keys per environment and per data class, so a staging leak never touches production.
- Alert on unusual decrypt volume: a sudden spike from one role is often the first sign of exfiltration.
- Cache unwrapped data keys for minutes, not hours, to cut KMS calls without widening exposure.
- Keep key administrators and key users as different people; nobody should both manage a key and read the data.
Questions
KMS FAQs
- What is the difference between a KMS and an HSM?
- An HSM is tamper-resistant hardware that holds keys; a KMS is the managed service that exposes key operations, often backed by HSMs. Most teams use a cloud KMS and choose a dedicated HSM only when regulation or contracts demand single-tenant hardware or a specific certification.
- Does rotating a master key re-encrypt all my data?
- No. Rotation creates a new key version for future wrapping, while existing data keys stay wrapped under older versions that the KMS keeps for decryption. To retire an old version completely, re-wrap the data keys; the bulk data does not need re-encrypting.
- Does WhatsApp's end-to-end encryption replace key management?
- No. End-to-End Encryption, which WhatsApp builds on the Signal Protocol, protects messages in transit with keys no KMS of yours ever holds. Once your systems receive messages from the Cloud API and store them, protecting those copies is your job, and that depends on keys you manage.
- What is BYOK and who asks for it?
- Bring-your-own-key means the customer's own KMS holds the master key that wraps their data keys inside your platform. Banks, insurers and large enterprises ask for it so they can audit every decrypt and cut off access by disabling the key.