Mini Project: An Encrypted, Authenticated File Vault
You will build vault, a small command-line tool that encrypts a file under a passphrase so that it stays confidential if the file is stolen and any modification is detected, and you will write the design document a reviewer would ask for. It combines the course's main pieces: a password-based KDF (Password Storage, KDFs and Peppers), an AEAD with a unique nonce (Authenticated Encryption, Nonce Reuse), a versioned format with its header as associated data (Common Mistakes: crypto agility), CSPRNG salts and nonces (Randomness) and negative tests.
This is a learning project. For real files, use a maintained tool such as age (or libsodium's secretstream), which solves the same problem and has been reviewed; the comparison at the end is part of the write-up.
Step 1: requirements and threat model
| Assets | the file's contents |
| Attacker | gets a copy of the vault file (stolen laptop, leaked backup, cloud sync); can modify it and give it back; can try passphrases offline at GPU speed |
| Out of scope | malware on the machine while the vault is open; a weak passphrase chosen by the user (we can only make guessing expensive); hiding the file's size |
| Goals | confidentiality; integrity and authenticity of contents and header; every guess costs about 19 MiB of memory and two Argon2id passes; the format can evolve |
Step 2: the file format
All integers are big-endian. The whole 43-byte header is the AEAD's associated data, so nobody can change a parameter, the salt or the nonce without detection.
| Offset | Size | Field | Value |
|---|---|---|---|
| 0 | 4 | magic | TADV |
| 4 | 1 | format version | 1 |
| 5 | 1 | KDF id | 1 = Argon2id |
| 6 | 4 | Argon2id memory in KiB | 19456 (OWASP minimum) |
| 10 | 4 | Argon2id iterations | 2 |
| 14 | 1 | Argon2id parallelism | 1 |
| 15 | 16 | salt | os.urandom(16) per file |
| 31 | 12 | nonce | os.urandom(12) per seal |
| 43 | n + 16 | AES-256-GCM ciphertext and tag |
Design decisions to justify in the write-up: why the parameters are stored (so they can be raised later without breaking old files), why they are bounded when reading (an attacker who lowers to 8 MiB must not make a cheaper file the tool accepts; one who raises it to 4 GiB must not exhaust memory), why each seal gets a fresh salt and nonce (a key is never used twice, so nonce reuse is impossible even if the user re-seals the same file with the same passphrase).
Step 3: the code
The program below is the whole tool plus its tests. Files are kept in a dictionary because the browser has no disk; replace FILES with open(path, "rb") to run it on your machine. Only in the CLI demo the salt and nonce are fixed, so the printed sizes and header are the same on every run; seal itself draws them from os.urandom, and the last test checks that.
import argparse, os, struct
from argon2.low_level import hash_secret_raw, Type
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.exceptions import InvalidTag
MAGIC, VERSION, KDF_ARGON2ID = b"TADV", 1, 1
HEADER = struct.Struct(">4sBBIIB16s12s") # magic, version, kdf id, m (KiB), t, p, salt, nonce = 43 bytes
LIMITS = {"m": (19456, 1048576), "t": (2, 10), "p": (1, 8)}
class VaultError(Exception):
pass
def derive_key(passphrase, salt, m, t, p):
return hash_secret_raw(passphrase.encode(), salt, time_cost=t, memory_cost=m,
parallelism=p, hash_len=32, type=Type.ID)
def seal(passphrase, data, m=19456, t=2, p=1, salt=None, nonce=None):
salt = os.urandom(16) if salt is None else salt # fixed values only for reproducible tests
nonce = os.urandom(12) if nonce is None else nonce
header = HEADER.pack(MAGIC, VERSION, KDF_ARGON2ID, m, t, p, salt, nonce)
return header + AESGCM(derive_key(passphrase, salt, m, t, p)).encrypt(nonce, data, header)
def unseal(passphrase, blob):
if len(blob) < HEADER.size + 16:
raise VaultError("file too short")
header = blob[:HEADER.size]
magic, version, kdf, m, t, p, salt, nonce = HEADER.unpack(header)
if magic != MAGIC:
raise VaultError("not a vault file")
if version != VERSION or kdf != KDF_ARGON2ID:
raise VaultError(f"unsupported version {version} / kdf {kdf}")
for name, value in (("m", m), ("t", t), ("p", p)):
lo, hi = LIMITS[name]
if not lo <= value <= hi:
raise VaultError(f"KDF parameter {name}={value} out of range")
try:
return AESGCM(derive_key(passphrase, salt, m, t, p)).decrypt(nonce, blob[HEADER.size:], header)
except InvalidTag:
raise VaultError("wrong passphrase or file was modified") from None
# --- a CLI front end; files live in a dict here because the browser has no disk ---
FILES = {"notes.txt": b"wifi: lab-ap / psk: lab-only-123\n"}
def cli(argv, passphrase):
ap = argparse.ArgumentParser(prog="vault")
ap.add_argument("command", choices=["seal", "open", "info"])
ap.add_argument("path")
a = ap.parse_args(argv)
if a.command == "seal":
FILES[a.path + ".tadv"] = seal(passphrase, FILES[a.path], salt=bytes(16), nonce=bytes(12))
return f"sealed {a.path} -> {a.path}.tadv ({len(FILES[a.path + '.tadv'])} bytes)"
if a.command == "info":
magic, version, kdf, m, t, p, salt, nonce = HEADER.unpack(FILES[a.path][:HEADER.size])
return f"{a.path}: {magic.decode()} v{version}, Argon2id m={m} KiB t={t} p={p}, salt {salt.hex()[:8]}..."
return unseal(passphrase, FILES[a.path]).decode().strip()
print(cli(["seal", "notes.txt"], "lab-only passphrase"))
print(cli(["info", "notes.txt.tadv"], ""))
print(cli(["open", "notes.txt.tadv"], "lab-only passphrase"))
# --- tests: every kind of tampering must be detected ---
blob = FILES["notes.txt.tadv"]
flip = lambda b, i: b[:i] + bytes([b[i] ^ 1]) + b[i + 1:]
def expect_error(label, pw, b):
try:
unseal(pw, b); print(f"FAIL {label}: accepted")
except VaultError as e:
print(f"ok {label}: {e}")
expect_error("wrong passphrase", "lab-only passphrasE", blob)
expect_error("ciphertext bit flipped", "lab-only passphrase", flip(blob, HEADER.size + 3))
expect_error("tag bit flipped", "lab-only passphrase", flip(blob, len(blob) - 1))
expect_error("salt changed", "lab-only passphrase", flip(blob, 20))
expect_error("nonce changed", "lab-only passphrase", flip(blob, 35))
expect_error("memory cost lowered", "lab-only passphrase", blob[:6] + struct.pack(">I", 8192) + blob[10:])
expect_error("t raised (header is AAD)", "lab-only passphrase", blob[:10] + struct.pack(">I", 3) + blob[14:])
expect_error("truncated", "lab-only passphrase", blob[:-1])
expect_error("version 2", "lab-only passphrase", blob[:4] + b"\x02" + blob[5:])
expect_error("not a vault", "x", b"PK\x03\x04" + bytes(60))
print("fresh salt and nonce each seal:", seal("pw", b"x", t=2)[10:43] != seal("pw", b"x", t=2)[10:43])sealed notes.txt -> notes.txt.tadv (92 bytes)
notes.txt.tadv: TADV v1, Argon2id m=19456 KiB t=2 p=1, salt 00000000...
wifi: lab-ap / psk: lab-only-123
ok wrong passphrase: wrong passphrase or file was modified
ok ciphertext bit flipped: wrong passphrase or file was modified
ok tag bit flipped: wrong passphrase or file was modified
ok salt changed: wrong passphrase or file was modified
ok nonce changed: wrong passphrase or file was modified
ok memory cost lowered: KDF parameter m=8192 out of range
ok t raised (header is AAD): wrong passphrase or file was modified
ok truncated: wrong passphrase or file was modified
ok version 2: unsupported version 2 / kdf 1
ok not a vault: not a vault file
fresh salt and nonce each seal: True
The vault is 92 bytes: 43 of header, 33 of ciphertext (the plaintext's length) and a 16-byte tag. Ten negative tests, all detected. Note two different failure paths for the KDF parameters: a value outside the bounds is refused before any work is done, while a value inside the bounds but changed (t from 2 to 3) is caught by the tag, because the header is associated data. The wrong-passphrase and modified-file cases deliberately give the same message: the tool can't tell them apart, and it shouldn't try.
Step 4: extend it
Pick at least two:
- Large files: AES-GCM should not encrypt gigabytes as one message, and the tool should not hold the whole file in memory. Split into 64 KiB chunks, each encrypted with nonce = 8-byte random prefix + 4-byte chunk counter, and bind the chunk index and a "last chunk" flag to each chunk (in its AAD here; the STREAM construction used by age and Tink puts them in the nonce), so chunks can't be reordered, dropped or truncated. Add tests for swapped and missing chunks.
- Re-keying without re-encryption: encrypt the file with a random 32-byte DEK and store the DEK wrapped by the passphrase key (envelope encryption, Key Management); changing the passphrase rewrites only the wrapped DEK. Add a second key slot (a recovery key), as LUKS does.
- Parameter upgrade: an
upgradecommand that opens a version-1 file and re-seals it with higher Argon2id parameters, and aMIN_PARAMSpolicy that warns on old files. - Passphrase strength: refuse passphrases under 15 characters and estimate entropy for generated Diceware passphrases (Password Entropy).
- Compare with age: install age in your own lab, encrypt the same file with
age -p, and compare its format (header, scrypt work factor, STREAM chunks, HMAC over the header) with yours.
Step 5: the design write-up
Fill in this template (one to two pages). A reviewer should be able to check every decision against it.
VAULT DESIGN NOTE version: 1.0 author: ... date: ...
1. Purpose and scope
What the tool protects, for whom, and what it explicitly does not do.
2. Threat model
Attacker capabilities (file theft, modification, offline guessing at N guesses/s), trust
assumptions (clean machine while open), out of scope (malware, file size, metadata).
3. Primitives and parameters
KDF: Argon2id, m = ... KiB, t = ..., p = ..., salt 16 bytes from os.urandom (source: OWASP, date checked)
AEAD: AES-256-GCM, 12-byte nonce from os.urandom per seal, 16-byte tag, header as AAD
Why these and not alternatives (scrypt, ChaCha20-Poly1305, XChaCha20).
4. File format
Byte layout table; versioning rules; bounds checked on read and why.
5. Key lifecycle
Where the key exists (memory only, during open/seal), how passphrase changes work,
what happens if the passphrase is lost (data loss: say so to users).
6. Security argument
For each goal (confidentiality, integrity of contents, integrity of header, cost per guess),
which mechanism provides it.
7. Tests
Known-answer tests, negative tests (list), what each failure must look like.
8. Limitations and future work
File size leaks, no forward secrecy, single passphrase, large-file streaming, post-quantum
(not needed: no public-key crypto), comparison with age / libsodium secretstream.
9. Review log
Who reviewed, findings, fixes.Checklist before you call it done
- Salt and nonce come from
os.urandomin every real seal; fixed values only in tests. - The whole header is AAD; header parameters are bounded on read.
- Every negative test fails closed with one generic error for wrong passphrase / modified data.
- No plaintext is written or printed before the tag has been verified.
- The passphrase and key are not logged, and the key is not stored.
- The design note is filled in, with the date you checked the Argon2id parameters.
Test yourself
Why is the whole vault header passed as associated data to AES-GCM?
- To encrypt it
- So any change to the version, KDF parameters, salt or nonce makes decryption fail
- To make the file smaller
- Because GCM requires a header
Why does the reader also check the KDF parameters against bounds?
- For speed only
- To refuse attacker-made files with weak or huge parameters before doing any work
- Because Argon2id needs them
- To compress the header
Why can't nonce reuse happen in this design even if the user seals the same file twice with the same passphrase?
- The nonce is a counter
- Each seal draws a fresh salt, so the derived key is different every time (and the nonce is fresh too)
- GCM ignores nonces
- The passphrase changes
How large is the vault file for a 33-byte plaintext?
- 33 bytes
- 49 bytes
- 76 bytes
- 92 bytes