Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 40 ยท Projects

Project: Encrypted Vault

Build a small encrypted vault: derive keys from a master password with PBKDF2, encrypt then MAC the data, detect tampering, and rotate the password.

In this project you build the core of a password manager: a vault that stores site names, user names and passwords in one encrypted blob, which can only be opened with a master password. You will use the pieces from the earlier chapters: password hashing and PBKDF2, key derivation, a stream cipher built from HMAC, and encrypt-then-MAC for integrity.

The code is for learning. Its cipher is a toy construction, and the PBKDF2 function is a pure-Python stand-in because the in-browser Python has no hashlib.pbkdf2_hmac. The design, however, is how real vault files work, and at the end you will see how to swap in production-grade parts.

The design

What must the file guarantee?

  • Confidentiality. Without the master password, the file reveals nothing, including entry names.
  • Integrity. Any modification (a flipped bit, a swapped salt, a truncated file) is detected before anything is decrypted.
  • Slow guessing. An attacker who steals the file can try master passwords offline, so each guess must be expensive: a salted, slow KDF.
  • Freshness. Saving the same vault twice must give different bytes, so equal contents are not recognizable.

The format is a header followed by ciphertext and a tag:

Part Size Purpose
Magic VAULT1 6 bytes Identifies the format and version
Iterations 4 bytes PBKDF2 cost, stored so it can be raised later
Salt 16 bytes Random per save, makes each derived key unique
Nonce 16 bytes Random per save, makes the keystream unique
Ciphertext variable The vault entries as encrypted JSON
Tag 32 bytes HMAC-SHA-256 over everything before it
flowchart LR
    PW["Master password"] --> K["PBKDF2<br/>(salt, iterations)"]
    SALT["Salt"] --> K
    K --> M["Master key"]
    M --> E["Encryption key"]
    M --> A["Authentication key"]
    J["Entries as JSON"] --> X["XOR with keystream<br/>(encryption key, nonce)"]
    E --> X
    X --> C["Ciphertext"]
    A --> T["HMAC over header + ciphertext"]
    C --> T
    T --> F["File = header + ciphertext + tag"]

The password becomes a master key; two separate keys come from it, one to encrypt and one to authenticate.

Opening runs the same steps in a strict order: read the header, derive the keys, verify the tag first, and only then decrypt. Checking before decrypting means a tampered file is rejected without any decryption output being produced.

Step 1: derive the keys

PBKDF2 turns the password and salt into a master key. Two keys are derived from that master key with HMAC and distinct labels, so the encryption and authentication keys are independent. The example confirms the PBKDF2 stand-in against published test values before using it.

Python Step 1: password to keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The iteration count is the knob that makes guessing expensive. Here it is 5,000 so the demos run quickly in a browser. A real vault today should use hundreds of thousands of PBKDF2-SHA256 iterations, or better a memory-hard function such as scrypt or Argon2, tuned so that unlocking takes a noticeable fraction of a second on your slowest supported device.

Step 2: seal and open

seal makes a fresh salt and nonce, derives the keys, encrypts with an HMAC-based keystream (the idea from the stream ciphers lesson) and appends the tag. open_blob does the reverse. Notice two defensive details:

  • The tag covers the header, so changing the salt, nonce or iteration count is detected.
  • The iteration count is read from a file an attacker may control. A malicious file could claim two billion iterations and freeze the program, so it is range-checked before running the KDF.

The Vault class on top of these is just a dictionary serialized as JSON. Run the whole project below.

Python Step 2: the complete vault

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Every change is refused. Apart from a damaged magic number, which is plainly not a vault, the message is always the same, and that is deliberate: from the outside, "wrong password" and "damaged file" should be indistinguishable, so an attacker cannot learn which parts of the file were accepted.

Step 3: strong secrets inside the vault

A vault is only as good as what goes into it. A password manager also generates credentials, and that must use a secure random source: the secrets module, never random. Strength is measured in bits of entropy, length * log2(alphabet size) for random characters and words * log2(list size) for passphrases.

The next example generates both kinds and estimates how long an offline attacker needs to try half the possibilities at two speeds: a fast unsalted hash on powerful hardware, and a slow, deliberately expensive KDF. The exact guess rates are illustrative assumptions, not measurements.

Python Step 3: generators and guessing cost

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The table makes two points. A short, human-chosen password falls in months or less even against a slow KDF, so the master password should be a long random passphrase. And the KDF's slowness multiplies the attacker's work for every candidate, which is why it matters so much for the vault's master password, the one secret that cannot be generated for the user.

Using real components

For production, keep the structure and replace the home-made parts with reviewed ones. The sketch below is read-only; install the cryptography package on a normal Python to try it.

Python
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt

def seal(password: str, plaintext: bytes) -> bytes:
    salt, nonce = os.urandom(16), os.urandom(12)
    key = Scrypt(salt=salt, length=32, n=2**15, r=8, p=1).derive(password.encode())
    header = b"VAULT2" + salt + nonce
    return header + AESGCM(key).encrypt(nonce, plaintext, header)   # header is authenticated, not encrypted

The structure is identical: random salt and nonce per save, a slow memory-hard KDF, an authenticated cipher, and the header bound into the tag. AES-GCM replaces the toy stream cipher and the separate HMAC.

Ideas for extending the project

  • Add an auto-lock that forgets the keys after a period of inactivity, and overwrite them where the language allows.
  • Store each entry as a separate record with its own nonce so that one change does not rewrite the whole file, while keeping the entry names encrypted.
  • Add a key file or a hardware token as a second factor combined into the KDF input.
  • Write tests that confirm every byte position of the file is covered by the tag.
  • Stretch goal: derive a per-entry key with HKDF from the master key and the entry name.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the vault verify the MAC tag before decrypting?

    In encrypt-then-MAC, authenticity is checked first. A tampered ciphertext never reaches the decryption step or the JSON parser.
  2. 2. Why does the file store the PBKDF2 iteration count in the header?

    The count is not secret. Storing it lets new files use more iterations as hardware improves. It must be authenticated and range-checked because the file is untrusted.
  3. 3. Why use separate encryption and authentication keys?

    Using one key for two purposes can create subtle attacks. Deriving two independent keys with different labels is simple and removes that risk.
  4. 4. What does a fresh random salt and nonce on every save achieve?

    A new salt gives new keys and a new nonce gives a new keystream, so two saves cannot be compared and no keystream is ever used twice.
  5. 5. Which source should generate a password inside a password manager?

    Generated credentials must be unpredictable. The random module is not designed to resist an attacker who sees some of its output.

Summary

  • A vault file combines a slow salted KDF, separate encryption and authentication keys, a fresh nonce, and a MAC over the whole header and ciphertext.
  • Verify first, decrypt second; authenticate the header; range-check values read from untrusted files; use one error message for wrong password and tampering.
  • Random salt and nonce on every save give fresh, unlinkable files and prevent keystream reuse.
  • Strength comes from entropy: generate secrets with secrets, and choose a long random passphrase as the master password.
  • In production keep the design but use reviewed parts such as scrypt or Argon2 with AES-GCM or ChaCha20-Poly1305.

Next: Project: A Mini Crypto Library, where you assemble modular math, primality testing and RSA signatures with tests.