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 optional Delete(session, key) and ListKeys(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

  1. 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.
  2. Separate login verification from encryption using envelope keys

    Two classic mistakes break password-encrypted stores right out of the gate:

    1. Reusing a stored password hash as the encryption key: If the server saves H = Hash(password) to verify sign-ins and encrypts values under H, dumping the users table hands the attacker H directly — zero password cracking required!
    2. Encrypting every entry directly under a password-derived key: If Maya stores 100,000 entries and rotates her password, the server has to decrypt and re-encrypt all 100,000 rows (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 (Argon2id or scrypt) + random 16-byte salt: 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_key vs KEK): HKDF (HMAC-based Key Derivation Function) expands master_secret into cryptographically independent subkeys. Even when storage leaks verifier = SHA-256(auth_key), inverting SHA-256 to recover auth_key is infeasible, and auth_key reveals nothing about KEK.
    • Random 256-bit DEK: Carries full 256-bit entropy regardless of password length, and rotating a password only re-wraps this single 32-byte DEK!
  3. 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 row
    

    Concrete storage and cracking numbers:

    • Per-blob byte overhead: AES-GCM prepends a 12-byte nonce and appends a 16-byte authentication tag (28 bytes overhead), so a 100-byte value occupies 12 + 100 + 16 = 128 bytes in value_blob.
    • Offline cracking cost: With scrypt parameters n = 2^17 = 131,072, r = 8, p = 1, each candidate check demands 128 * r * n = 128 MiB of RAM (Argon2id at 19–64 MiB RAM offers comparable resistance). At ~0.2 s per core check, testing 1,000,000 common passwords against one user costs 200,000 core-seconds (~55.6 core-hours), and salt forces 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 without index_key) gives O(1) primary-key lookups without leaking sensitive key labels like "tax_id" or "signing_seed", while name_blob lets ListKeys decrypt key names for the authenticated owner.
  4. Implement registration and constant-time login

    Below is a clean reference implementation using Python's hashlib/hmac/secrets plus AESGCM from cryptography. Notice three subtle hardening details in register and login:

    1. 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.
    2. Uniform timing and error responses: When username is unknown, login still executes derive_keys on a random DUMMY_SALT before raising the identical PermissionError, stopping attackers from enumerating valid usernames via 200 ms vs 0.1 ms response timing.
    3. Constant-time digest check (hmac.compare_digest): Compares all 32 verifier 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
    
  5. Encrypt and authenticate entries in Put and Get

    Every blob is sealed with AEAD (Authenticated Encryption with Associated Data) using AES-256-GCM (or ChaCha20-Poly1305), pairing confidentiality with a 16-byte cryptographic integrity tag in one pass. Three invariants protect Put and Get:

    1. Fresh 96-bit random nonce per seal: Reusing a (key, nonce) pair under AES-GCM is fatal — XORing two ciphertexts exposes plaintext1 XOR plaintext2 and leaks the GHASH authentication key, enabling tag forgery! Per NIST SP 800-38D, up to 2^32 random 96-bit nonces under one key keep collision risk at or below 2^-33 ≈ 1.2 * 10^-10 (2^31 Put operations here because each Put seals both value_blob and name_blob; past that threshold, rotate the DEK or switch to 192-bit-nonce XChaCha20-Poly1305).
    2. 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.
    3. Context binding via Associated Data (AAD): AAD is cleartext context authenticated inside the GCM tag. Binding b"item|" + user_id + b"|" + key_id + b"|v" + ver (plus b"|name" on name_blob) makes unseal reject any attempt to swap two keys' ciphertexts, transplant a blob across users, or substitute name_blob for value_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)
    
  6. 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 SESSIONS to a database table or OS swap partition would leak value_key during a storage breach. Keying SESSIONS by SHA-256(token) also prevents lookup timing leaks and keeps raw tokens out of crash dumps or logs.
    • Bounded TTL, explicit logout, and rate limiting: Logout and session expiration purge the SESSIONS entry 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 DEK under HKDF(token, b"session wrap") and store only (SHA-256(token), wrapped_session_dek) in Redis — an attacker dumping Redis still lacks the client's raw token required to unwrap it!
  7. Handle password changes, corruption, and edge cases

    • Password rotation (O(1) re-wrap vs full DEK re-key): Verify the current password, unwrap DEK, draw a new 16-byte salt, derive (new_auth_key, new_kek) from the new password, atomically update (salt, verifier, wrapped_dek), and evict prior sessions — zero items rows require re-encryption! If the rotation was triggered by a suspected password compromise (where an attacker might also steal an old backup of wrapped_dek), generate a fresh DEK, increment dek_version, and re-encrypt rows lazily or in the background while retaining the old DEK wrapped under new_kek until 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 second recovery_wrapped_dek beside wrapped_dek.
    • Disk bit-rot or active tampering: Any altered bit inside nonce, ciphertext, tag, or AAD makes AESGCM.decrypt raise InvalidTag before returning a single byte of unverified plaintext.
    • Transparent KDF upgrades: Storing kdf_params on each users row lets you raise DEFAULT_KDF work factors over time and transparently re-derive and re-wrap a user's DEK on their next valid login.

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 Argon2id or scrypt — 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 derive auth_key (storing only SHA-256(auth_key) as verifier) and KEK (never persisted).
  • Envelope encryption (KEK wraps random DEK): A random 256-bit per-user DEK guarantees full 256-bit key strength and makes routine password updates O(1) (60-byte rewrite) rather than O(stored entries).
  • AEAD (AES-256-GCM or ChaCha20-Poly1305) on every persisted blob: AEAD (Authenticated Encryption with Associated Data) delivers confidentiality plus a 16-byte tamper-evident tag (28 bytes overhead per blob with a 12-byte nonce).
  • Fresh nonces + Associated Data (AAD): Draw a fresh 96-bit CSPRNG nonce on every seal (up to 2^32 seals = 2^31 Puts per DEK under NIST SP 800-38D, or 192-bit XChaCha20-Poly1305), and bind (user_id, key_id, dek_version) into AAD so blobs cannot be swapped across keys, versions, or accounts.
  • Keyed-hash indexing: Primary-keying rows by key_id = HMAC-SHA256(index_key, key) preserves O(1) point lookups without exposing plaintext key names, paired with an AEAD-sealed name_blob for ListKeys.
  • RAM-only sessions and side-channel hygiene: Index in-memory sessions by SHA-256(token), read user_id strictly from server session state (never request parameters), normalize passwords to Unicode NFC, compare digests via hmac.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) in users for 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 bare SHA-256 hashes 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-GCM leaks plaintext1 XOR plaintext2 and 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) in AAD, valid ciphertexts can be copied across keys or accounts.
  • Trusting caller-passed user_id or fast-failing unknown usernames: Reading user_id from 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 AEAD AAD stops 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's AAD and 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 a DEK subkey. 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, DEK unwrapping, and AEAD sealing/unsealing onto the client device so the server only stores opaque wrapped_dek and ciphertext blobs and never holds KEK or DEK in server RAM. To authenticate logins without sending a password-equivalent secret over the network, either derive a separate client auth_key (salted and hashed once more on the server) or run a PAKE (Password-Authenticated Key Exchange) protocol such as OPAQUE, 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-bit item_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 personal DEK). When Maya shares an entry with Noah, she seals item_key under Noah's authenticated public key alongside her own DEK-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 fresh item_key wrapped only for remaining members and re-encrypts updated values so Noah's previously seen item_key cannot read future writes.

Follow-up questions

Similar questions

More Cloudflare interview questions

All 6 Cloudflare questions →