Free & open · no paywall, ever

IntegrAuth Academy

Identity, security and practical AI — free, from zero. Byte-sized lessons, real diagrams, hands-on labs, zero fluff. Two programs, each with its own exam and certificate.

20 tracks 241 lessons 242 hands-on labs 230+ diagrams 100% free

English is hard? Your browser can translate this page into Tamil, Telugu, Kannada, Malayalam or Hindi. Tech words stay in English so you learn the real names.

How?
  • Chrome on phone: ⋮ menu → Translate
  • Chrome on computer: right-click → Translate to …
  • Edge: the translate icon in the address bar
Identity & API Security Track 6 · API Security
0/166 lessons read
API SECURITY · LESSON 5

Guarding private keys — KMS, HSM and rotation

One key signs every token Maya's app trusts. Another encrypts her records. If a thief steals one, they do not break in. They become the system. Your goal: know where keys should live, how to change them, and what to do when one leaks.

Key points
  • Ask first: can the key be copied out at all?
  • A KMS or HSM key is used through an API and every use is logged.
  • Envelope encryption: a small data key locks the data, a key that never leaves the KMS locks the data key.
  • Use one key for one job.
  • After a leak, remove the key at once and assume the worst.

A key's worst enemy is a copy

Think of it like…

a spare house key under the flowerpot, against a bank locker. Anyone can find the flowerpot key and copy it, and you never know. A locker opens only in front of bank staff, and a register notes every visit. A file in the repo is the flowerpot. A KMS or HSM is the locker.

Secrets management keeps secrets out of code. Keys that sign and encrypt need one more question: can the key be copied out at all? A copied key works from anywhere, in silence. A key that can only be used, in one guarded place, makes theft a small problem.

Where the key livesCan it be copied out?Is every use logged?
File in the repo or imageYesNo
Environment variableYes, by anything in that processNo
Secrets managerYes. The app fetches the plain key.Each fetch, not each use
KMS (key management service)No. You call it to sign or decrypt.Yes
HSM (hardware security module)No. Sealed in tamper-resistant hardware.Yes
TPM (Trusted Platform Module) or secure enclaveNo. Tied to one device's chip.On the device

Non-exportable keys: sign through an API

With a non-exportable key, your token service never holds the private key. It sends a hash to the KMS and gets a signature back. An attacker who takes over the service can still ask for signatures, but only while they control it. They cannot take the key away, and the audit log shows every signature they asked for.

Envelope encryption

You cannot push terabytes through a KMS. Envelope encryption uses two layers of keys:

  1. The app makes a fresh data key for each record. It encrypts the data locally with it.
  2. The KMS locks (wraps) that small data key with a key-encryption key. This key never leaves the KMS.
  3. The app stores the wrapped data key next to the ciphertext. It throws away the plain data key.
  4. To read the record, the app sends the wrapped key to the KMS. The KMS checks policy, logs it and returns the data key.

To rotate the key-encryption key, you only re-wrap the small data keys. You do not re-encrypt the data. Old key versions stay until everything is re-wrapped.

KMS / HSMkey-encryption key (KEK)never leaves · every use loggedApp server1 · make a fresh data key2 · encrypt the record locallyStorage🔒 ciphertext🔑 wrapped data key beside it3 · "wrap this data key"4 · wrapped data key comes back5 · store ciphertext + wrapped keyplaintext data key: thrown awayTo read: send the wrapped key to the KMS (checked + logged), get the data key back, decrypt locally.
Figure — Lock the data with a small key, and lock that key in the vault. The bulk data never goes to the KMS. A thief who copies the storage gets ciphertext and a wrapped key, and cannot unwrap it.

One key, one job

Use separate keys for signing and for encrypting, and for production and testing. Give each application its own key, and each tenant whose data must stay apart. Sharing one key spreads its blast radius to every job. Anyone who can call sign or unwrap holds the key's power. So only the service that needs a key may use it. Humans manage keys but do not use them day to day.

When a key leaks: the playbook

  1. Contain. Remove the key's public half from the published key set now. Skip the polite overlap.
  2. Replace. Make a new key with a new key id. Move signing or encryption to it.
  3. Scope. Read the audit log. A non-exportable key has one. A copied file has none, so assume every token it signed might be forged.
  4. Fix the cause. Close the path the key left by. Clean up exposed data.
Routine rotation — the key set overlaps on purposeA leaked key — no overlap for the attackerkey v1 in the key setkey v2 in the key setkey v1 in the key setkey v2 in the key setpublish v2, then sign with v2retire v1 once its tokens expirepulled at once — tokens v1 signed, real or forged, stop verifying
Figure — Politeness is for routine days. A planned rotation overlaps old and new keys. After a leak, the bad key goes at once.
Watch out

Non-exportable does not mean unusable. The KMS policy matters as much as the key. Set an alert for a key that suddenly signs ten times its normal amount.

Go deeper: KMS, HSM and TPM

A KMS makes keys inside itself and never gives them out in plain form. It checks a policy and writes an audit record for each request. All cloud platforms offer one. The OpenBao transit engine is an open-source example.

An HSM is a tamper-resistant device whose keys cannot be exported. It is usually checked against FIPS 140-3 and reached through a standard interface called PKCS#11. Many KMS products keep their master keys in HSMs.

A TPM or a phone's secure enclave is a small chip that does the same for one device. A passkey can live there. The browser version of the idea is a DPoP key that WebCrypto signs with but never hands over.

Non-exportable keys have costs. Each use needs a network trip. There are rate limits. If the KMS is down, nothing gets signed. Still, they turn "stolen forever" into "misused briefly, on the record".

Go deeper: Rotation and cryptoperiod

Every key needs a planned lifetime. NIST calls it a cryptoperiod. Regular rotation limits what a secretly leaked key can do. It also keeps the steps practiced. The trick is always new next to old, then retire. A key id tells everyone which key was used.

  • Signing keys. Publish the new public key first. Start signing with it. Drop the old one when every token it signed has expired. The kid header picks the key (federation trust).
  • Encryption keys. A new version encrypts new data. Old versions stay for decrypting. Each ciphertext records which version made it.
  • Shared secrets. For HMAC-signed requests, the receiver accepts old and new side by side for a while. See signed requests and webhooks.

Destroying a key-encryption key makes everything under it unreadable. This is crypto-shredding.

NIST SP 800-57 says one key should serve one purpose. A JSON Web Key can say it with use (sig or enc) and alg. Mixing algorithms on one key has led to real attacks, such as treating a public key as an HMAC secret (JWT validation).

🧪 Interactive lab — enable JavaScript to play with this one.

🧪 Try it free

In a browser console on an https page, run k = await crypto.subtle.generateKey({name: 'ECDSA', namedCurve: 'P-256'}, false, ['sign', 'verify']). Then try await crypto.subtle.exportKey('jwk', k.privateKey). The browser refuses, though it signs with that key. The open-source SoftHSM does PKCS#11 in software. Use it to learn, not to protect real keys. The OpenBao transit engine shows sign-through-an-API and key wrapping.