← Back to section · Tutorials & Labs
Project: The Cryptographic Core of a Password Vault (Teaching Implementation)
Derive a key from a master password with scrypt and seal the whole vault file with AES-256-GCM: implement a minimal working password vault core, with an itemized account of how it falls short of a production vault.
Strip the interface and sync features from any password manager and the cryptographic core that remains is surprisingly small: one slow key derivation function, one authenticated symmetric cipher, one file format. This project implements that core. The user sets a master password; the program derives a 256-bit master key from the password and a random salt with hashlib.scrypt, then encrypts the entire vault — a JSON list of entries — into a single file with AES-256-GCM. Unlocking reverses the process, and a wrong password or a tampered file simply fails decryption. Its value is turning “what does a vault actually do cryptographically” from a black box into a white one. The boundary goes first, and more sternly than in any other article in this series: this is a teaching implementation and must never store real passwords. It has no memory wiping, no automatic clipboard clearing, no anti-peeking unlock interface, and no professional audit. Real passwords belong in mature products such as Bitwarden or KeePassXC — whose value lies precisely in the parts this project omits.
Goal and Architecture
The core exposes four operations. create makes a new vault: set the master password, generate a random salt, and write the encrypted file of an empty vault. unlock takes the master password, derives the key, decrypts, and reads the entries into memory. add and list operate on entries while unlocked. lock re-serializes and re-encrypts the whole vault back to disk and drops the plaintext references from memory. The file format is a single-line JSON envelope with four fields: kdf (the algorithm name and the scrypt n/r/p parameters), salt (Base64 of a 16-byte random salt), nonce (the 12-byte GCM nonce), and ct (Base64 of the ciphertext and authentication tag). Writing the KDF parameters into the file header rather than hard-coding them keeps a door open for future parameter upgrades: unlocking derives with whatever parameters the file records, so old files still open after parameters are raised.
The architecture deliberately keeps the simple “one ciphertext for the whole vault” model: no per-entry encryption, no searchable index. That differs substantially from real products, which need entry-level sync and sharing, but it is right for teaching — the trust boundary is unmistakable. With the master key, everything opens; without it, the file is a blob of random bytes. The core’s only security assumptions are that the scrypt parameters are expensive enough and that the master password itself is strong enough. The second assumption is outside the code’s control, which is why the tutorial must show the reader the password-strength arithmetic.
Walking Through the Core Code
Derivation and sealing, entirely from the standard library and cryptography:
import hashlib, os, json, base64
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
SCRYPT = {"n": 2**15, "r": 8, "p": 1}
def derive_key(password: str, salt: bytes, params: dict) -> bytes:
return hashlib.scrypt(password.encode(), salt=salt,
n=params["n"], r=params["r"], p=params["p"],
dklen=32, maxmem=128 * 1024 * 1024)
def seal(password: str, vault_obj: dict) -> dict:
salt = os.urandom(16)
key = derive_key(password, salt, SCRYPT)
nonce = os.urandom(12)
plaintext = json.dumps(vault_obj).encode()
ct = AESGCM(key).encrypt(nonce, plaintext, None)
return {"kdf": {"alg": "scrypt", **SCRYPT},
"salt": base64.b64encode(salt).decode(),
"nonce": base64.b64encode(nonce).decode(),
"ct": base64.b64encode(ct).decode()}
Three details. First, maxmem must be given explicitly and generously: scrypt at n=2^15, r=8 needs roughly 32 MB of memory, and OpenSSL’s default cap makes derivation fail outright — a toll everyone pays once when using scrypt from the standard library. Second, notice that the design contains no “password hash” anywhere: checking the master password means deriving the key and attempting decryption to see whether the GCM tag passes. Storing a separate password hash hands attackers one more offline-cracking target — the most common superfluous addition in beginner vault implementations. Third, lock must re-randomize both salt and nonce and re-encrypt in full rather than patching the ciphertext under the old parameters: reusing a nonce under the same key directly destroys GCM’s security, and in the change-password scenario an unchanged salt raises the further question of old copies of the file still opening under the old password — a lifecycle issue the tutorial spells out rather than hides.
Running and Verifying
Four acceptance checks. First, round-trip: create a vault, add three entries, lock, unlock, and the entries read back identical to what was written. Second, wrong password: unlocking with a wrong password must fail, and the failure must be indistinguishable from file corruption — the same InvalidTag — with the program never printing distinguishable “wrong password” versus “file damaged” messages; distinguishable errors are themselves an information leak. Third, tampering: flip one Base64 character in the ciphertext field and unlocking must fail. Fourth, the parameter ledger: measure one derivation with the current scrypt parameters on your own machine; it should land in the hundreds of milliseconds. Much faster means the parameters are too weak (the attacker’s cracking cost falls in step); much slower and usability collapses first. Understanding this ledger — the defender pays once, the attacker pays billions of times — is the key to every password KDF.
Exercises
One: swap scrypt for Argon2id (the low-level argon2.low_level.hash_secret_raw from argon2-cffi), compare the two parameter systems and their memory hardness, and make the file header recognize both KDFs. Two: run an offline cracking experiment — write a script that tries a weak-password dictionary against your own vault file, count how many attempts per second it manages, and work backwards to how long a six-digit numeric “master password” would survive; numbers you compute yourself persuade better than any slogan. Three: add a change-master-password operation with atomic file replacement (write a temporary file, then rename), and think through what happens if power fails mid-write. Four, the advanced one: change the single-file model to per-entry encryption (each entry its own nonce, one shared master key) and discuss which doors that opens for sync and sharing, and which new metadata leaks it introduces.
Summary
This core demonstrates something worth knowing: the cryptography inside a vault is not mysterious — what is hard is all the surrounding engineering required to do it right: memory hygiene, parameter governance, format evolution, and error handling that leaks nothing. The project walks the core chain end to end and lists every missing piece by name, which is the honesty a teaching implementation owes. The boundary one last time: real passwords go only into mature vaults; this core goes only into your exercise directory.
Tags: Password VaultKDFAEADTeaching Implementation