Password-Protected Key-Value Store with At-Rest Encryption
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
Architect a standalone, multi-user key-value storage service or library (in any programming language, relying on vetted cryptographic libraries rather than custom cipher implementations) where accounts sign in with passwords and every persisted value remains unreadable on disk without its owner's password.
Your design should support an API surface along the lines of:
Register(username, password)— Create a new user account without ever writing plaintext passwords to persistent storage.Login(username, password) -> session— Authenticate credentials and issue an active session handle or token.Put(session, key, value)— Persist an encrypted entry scoped to the signed-in account.Get(session, key) -> value— Decrypt and return the entry belonging to the signed-in account (with optionalDelete(session, key)andListKeys(session)).
Assume an offline storage-compromise adversary who captures a full snapshot of persistent storage (database tables, disk files, or backups), while live server RAM during active user sessions remains out of reach. Watch out for classic applied-cryptography traps such as reusing login hashes directly as encryption keys, deterministic ciphertexts, nonce/IV collisions, and unauthenticated ciphertexts.
Scope & Expectations
- Storage schema & session lifecycle: Lay out what credential records, encrypted blobs, and non-secret metadata live on disk versus what key material stays exclusively in volatile memory during an authenticated session.
- Key hierarchy & cryptographic primitives: Justify your choices for password-based key derivation, domain separation between login verification and data decryption, authenticated encryption, and per-write nonce generation.
- Pitfall resistance: Show why identical values never produce identical ciphertexts, why database dumps never hand an attacker a ready-made decryption key, and why swapping ciphertexts across keys or accounts fails closed.
- Operational edge cases: Address password changes without mass re-encryption, wrong-password attempts, bit-rot or active tampering on disk, and strict tenant isolation.
Step-by-step walkthrough
Pin down the threat model and honest security boundaries
Under our threat model, an adversary captures a complete copy of persistent storage (database tables, disk images, or backups), without reading live server RAM while an account has an active session. From that premise, the store must uphold four hard guarantees:
- No plaintext or cheaply crackable credentials: Persisted login material must force an offline attacker to spend heavy CPU and memory on every password guess.
- Zero unencrypted secrets on disk: Neither plaintext values nor any unwrapped key capable of decrypting them may ever be written to persistent storage.
- Tamper and corruption detection: Bit-flips on disk, truncated blobs, or valid ciphertexts copied from another key or user must fail verification rather than returning corrupted bytes.
- Strict per-account isolation: Possessing Maya's password or session token must confer zero ability to read, overwrite, or match Noah's keys or values.
State inherent cryptographic limits up front so an interviewer sees clear threat-modeling judgment:
- Offline password guessing can only be slowed, never eliminated: Anyone holding a database snapshot can test candidate passwords locally; a weak password like
"123456"will still fall, so a memory-hard key derivation function must be paired with minimum password-entropy rules. - Record metadata still leaks shape: Entry counts, approximate value byte lengths, and modification timestamps remain observable on disk unless values are padded to fixed block buckets.
Separate login verification from encryption using envelope keys
Two classic mistakes break password-encrypted stores right out of the gate:
- Reusing a stored password hash as the encryption key: If the server saves
H = Hash(password)to verify sign-ins and encrypts values underH, dumping theuserstable hands the attackerHdirectly — zero password cracking required! - Encrypting every entry directly under a password-derived key: If Maya stores
100,000entries and rotates her password, the server has to decrypt and re-encrypt all100,000rows (and a crash mid-flight leaves rows split across two keys).
We avoid both traps via envelope encryption (encrypting records with a random data-encryption key (DEK), while encrypting only that small DEK under a password-derived key-encryption key (KEK)) combined with domain-separated key derivation:
password (NFC-normalized) + 16-byte per-user random salt | | Slow, memory-hard KDF (Argon2id or scrypt) v master_secret (32 bytes — NEVER written to disk) | | HKDF-SHA256 with distinct context labels +── label "kv auth v1" ──> auth_key ──SHA-256──> verifier (32B, STORED for sign-in check) | +── label "kv kek v1" ──> KEK (32B — NEVER stored; lives in RAM only during login) | | AES-256-GCM encrypts/decrypts v wrapped_dek (60B, STORED) <═══ DEK (32 random bytes generated once) | | HKDF-SHA256 subkeys +──> value_key (AES-256-GCM values) +──> index_key (HMAC-SHA256 key names)Why each stage in this hierarchy matters:
- Memory-hard KDF (
Argon2idorscrypt) + random16-bytesalt: A KDF (key derivation function) intentionally consumes tens of megabytes of RAM and tens of milliseconds of CPU per password evaluation, while the per-account salt defeats precomputed tables and prevents testing one guess across all accounts simultaneously. - HKDF split (
auth_keyvsKEK): HKDF (HMAC-based Key Derivation Function) expandsmaster_secretinto cryptographically independent subkeys. Even when storage leaksverifier = SHA-256(auth_key), inverting SHA-256 to recoverauth_keyis infeasible, andauth_keyreveals nothing aboutKEK. - Random
256-bitDEK: Carries full256-bit entropy regardless of password length, and rotating a password only re-wraps this single32-byteDEK!
- Reusing a stored password hash as the encryption key: If the server saves
Design the persistence schema and concrete byte budgets
Table: users (1 row per registered account) ────────────────────────────────────────────────────────────────────────────────────────── user_id 16 random bytes (immutable primary key; survives username renames) username TEXT UNIQUE kdf_params JSON, e.g. {"alg": "scrypt", "n": 131072, "r": 8, "p": 1} salt 16 random bytes verifier 32 bytes = SHA-256(auth_key) wrapped_dek 60 bytes = nonce(12B) || AES-256-GCM(KEK, DEK, aad)(32B + 16B tag) dek_version INTEGER = 1, 2, ... (incremented only when rotating the DEK itself) Table: items (1 row per stored entry; primary key = (user_id, key_id)) ────────────────────────────────────────────────────────────────────────────────────────── user_id 16 bytes key_id 32 bytes = HMAC-SHA256(index_key, key_utf8) name_blob bytes = nonce(12B) || AES-256-GCM(value_key, key_utf8, aad_name) value_blob bytes = nonce(12B) || AES-256-GCM(value_key, value_bytes, aad_val) dek_version INTEGER = DEK version that encrypted this rowConcrete storage and cracking numbers:
- Per-blob byte overhead: AES-GCM prepends a
12-byte nonce and appends a16-byte authentication tag (28bytes overhead), so a100-byte value occupies12 + 100 + 16 = 128bytes invalue_blob. - Offline cracking cost: With
scryptparametersn = 2^17 = 131,072,r = 8,p = 1, each candidate check demands128 * r * n = 128 MiBof RAM (Argon2idat19–64 MiBRAM offers comparable resistance). At~0.2 sper core check, testing1,000,000common passwords against one user costs200,000core-seconds (~55.6core-hours), andsaltforces the attacker to start over per account. - Key-name privacy: Indexing rows by
key_id = HMAC-SHA256(index_key, key)(an HMAC, a keyed hash indistinguishable from random bytes withoutindex_key) givesO(1)primary-key lookups without leaking sensitive key labels like"tax_id"or"signing_seed", whilename_blobletsListKeysdecrypt key names for the authenticated owner.
- Per-blob byte overhead: AES-GCM prepends a
Implement registration and constant-time login
Below is a clean reference implementation using Python's
hashlib/hmac/secretsplusAESGCMfromcryptography. Notice three subtle hardening details inregisterandlogin:- Unicode normalization (
NFC): Accented characters like"é"have multiple Unicode encodings; normalizing first ensures a password typed on macOS unlocks entries created on Linux or Windows. - Uniform timing and error responses: When
usernameis unknown,loginstill executesderive_keyson a randomDUMMY_SALTbefore raising the identicalPermissionError, stopping attackers from enumerating valid usernames via200 msvs0.1 msresponse timing. - Constant-time digest check (
hmac.compare_digest): Compares all32verifier bytes without early-exiting on the first mismatched byte.
import hashlib import hmac import secrets import time import unicodedata from cryptography.hazmat.primitives.ciphers.aead import AESGCM DEFAULT_KDF = {"alg": "scrypt", "n": 2**17, "r": 8, "p": 1} DUMMY_SALT = secrets.token_bytes(16) # SESSIONS lives in process RAM only: sha256(token) -> (user_id, dek_ver, value_key, index_key, exp) SESSIONS = {} def hkdf_sha256(key_material: bytes, info: bytes, length: int = 32) -> bytes: """RFC 5869 HKDF-SHA256: extract a pseudorandom key, then expand with context label `info`.""" if length > 255 * 32: raise ValueError("HKDF output length exceeds RFC 5869 limit") prk = hmac.new(b"\x00" * 32, key_material, hashlib.sha256).digest() out, prev_block, counter = b"", b"", 1 while len(out) < length: prev_block = hmac.new( prk, prev_block + info + bytes([counter]), hashlib.sha256 ).digest() out += prev_block counter += 1 return out[:length] def derive_keys(password: str, salt: bytes, kdf: dict): normalized_pw = unicodedata.normalize("NFC", password).encode("utf-8") # Raise OpenSSL's 32 MiB default maxmem ceiling so 128 MiB scrypt parameters succeed. master = hashlib.scrypt( normalized_pw, salt=salt, n=kdf["n"], r=kdf["r"], p=kdf["p"], maxmem=256 * 1024 * 1024, dklen=32, ) auth_key = hkdf_sha256(master, b"kv auth v1") kek = hkdf_sha256(master, b"kv kek v1") return auth_key, kek def seal(key: bytes, plaintext: bytes, aad: bytes) -> bytes: nonce = secrets.token_bytes(12) # Fresh OS CSPRNG 96-bit nonce on every single write return nonce + AESGCM(key).encrypt(nonce, plaintext, aad) def unseal(key: bytes, blob: bytes, aad: bytes) -> bytes: # Require at least 12-byte nonce + 16-byte GCM authentication tag before slicing. if len(blob) < 28: raise ValueError("corrupted or truncated ciphertext") return AESGCM(key).decrypt(blob[:12], blob[12:], aad) def register(db, username: str, password: str) -> None: if db.find_user(username) is not None: raise ValueError("username already registered") user_id = secrets.token_bytes(16) salt = secrets.token_bytes(16) auth_key, kek = derive_keys(password, salt, DEFAULT_KDF) dek = secrets.token_bytes(32) db.insert_user({ "user_id": user_id, "username": username, "kdf": DEFAULT_KDF, "salt": salt, "verifier": hashlib.sha256(auth_key).digest(), "wrapped_dek": seal(kek, dek, b"dek|" + user_id + b"|v1"), "dek_version": 1, }) def login(db, username: str, password: str) -> bytes: row = db.find_user(username) if row is None: derive_keys(password, DUMMY_SALT, DEFAULT_KDF) raise PermissionError("invalid username or password") auth_key, kek = derive_keys(password, row["salt"], row["kdf"]) expected_verifier = hashlib.sha256(auth_key).digest() if not hmac.compare_digest(expected_verifier, row["verifier"]): raise PermissionError("invalid username or password") dek_aad = b"dek|" + row["user_id"] + b"|v" + str(row["dek_version"]).encode() dek = unseal(kek, row["wrapped_dek"], dek_aad) token = secrets.token_bytes(32) SESSIONS[hashlib.sha256(token).digest()] = ( row["user_id"], row["dek_version"], hkdf_sha256(dek, b"kv values v1"), hkdf_sha256(dek, b"kv index v1"), time.time() + 3600, ) return token- Unicode normalization (
Encrypt and authenticate entries in Put and Get
Every blob is sealed with AEAD (Authenticated Encryption with Associated Data) using
AES-256-GCM(orChaCha20-Poly1305), pairing confidentiality with a16-byte cryptographic integrity tag in one pass. Three invariants protectPutandGet:- Fresh
96-bit random nonce per seal: Reusing a(key, nonce)pair under AES-GCM is fatal — XORing two ciphertexts exposesplaintext1 XOR plaintext2and leaks the GHASH authentication key, enabling tag forgery! Per NIST SP 800-38D, up to2^32random96-bit nonces under one key keep collision risk at or below2^-33 ≈ 1.2 * 10^-10(2^31Putoperations here because eachPutseals bothvalue_blobandname_blob; past that threshold, rotate the DEK or switch to192-bit-nonceXChaCha20-Poly1305). - Randomized, non-deterministic ciphertexts: Drawing a fresh nonce on every write ensures storing
"approved"under two keys (or overwriting a key with the same payload) yields completely unrelated ciphertexts — unlike ECB mode or a static IV. - Context binding via Associated Data (
AAD): AAD is cleartext context authenticated inside the GCM tag. Bindingb"item|" + user_id + b"|" + key_id + b"|v" + ver(plusb"|name"onname_blob) makesunsealreject any attempt to swap two keys' ciphertexts, transplant a blob across users, or substitutename_blobforvalue_blob!
def _require_session(token: bytes): session_key = hashlib.sha256(token).digest() entry = SESSIONS.get(session_key) if entry is None or entry[4] < time.time(): SESSIONS.pop(session_key, None) raise PermissionError("invalid or expired session") return entry def _item_aad(user_id: bytes, key_id: bytes, dek_version: int) -> bytes: # Fixed-width 16-byte user_id and 32-byte key_id prevent boundary ambiguity. return b"item|" + user_id + b"|" + key_id + b"|v" + str(dek_version).encode() def put(db, token: bytes, key: str, value: bytes) -> None: user_id, dek_version, value_key, index_key, _ = _require_session(token) key_bytes = key.encode("utf-8") key_id = hmac.new(index_key, key_bytes, hashlib.sha256).digest() aad = _item_aad(user_id, key_id, dek_version) db.upsert_item(user_id, key_id, { "value_blob": seal(value_key, value, aad), "name_blob": seal(value_key, key_bytes, aad + b"|name"), "dek_version": dek_version, }) def get(db, token: bytes, key: str) -> bytes: # Always read user_id from the authenticated server session, NEVER from caller arguments! user_id, _, value_key, index_key, _ = _require_session(token) key_id = hmac.new(index_key, key.encode("utf-8"), hashlib.sha256).digest() row = db.find_item(user_id, key_id) if row is None: raise KeyError(key) aad = _item_aad(user_id, key_id, row["dek_version"]) return unseal(value_key, row["value_blob"], aad)- Fresh
Keep unwrapped session keys strictly in volatile memory
Client Server RAM (SESSIONS) Disk / DB ────── ───────────────────── ───────── token (32 random bytes) ───> SHA-256(token) -> (user_id, users + items (held only by client) value_key, index_key, expires_at) (ciphertext ONLY!)- Never write unwrapped session keys to disk: Persisting
SESSIONSto a database table or OS swap partition would leakvalue_keyduring a storage breach. KeyingSESSIONSbySHA-256(token)also prevents lookup timing leaks and keeps raw tokens out of crash dumps or logs. - Bounded TTL, explicit logout, and rate limiting:
Logoutand session expiration purge theSESSIONSentry from RAM, while per-IP and per-account rate limiters throttle online brute-force attempts. - Multi-node horizontal scaling: When stateless app servers share a Redis session store, wrap the session's
DEKunderHKDF(token, b"session wrap")and store only(SHA-256(token), wrapped_session_dek)in Redis — an attacker dumping Redis still lacks the client's rawtokenrequired to unwrap it!
- Never write unwrapped session keys to disk: Persisting
Handle password changes, corruption, and edge cases
- Password rotation (
O(1)re-wrap vs full DEK re-key): Verify the current password, unwrapDEK, draw a new16-bytesalt, derive(new_auth_key, new_kek)from the new password, atomically update(salt, verifier, wrapped_dek), and evict prior sessions — zeroitemsrows require re-encryption! If the rotation was triggered by a suspected password compromise (where an attacker might also steal an old backup ofwrapped_dek), generate a freshDEK, incrementdek_version, and re-encrypt rows lazily or in the background while retaining the oldDEKwrapped undernew_kekuntil migration finishes. - Lost password: Because there is no server master backdoor, losing a password permanently locks the account unless registration optionally issued a printable
256-bit recovery code and stored a secondrecovery_wrapped_dekbesidewrapped_dek. - Disk bit-rot or active tampering: Any altered bit inside
nonce, ciphertext,tag, orAADmakesAESGCM.decryptraiseInvalidTagbefore returning a single byte of unverified plaintext. - Transparent KDF upgrades: Storing
kdf_paramson eachusersrow lets you raiseDEFAULT_KDFwork factors over time and transparently re-derive and re-wrap a user'sDEKon their next validlogin.
- Password rotation (
Intuition & how it works
Picture the store as a bank vault holding private safe-deposit boxes. Each account's stored values sit inside steel boxes locked by a random 256-bit master key (DEK, or data-encryption key), while that master key itself rests inside a tiny lockbox at the front counter whose combination (KEK, or key-encryption key) is computed in memory only when the owner enters their password — and the lobby guard checks a separate one-way badge (verifier) to admit the owner! This two-layer design is envelope encryption (encrypting bulk records with a random key, and encrypting only that random key under a password-derived key): if the entire database leaks, every value and wrapped_dek stay encrypted, yet rotating a password only re-seals the 60-byte wrapped_dek instead of re-encrypting thousands of records.
Why do simpler shortcuts fail catastrophically? Hashing the password once and both storing that digest for login checks and passing it as your AES key means anyone who dumps the users table steals the decryption key directly! Encrypting entries with deterministic AES-ECB or a static initialization vector (IV) exposes whenever two keys hold identical values (and reusing a nonce in AES-GCM lets an attacker XOR ciphertexts to recover plaintexts and forge integrity tags). And using unauthenticated encryption (such as raw AES-CBC without an integrity tag) or omitting account/key context lets an attacker with disk access silently flip bits or transplant Maya's "api_secret" ciphertext into "display_name".
Trace Maya signing up, storing a 5-byte PIN, reading it back, and rotating her password:
1. Register("maya", pw):
salt (16B) + pw ──scrypt──> master ──HKDF──> verifier (stored) + KEK (RAM only)
random DEK (32B) sealed under KEK ────────> wrapped_dek (12B nonce + 32B + 16B tag = 60B)
2. Login("maya", pw):
re-derives verifier (matches!) + KEK -> unwraps DEK -> caches value_key, index_key in RAM
3. Put(token, "pin", b"48219"):
key_id = HMAC(index_key, "pin"); seals b"48219" with fresh 12B nonce + AAD(maya, key_id, v1)
-> writes 12 + 5 + 16 = 33-byte value_blob to disk
4. ChangePassword(old_pw, new_pw):
unwraps DEK with old KEK, draws fresh salt, re-seals same 32B DEK under new KEK (0 items touched!)
Key points
- Honor the threat model and state its limits: Against a full persistent-storage leak (without live RAM capture), nothing persisted on disk may decrypt data by itself, and offline guessing must be throttled via a salted, memory-hard KDF (key derivation function) like
Argon2idorscrypt— while noting weak passwords require password policy and byte-length leaks require block padding if sensitive. - Split verification from encryption via HKDF: Run the expensive KDF once to obtain
master, then apply HKDF (HMAC-based Key Derivation Function) with distinct context strings to deriveauth_key(storing onlySHA-256(auth_key)asverifier) andKEK(never persisted). - Envelope encryption (
KEKwraps randomDEK): A random256-bit per-userDEKguarantees full256-bit key strength and makes routine password updatesO(1)(60-byte rewrite) rather thanO(stored entries). - AEAD (
AES-256-GCMorChaCha20-Poly1305) on every persisted blob: AEAD (Authenticated Encryption with Associated Data) delivers confidentiality plus a16-byte tamper-evident tag (28bytes overhead per blob with a12-byte nonce). - Fresh nonces + Associated Data (
AAD): Draw a fresh96-bit CSPRNG nonce on every seal (up to2^32seals =2^31Puts per DEK under NIST SP 800-38D, or192-bitXChaCha20-Poly1305), and bind(user_id, key_id, dek_version)intoAADso blobs cannot be swapped across keys, versions, or accounts. - Keyed-hash indexing: Primary-keying rows by
key_id = HMAC-SHA256(index_key, key)preservesO(1)point lookups without exposing plaintext key names, paired with an AEAD-sealedname_blobforListKeys. - RAM-only sessions and side-channel hygiene: Index in-memory sessions by
SHA-256(token), readuser_idstrictly from server session state (never request parameters), normalize passwords to UnicodeNFC, compare digests viahmac.compare_digest, and run a dummy KDF on missing usernames to equalize login latency.
Common mistakes
- Using the stored password verifier as the encryption key: Persisting
scrypt(password, salt)inusersfor login checks and encrypting values under that same digest lets anyone with a database dump decrypt every entry immediately without guessing passwords. - Fast hashes (
SHA-256,MD5) or missing per-account salts: Commodity GPUs evaluate billions of bareSHA-256hashes per second, and omitting salts lets one guess or rainbow table attack every user at once. - Nonce / IV reuse: A constant IV, a counter reset after process restart, or a VM snapshot rollback under
AES-GCMleaksplaintext1 XOR plaintext2and compromises the authentication tag key. - Deterministic value encryption (AES-ECB or fixed IV): Leaks whenever two keys or accounts hold identical payloads and whether an overwrite changed a value.
- Unauthenticated encryption (bare AES-CBC or AES-CTR) or empty
AAD: Without an integrity tag, disk corruption or padding-oracle tampering goes unnoticed; without(user_id, key_id)inAAD, valid ciphertexts can be copied across keys or accounts. - Trusting caller-passed
user_idor fast-failing unknown usernames: Readinguser_idfrom request arguments bypasses cryptography altogether, while returning instant"unknown user"errors enables account enumeration.
Follow-up questions
- How can the system detect rollback attacks when an adversary also gains write access to disk? Binding
(user_id, key_id)into AEADAADstops forged or transplanted ciphertexts, yet an attacker with write access can still replace a row with a genuine older ciphertext recorded yesterday for that same key! To catch per-key replays, embed a monotonic write generation counter inside each row'sAADand maintain an authenticated digest over all current counters — such as a Merkle tree (a binary hash tree whose root digest commits to every leaf key and generation counter) MACed under aDEKsubkey. Because an attacker could still revert the entire database and root digest together, preventing full-store rollback requires anchoring that root counter outside untrusted disk — either on the client device or inside a hardware TPM (Trusted Platform Module) monotonic counter. - How does the architecture shift if the server itself is untrusted and must never observe plaintext values or passwords? Push KDF execution,
DEKunwrapping, and AEAD sealing/unsealing onto the client device so the server only stores opaquewrapped_dekand ciphertext blobs and never holdsKEKorDEKin server RAM. To authenticate logins without sending a password-equivalent secret over the network, either derive a separate clientauth_key(salted and hashed once more on the server) or run a PAKE (Password-Authenticated Key Exchange) protocol such asOPAQUE, proving password knowledge mutually without transmitting the password. In exchange, you give up server-side plaintext indexing, make lost passwords unrecoverable without a client-saved recovery code, and must secure client code delivery. - How would you let one account grant another user read/write access to selected keys without revealing their password? Encrypt each shared item or namespace under its own random
256-bititem_key, and provision every account at sign-up with an asymmetric key pair (a public encryption/verification key pair whose private key is sealed under the owner's personalDEK). When Maya shares an entry with Noah, she sealsitem_keyunder Noah's authenticated public key alongside her ownDEK-wrapped copy (signing the grant so a compromised store cannot swap in a rogue public key for Noah). When revoking Noah later, Maya generates a freshitem_keywrapped only for remaining members and re-encrypts updated values so Noah's previously seenitem_keycannot read future writes.
Follow-up questions
- How can the system detect rollback attacks when an adversary also gains write access to disk?
- How does the architecture shift if the server itself is untrusted and must never observe plaintext values or passwords?
- How would you let one account grant another user read/write access to selected keys without revealing their password?
Similar questions
- Systematic Production Debugging Workflow
- Shipping Changes to Live Production Systems
- Global Source-Encrypted Audit Log Pipeline
- Prefix-Rule Sliding-Window Rate Limiter
- Walking Through a Recent Engineering Project
- Dynamic Dynasty Succession Without an Initial Monarch