Password-Protected Encrypted Key-Value Store
System DesignModel answerLast updated
Design a user-authenticated key-value store where values are encrypted at rest using the user's password, covering key derivation, storage layout, and cryptographic trade-offs.
The Problem
You are building a small personal secrets store — think a stripped-down password manager or config vault. Each user registers with a username and password, logs in, and can then store and retrieve arbitrary string values under named keys.
The critical requirement: if someone steals a full copy of the database or storage files, they must not be able to read any stored values without knowing the user's password.
You may treat this as a language-agnostic library or service. You can use any standard cryptographic primitives (AES-GCM, Argon2, HKDF, etc.) from an existing library — you do not need to implement ciphers from scratch.
API surface
Register(username, password)
Login(username, password) → session_token
Put(session_token, key, value)
Get(session_token, key) → value
Delete(session_token, key) // optional
ListKeys(session_token) → [key] // optional, discuss trade-offs
Requirements
- No plaintext passwords in storage. The system must tolerate a full database leak without exposing credentials.
- Values are unreadable without the user's password. Someone with the raw storage rows cannot recover any value.
- Tampering is detectable. If a stored ciphertext is modified, the system should refuse to return a result rather than silently returning corrupted data.
- Password changes should be practical. Changing a password must not require re-encrypting every stored value.
- Users are isolated. One user's ciphertexts cannot be transplanted into another user's account.
Threat model
Assume an attacker can:
- Obtain a full snapshot of persistent storage (all rows, all files, all backups).
Assume an attacker cannot:
- Read process memory while the service is running.
- Observe network traffic (TLS is assumed).
What to cover in your answer
- Data model: what you store per user and per item, including every piece of metadata needed to decrypt later.
- Cryptographic choices: which algorithms, why, and what pitfalls they avoid.
- Key hierarchy: how you get from a raw password to the keys that actually encrypt data.
- Core flows: Register, Login, Put, Get step by step.
- Edge cases: wrong password, password change, storage corruption, multi-user isolation, key-name confidentiality.
Where helpful, include a code sketch (any language) to make the flows concrete.
Hints
Hint 1
Start by separating two distinct jobs: proving the user knows their password (authentication) and deriving the key that encrypts their data. These should produce independent keys from the same password-derivation step — not share a single output.
Hint 2
A password change shouldn't mean re-encrypting every stored value. Think about what would make that practical: if the data is encrypted under a random key, and that random key is itself encrypted under the password, only one small blob needs to change.
Hint 3
Every encryption operation needs a fresh random nonce/IV. Think about what goes wrong if two writes share a nonce under AES-GCM, and why a random-per-write strategy avoids it. Also consider what authenticated encryption gives you that plain AES-CBC does not.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach overview
The core challenge is that a password is not directly usable as an encryption key — it's a low-entropy, human-memorable string, and it needs to serve two separate purposes: proving identity and protecting data. A strong solution separates these concerns cleanly and adds a key-wrapping layer so that the encrypted values themselves never need to change when the user updates their password.
Four properties define a correct design:
- Password verification is separate from key derivation. Derive two independent subkeys from one KDF output: one to verify the password, one as a key-encryption key (KEK).
- A slow, salted KDF is used on the password. This makes offline guessing expensive.
- Data is encrypted under a random per-user key (DEK), not directly under the password. Only the wrapped DEK changes on a password reset.
- Authenticated encryption with a fresh nonce per write. This detects tampering and prevents nonce-reuse attacks.
Cryptographic building blocks
| Job | Choice | Reason |
|---|---|---|
| Password → key material | Argon2id (e.g. 64 MiB memory, 3 iterations, 16-byte random salt) | Memory-hard KDF; slows GPU/ASIC brute force; per-user salt defeats precomputed tables |
| Splitting one secret into two | HKDF-SHA256 with distinct info labels | Produces cryptographically independent auth key and KEK from one master |
| Encrypting values and wrapping keys | AES-256-GCM (or XChaCha20-Poly1305) | AEAD: provides both confidentiality and integrity; tampering causes decryption to fail loudly |
| Nonces | 96-bit random, generated fresh per encryption | Avoids nonce reuse, which in GCM is catastrophic — it leaks the XOR of plaintexts and breaks authentication |
| Session tokens | 256-bit CSPRNG output | Unguessable; optionally store only its hash server-side |
Common mistakes to avoid explicitly:
- Using the password hash as the encryption key. Anyone with the database then has the key.
- Storing the password encrypted rather than hashed. Encryption is reversible — only a one-way verifier belongs in storage.
- Using ECB mode or deterministic encryption. Identical values produce identical ciphertexts, leaking structure.
- Using a counter or timestamp as a nonce. A database restore rolls the counter back, guaranteeing reuse.
- Using unauthenticated CBC. Vulnerable to padding oracle attacks and silent data corruption.
Key hierarchy
password ──Argon2id(user_salt)──► master_key (32 bytes)
├── HKDF(master, info="auth") ──► auth_key ──SHA-256──► stored verifier
├── HKDF(master, info="kek") ──► KEK
│ └── AES-GCM wrap ──► wrapped_DEK (stored)
└── DEK (random 32 bytes, generated at registration)
└── AES-GCM(nonce_i) ──► each stored value
└── HKDF(DEK, info="names") ──► name_key ──HMAC──► key_id (optional)
The DEK is random and never changes. A password change derives a new KEK and rewraps the same DEK — one row update, regardless of how many values exist.
Data model
users table
| Column | Contents |
|---|---|
username | Primary key |
user_id | Random stable identifier |
kdf_params | Algorithm, memory cost, iterations, version |
salt | 16-byte random, per user |
verifier | SHA-256(auth_key) |
wrap_nonce | Nonce used to wrap the DEK |
wrapped_dek | AES-GCM ciphertext of the DEK (includes tag) |
items table
| Column | Contents |
|---|---|
user_id | Foreign key |
key_id | HMAC(name_key, key) or plaintext key name |
nonce | 12-byte random, fresh per write |
ciphertext | AES-GCM output including the authentication tag |
format_version | For future migration |
Primary key: (user_id, key_id).
Associated data (AAD) binds each ciphertext to its context. For item encryption: AAD = user_id || key_id || format_version. For the wrapped DEK: AAD = user_id. This means a row copied to another user's account or renamed key will fail decryption — the tag won't verify.
Sessions live in memory only: token → (user_id, DEK, expiry).
Core flows
Register: Generate salt, run Argon2id to get master_key, derive auth_key and KEK via HKDF. Generate a random DEK. Wrap it under KEK with a fresh nonce. Store verifier, salt, KDF params, wrap_nonce, and wrapped_dek.
Login: Retrieve the user's salt and KDF params, recompute master_key and auth_key. Compare SHA-256(auth_key) to the stored verifier using a constant-time comparison (prevents timing attacks). Unwrap the DEK — the GCM tag provides a second integrity check. Mint a random session token and cache (user_id, DEK) in the session map with a TTL.
Put: Look up the session and resolve user_id and DEK. Compute key_id. Generate a 12-byte random nonce. Encrypt the value with AAD. Upsert (user_id, key_id, nonce, ciphertext).
Get: Look up session and key_id. Fetch the row. Decrypt using the nonce and AAD. If the tag check fails, raise an integrity error — never return partial or unauthenticated data.
Code sketch (Python)
import os, hmac, hashlib, secrets, time
from argon2.low_level import hash_secret_raw, Type
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes
def derive_subkey(master: bytes, label: bytes) -> bytes:
return HKDF(hashes.SHA256(), 32, salt=None, info=label).derive(master)
def stretch(password: str, salt: bytes) -> bytes:
return hash_secret_raw(password.encode(), salt,
time_cost=3, memory_cost=65536,
parallelism=1, hash_len=32, type=Type.ID)
class EncryptedKV:
def __init__(self):
self.users, self.items, self.sessions = {}, {}, {}
def register(self, username: str, password: str) -> None:
salt = os.urandom(16)
user_id = secrets.token_hex(16)
master = stretch(password, salt)
kek = derive_subkey(master, b"kek")
auth_key = derive_subkey(master, b"auth")
dek = AESGCM.generate_key(256)
wrap_nonce = os.urandom(12)
wrapped_dek = AESGCM(kek).encrypt(wrap_nonce, dek, user_id.encode())
self.users[username] = {
"user_id": user_id, "salt": salt,
"verifier": hashlib.sha256(auth_key).digest(),
"wrap_nonce": wrap_nonce, "wrapped_dek": wrapped_dek,
}
def login(self, username: str, password: str) -> str:
u = self.users.get(username)
if u is None:
raise PermissionError("invalid credentials")
master = stretch(password, u["salt"])
auth_key = derive_subkey(master, b"auth")
if not hmac.compare_digest(hashlib.sha256(auth_key).digest(), u["verifier"]):
raise PermissionError("invalid credentials")
dek = AESGCM(derive_subkey(master, b"kek")).decrypt(
u["wrap_nonce"], u["wrapped_dek"], u["user_id"].encode())
token = secrets.token_urlsafe(32)
self.sessions[token] = (u["user_id"], dek, time.time() + 3600)
return token
def _session(self, token: str):
s = self.sessions.get(token)
if not s or time.time() > s[2]:
raise PermissionError("session expired")
return s[0], s[1] # user_id, dek
def put(self, token: str, key: str, value: str) -> None:
user_id, dek = self._session(token)
key_id = hmac.new(dek, key.encode(), hashlib.sha256).hexdigest()
nonce = os.urandom(12)
aad = f"{user_id}:{key_id}:v1".encode()
ct = AESGCM(dek).encrypt(nonce, value.encode(), aad)
self.items[(user_id, key_id)] = (nonce, ct)
def get(self, token: str, key: str) -> str:
user_id, dek = self._session(token)
key_id = hmac.new(dek, key.encode(), hashlib.sha256).hexdigest()
entry = self.items.get((user_id, key_id))
if entry is None:
raise KeyError(key)
nonce, ct = entry
aad = f"{user_id}:{key_id}:v1".encode()
return AESGCM(dek).decrypt(nonce, ct, aad).decode()
Edge cases
Wrong password: Argon2id runs to completion before the verifier check fails. This prevents short-circuit timing leaks. Return the same error message for unknown user and wrong password — no user enumeration.
Password change: Re-derive a new KEK from the new password, unwrap the existing DEK using the old KEK, rewrap it under the new KEK, and update the wrap_nonce, wrapped_dek, and verifier columns atomically. All stored item ciphertexts are unchanged.
Corrupted ciphertext: AES-GCM tag verification fails with an explicit error. The system never returns partially decrypted output.
Multi-user isolation: The AAD includes user_id on every encryption. Moving a row from one user's namespace to another's causes authentication tag failure on decrypt.
Key-name confidentiality: Storing HMAC(name_key, key) as key_id hides plaintext key names in storage. The trade-off is that ListKeys cannot return human-readable names without separately storing an encrypted name blob per row, or an encrypted index.
ListKeys design choice: Either store an extra encrypted plaintext name column per row (leaks count and approximate name lengths), or maintain a single encrypted index blob per user (atomic updates required, but names stay entirely hidden). Neither option is free — state the trade-off rather than picking one silently.