These are the notes for Cybersecurity Fundamentals (defensive), episode 44. Episode 43 stopped our server being tricked into fetching internal addresses. Today the question is: when data leaks anyway, does the thief get anything? We protect customer data the wrong ways first (Base64, a key in the code, MD5, a clock-seeded random token) and watch each one fail, then build the real defences: data classification, data minimisation, masking, tokenisation, field-level encryption, encryption at rest, no-store caching and data loss prevention (DLP). Every term is explained the first time it appears, and the Glossary at the end defines them all again.
Neha, Ravi, the shop and every value are made up: 98450 12345 is a made-up phone number and 4111 1111 1111 1111 is a dummy test-style card number. Every program runs on one machine and contacts nothing outside it. Python samples run on 11 Nov 2026 with Python 3.13 and the cryptography library (version 50); every output below is copied from a real run. Random values (tokens, ciphertext, timings) are different on every run.
The problems you'll solve
| Problem | Idea it teaches |
|---|---|
| A customer backup leaks | cleartext, encoding vs encryption, hardcoded keys |
| PINs stored as MD5 are found in milliseconds | weak and deprecated algorithms, keyspace, brute force |
| A password-reset token anyone can rebuild | insufficient randomness, PRNG vs CSPRNG, secrets |
| Data read on the café Wi-Fi | cleartext transmission, TLS everywhere |
| Which data matters most? | data classification, data minimisation, retention |
| Card numbers spread across the system | masking, tokenisation, a vault |
| A database that decrypts for everyone it lets in | encryption at rest vs field-level encryption, AES-GCM, associated data |
| A personal page still there after logout | caching sensitive data, Cache-Control: no-store |
| A card number emailed by mistake | data loss prevention (DLP), the Luhn check |
Problem 1: a backup leaks
Basic words first:
- Sensitive data is data that causes harm if the wrong person sees it: names with phone numbers, addresses, card numbers, passwords, health records.
- Cleartext (or plaintext) means stored or sent as plain readable text, with no protection.
- Encryption turns plaintext into ciphertext using a key; only someone with the key can turn it back (episode 10).
- Encoding only changes the format of data so it survives a channel. Base64 writes any bytes using 64 safe characters (A–Z, a–z, 0–9,
+,/). It has no key: anyone can decode it. - XOR ("exclusive or") flips bits:
a XOR k XOR k = a. XOR with a short repeating key is a homemade cipher, not real encryption. - A hardcoded key is a secret written directly in the source code.
Neha's shop backs up its customer table every night. The file is copied to a shared drive "just for a day" and stays for a year. Neha wants it "encrypted". Here are the first two attempts.
Demo 1: Base64 and a key in the code
# Neha's shop "protects" its customer backup. An intern finds the file.
import base64
KEY = "shop2024" # written right in the code!
def protect(text): # "encryption", version 1
return base64.b64encode(text.encode()).decode()
def protect2(text): # version 2: XOR with KEY
out = bytes(b ^ ord(KEY[i % len(KEY)]) for i, b in enumerate(text.encode()))
return out.hex()
row = "Ravi Kumar, 98450 12345, card 4111 1111 1111 1111"
print("in the backup (v1):", protect(row)[:44] + "...")
print("anyone decodes it :", base64.b64decode(protect(row)).decode())
print()
blob = bytes.fromhex(protect2(row))
print("in the backup (v2):", protect2(row)[:44] + "...")
found_key = "shop2024" # copied from the source code
plain = bytes(b ^ ord(found_key[i % 8]) for i, b in enumerate(blob))
print("with the key :", plain.decode())
Output:
in the backup (v1): UmF2aSBLdW1hciwgOTg0NTAgMTIzNDUsIGNhcmQgNDEx...
anyone decodes it : Ravi Kumar, 98450 12345, card 4111 1111 1111 1111
in the backup (v2): 21091919127b4759121a43500b08060143485e420104...
with the key : Ravi Kumar, 98450 12345, card 4111 1111 1111 1111
Why it failed: Base64 is reversible by anyone, and the XOR key sits in the source code, which is copied to Git, every developer's laptop and every build of the app. OWASP's Cryptographic Storage Cheat Sheet: "Do not hard-code keys into the application source code."
What a cryptographic failure is
Cryptographic failures are mistakes where sensitive data isn't protected because the cryptography is missing, weak or misused. In the OWASP Top 10 (the best-known list of web application risks) it was A02 in 2021 and is A04 in 2025. OWASP's 2025 summary: sensitive data is not properly protected because encryption, hashing, key management, or transport security is weak or missing.
| Kind | Examples |
|---|---|
| Missing | cleartext at rest, cleartext in transit, backups not encrypted |
| Weak | MD5, SHA-1, DES, RC4, AES-ECB, small keys, guessable random numbers |
| Misused | keys in the code, keys stored next to the data, a reused nonce, a homemade cipher |
Keys belong in a key management system (KMS) or a hardware security module (episode 27), stored separately from the encrypted data. OWASP: "Where possible, encryption keys should be stored in a separate location from encrypted data."
Problem 2: weak and deprecated algorithms
- A deprecated algorithm is one experts now say to stop using, because practical attacks exist or it's too weak: MD5 and SHA-1 hashes (episode 13), the DES cipher, RC4, and AES in ECB mode (the penguin problem, episode 11). OWASP: "ECB should not be used outside of very specific circumstances."
- The keyspace is the number of possible secrets. A 4-digit PIN has only 10,000.
- A brute-force attack tries every possibility.
- A hash turns any input into a fixed-size fingerprint that can't simply be run backwards (episode 13).
Demo 2: an MD5-hashed PIN
# The old system stored each customer's 4-digit PIN as an MD5 hash.
import hashlib, time
stored = hashlib.md5(b"4721").hexdigest() # what the database holds
print("database has:", stored)
start = time.perf_counter()
for n in range(10000): # every PIN from 0000 to 9999
guess = f"{n:04d}"
if hashlib.md5(guess.encode()).hexdigest() == stored:
break
ms = (time.perf_counter() - start) * 1000
print(f"PIN found: {guess} after {n + 1} guesses in {ms:.1f} ms")
print("MD5 is fast and only 10,000 PINs exist: no hash can hide that.")
Output (the time changes a little each run):
database has: c47e93742387750baba2e238558fa12d
PIN found: 4721 after 4722 guesses in 2.3 ms
MD5 is fast and only 10,000 PINs exist: no hash can hide that.
Why it failed: MD5 is fast and the keyspace is tiny, so trying everything is instant. For passwords use a slow, salted key derivation function such as Argon2id (episode 14). For short values like PINs, a hash alone can never hide them: add a pepper (a secret key kept in the KMS, e.g. HMAC-SHA-256 with that key) and limit attempts.
Problem 3: insufficient randomness
- A pseudo-random number generator (PRNG) makes random-looking numbers from a formula. The same starting value, the seed, always gives the same sequence. Python's
randommodule is a PRNG for games and simulations. - A cryptographically secure PRNG (CSPRNG) can't be predicted even if you've seen earlier outputs. In Python it's the
secretsmodule (andos.urandom). - Insufficient randomness means security values (tokens, keys, nonces, reset links) that can be guessed.
- A password-reset token is the secret value in the "forgot password" link emailed to you.
Demo 3: a reset token rebuilt from the clock
# Password-reset tokens. Version 1 uses Python's random, seeded by the clock.
import random, time, secrets
def weak_token(now):
random.seed(int(now)) # seed = current second
return "".join(random.choice("0123456789abcdef") for _ in range(16))
issued_at = time.time()
token = weak_token(issued_at) # emailed to Neha
print("Neha's reset token :", token)
# An attacker asked for a reset at about the same time.
# They try every second of the last 5 minutes as the seed:
now = int(time.time())
for s in range(now - 300, now + 1):
if weak_token(s) == token:
print("attacker rebuilt it:", weak_token(s), f"(seed {s})")
break
print()
print("secrets.token_urlsafe(32):", secrets.token_urlsafe(32))
print("secrets.token_urlsafe(32):", secrets.token_urlsafe(32))
Output (tokens differ every run):
Neha's reset token : 8943bc8f79480c4d
attacker rebuilt it: 8943bc8f79480c4d (seed 1794441996)
secrets.token_urlsafe(32): 5IFAWUga89ehYauyaWaghD8uPrs7WgwnOj_bJSMx62M
secrets.token_urlsafe(32): AoxFtN5djyQfQ__7pOLTDfj_Bmt7Hka4ySdP9gH9pEE
Why it failed: the seed is the current second, so an attacker who knows roughly when the token was made tries a few hundred seeds. OWASP lists random() as not to be used for anything security-critical, and secrets as the secure choice. secrets.token_urlsafe(32) gives 32 random bytes (256 bits) as 43 URL-safe characters.
Problem 3b: cleartext transmission
Cleartext transmission is sending sensitive data without encryption: plain http://, plain SMTP between mail servers, an unencrypted database connection. Anyone on the path (café Wi-Fi, a compromised router, an attacker inside the network) can read it.
- Use HTTPS/TLS 1.2 or newer everywhere, with HSTS so browsers never fall back to HTTP (episode 22).
- Encrypt inside the network too: app ↔ database, message queues, service ↔ service. "It's internal" is not encryption.
Problem 4: data classification and data minimisation
Data classification means labelling every kind of data with a level, and giving each level rules. A common four-level scheme (organisations choose their own names):
| Level | School office example | Shop examples | Typical rules |
|---|---|---|---|
| Public | notice board | product prices, blog posts | anyone may read |
| Internal | staff room files | stock levels, staff rota | employees only |
| Confidential | student records | names, phones, addresses, order history | need-to-know, encrypted, logged access |
| Restricted | exam papers in the safe | card numbers, passwords, health data | minimise, tokenise or encrypt per field, tiny access list |
Data minimisation means collecting, keeping and showing only what you actually need. Three questions:
- Do we need it? No → don't collect it.
- Do we still need it? No → delete it after a fixed retention period (how long a type of data may be kept).
- Who needs it? Only they see the real value; everyone else gets a masked or tokenised value.
OWASP: "The best way to protect sensitive information is to not store it in the first place."
Problem 5: masking and tokenisation
- Masking hides most of a value when it's shown:
XXXX XXXX XXXX 1111. Enough to recognise, useless to steal. - Tokenisation replaces the real value with a random stand-in, a token, and keeps the real value in a separate, heavily protected vault. Like a cloakroom token: worthless outside the hall.
- Detokenisation swaps a token back for the real value, allowed only for the few services that need it.
Demo 4: mask and tokenise
# Masking and tokenisation: most of the shop never needs the real card number
import secrets
def mask(card): # for screens and receipts
digits = card.replace(" ", "")
return "XXXX XXXX XXXX " + digits[-4:]
VAULT = {} # separate, locked-down service
def tokenise(card):
token = "tok_" + secrets.token_hex(8) # random: no maths links it to the card
VAULT[token] = card
return token
def detokenise(token, caller):
if caller != "payment-service": # only one service may ask
return "DENIED"
return VAULT[token]
card = "4111 1111 1111 1111"
t = tokenise(card)
orders = [{"order": 501, "card": t, "show": mask(card)}] # the shop database
print("orders table : order 501 |", orders[0]["card"], "|", orders[0]["show"])
print("support app :", detokenise(t, "support-app"))
print("payment svc :", detokenise(t, "payment-service"))
print("leak orders table -> attacker gets:", orders[0]["card"], orders[0]["show"])
Output (the token differs every run):
orders table : order 501 | tok_971fd63ee2bf8302 | XXXX XXXX XXXX 1111
support app : DENIED
payment svc : 4111 1111 1111 1111
leak orders table -> attacker gets: tok_971fd63ee2bf8302 XXXX XXXX XXXX 1111
Why it works: the token is random, so no maths turns it back into the card (unlike encryption, where whoever steals the key can decrypt). Only the vault can, and the vault is small, separate and closely guarded. Most of the system (orders, support, analytics) never touches a real card number, which shrinks what has to be protected.
| Masking | Tokenisation | Encryption | |
|---|---|---|---|
| Reversible? | No (information removed) | Only by the vault | By anyone with the key |
| Use for | screens, receipts, logs | storing a reference to card or ID numbers | data the app must read back |
| Leak of the table gives | last 4 digits | random tokens | ciphertext (safe only while the key is safe) |
Problem 6: encryption at rest vs field-level encryption
- Encryption at rest means data is encrypted where it's stored: disks, database files, backups. It stops thieves with a stolen laptop, disk or backup tape. But a running database decrypts for anyone it lets in: an SQL injection (episode 38) or an admin running
SELECT *still sees everything. - Field-level encryption encrypts individual sensitive fields (columns) inside the application before they reach the database, so the database only ever stores ciphertext for those fields.
- AES-GCM is authenticated encryption (AEAD, episode 12): it hides the data and detects any change. OWASP recommends AES with a key "at least 128 bits (ideally 256 bits)" and says GCM and CCM "should be used as a first preference".
- A nonce ("number used once") must be new for every encryption with the same key; 12 random bytes for AES-GCM.
- Associated data (AAD) is extra, non-secret data bound to the ciphertext. Here it's the row id, so an encrypted field copied to another row is refused.
Demo 5: field-level encryption with AES-GCM
# Field-level encryption with AES-GCM (authenticated encryption, episode 12)
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.exceptions import InvalidTag
key = AESGCM.generate_key(bit_length=256) # real app: from a KMS (episode 27),
aes = AESGCM(key) # never written in the code
def encrypt_field(value, row_id):
nonce = os.urandom(12) # new random nonce every time
ct = aes.encrypt(nonce, value.encode(), row_id.encode()) # row id = AAD
return (nonce + ct).hex()
def decrypt_field(blob, row_id):
raw = bytes.fromhex(blob)
return aes.decrypt(raw[:12], raw[12:], row_id.encode()).decode()
row = {"id": "cust-17", "name": "Ravi Kumar",
"phone": encrypt_field("98450 12345", "cust-17")}
print("database row:", row["name"], "|", row["phone"][:40] + "...")
print("app decrypts:", decrypt_field(row["phone"], "cust-17"))
try: # someone copies the field to row 18
decrypt_field(row["phone"], "cust-18")
except InvalidTag:
print("moved to another row -> InvalidTag: refused")
Output (ciphertext differs every run):
database row: Ravi Kumar | 5c681455dd5e16564747b70d2cd53dad8b5f5bc3...
app decrypts: 98450 12345
moved to another row -> InvalidTag: refused
The key here is generated in the demo; a real app fetches it (or uses envelope encryption, episode 27) from a KMS, and never writes it in code or stores it beside the data. Use a vetted library like cryptography, libsodium or Tink: never write your own cipher.
Problem 7: caching sensitive data
A cache is a saved copy kept so pages load faster: in the browser, a company proxy, or a CDN (content delivery network, episode 21). A personal page cached on a shared computer can be reopened with the Back button after logout; a page cached by a shared proxy or CDN can be served to other people.
From MDN's Cache-Control reference:
no-store: "any caches of any kind (private or shared) should not store this response."private: "can be stored only in a private cache (e.g., local caches in browsers)."no-cache: can be stored, but "must be validated with the origin server before each reuse" (it does not mean "don't store").
HTTP/1.1 200 OK
Content-Type: text/html
Cache-Control: no-store
Send no-store on pages and API responses with personal data. Also keep sensitive data out of URLs (they end up in browser history, proxy logs and Referer headers) and out of log files.
Problem 8: data loss prevention (DLP)
Data loss prevention (DLP) tools watch data leaving the organisation (email, uploads, chat, USB drives) for sensitive patterns, and block, warn or log. Most leaks are accidents: a spreadsheet sent to the wrong person.
- A regular expression (regex) is a pattern for matching text, like "13 to 19 digits, spaces or dashes allowed".
- The Luhn check is a simple checksum: card numbers end in a check digit computed from the other digits, so most random digit strings fail it. Using it means fewer false positives (false alarms), so people don't learn to ignore the tool.
Demo 6: a tiny DLP scanner
# A tiny data loss prevention (DLP) check on outgoing messages
import re
def luhn_ok(num): # the check-digit test card numbers pass
total = 0
for i, d in enumerate(reversed(num)):
n = int(d)
if i % 2 == 1:
n *= 2
if n > 9: n -= 9
total += n
return total % 10 == 0
CARD = re.compile(r"\b(?:\d[ -]?){13,19}\b")
def dlp_scan(text):
for m in CARD.finditer(text):
digits = re.sub(r"\D", "", m.group())
if luhn_ok(digits):
return f"BLOCKED: card ending {digits[-4:]}"
return "sent"
for msg in ["Order 501 ships tomorrow",
"Ref no 1234 5678 9012 3456 for your claim",
"Hi, the customer's card is 4111 1111 1111 1111",
"Use card 4111-1111-1111-1111 for the refund"]:
print(f"{msg[:46]:48}-> {dlp_scan(msg)}")
Output:
Order 501 ships tomorrow -> sent
Ref no 1234 5678 9012 3456 for your claim -> sent
Hi, the customer's card is 4111 1111 1111 1111 -> BLOCKED: card ending 1111
Use card 4111-1111-1111-1111 for the refund -> BLOCKED: card ending 1111
Real DLP tools know many data types (cards, ID numbers, health codes, source code, documents labelled "Restricted"), and they rely on your classification. DLP is the last net, not the first wall.
The whole chain
- Base64 and a key in the code were undone → real encryption, keys in a KMS, apart from the data.
- An MD5 PIN fell in milliseconds → no deprecated algorithms, mind the keyspace.
- A clock-seeded token was rebuilt →
secrets(a CSPRNG). - Data crossed the network in cleartext → TLS everywhere, inside too.
- Classify data, minimise it, mask and tokenise what most of the system touches.
- Field-level AES-GCM for the most sensitive fields, encryption at rest for everything,
no-storefor personal pages, and DLP as the last net.
Common mistakes (and what they cause)
| Mistake | What happens (real output) | Why | Fix |
|---|---|---|---|
| Base64 as "encryption" | anyone decodes it : Ravi Kumar, 98450 12345, card 4111 ... |
encoding has no key | AES-GCM via a vetted library |
KEY = "shop2024" in the code |
with the key : Ravi Kumar, ... card 4111 ... |
source code is copied everywhere | key from a KMS, stored apart from the data |
| MD5 for PINs | PIN found: 4721 after 4722 guesses in 3.4 ms |
fast hash, tiny keyspace | pepper (HMAC with a KMS key) + attempt limits |
random.seed(time) for tokens |
attacker rebuilt it: ab81bb49fb6d59dc |
PRNG + guessable seed | secrets.token_urlsafe(32) |
| Reusing a nonce with AES-GCM | breaks confidentiality and integrity (episode 12) | GCM needs a unique nonce per key | os.urandom(12) every time |
| Moving an encrypted field | cryptography.exceptions.InvalidTag |
the row id is associated data | that's the protection working |
Personal pages without Cache-Control |
page reappears after logout | browser/proxy cache | Cache-Control: no-store |
| Card numbers in logs and URLs | data copied into many systems | logs and URLs are stored everywhere | mask before logging; POST bodies, not URLs |
Mini project: a customer store that protects each field by its classification
Each field's level decides what happens: never-store fields are dropped (minimisation), restricted fields are tokenised and masked, confidential fields are encrypted with AES-GCM (with customer:field as associated data), internal fields are stored as they are. An unknown field is treated as restricted.
# Mini project: a customer store that protects each field by its classification
import os, secrets
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
CLASS = {"name": "confidential", "city": "internal", "phone": "confidential",
"card": "restricted", "cvv": "never-store"}
class CustomerStore:
def __init__(self, key): # key comes from a KMS in real life
self.aes, self.rows, self.vault = AESGCM(key), {}, {}
def save(self, cid, record):
row = {}
for field, value in record.items():
level = CLASS.get(field, "restricted") # unknown field = strictest
if level == "never-store":
continue # data minimisation
if level == "restricted": # tokenise + mask
tok = "tok_" + secrets.token_hex(8)
self.vault[tok] = value
row[field] = {"token": tok, "show": "XXXX " + value[-4:]}
elif level == "confidential": # field-level encryption
nonce = os.urandom(12)
ct = self.aes.encrypt(nonce, value.encode(), f"{cid}:{field}".encode())
row[field] = (nonce + ct).hex()
else:
row[field] = value # internal: stored as is
self.rows[cid] = row
def read(self, cid, field):
blob = bytes.fromhex(self.rows[cid][field])
return self.aes.decrypt(blob[:12], blob[12:], f"{cid}:{field}".encode()).decode()
store = CustomerStore(AESGCM.generate_key(bit_length=256))
store.save("cust-17", {"name": "Ravi Kumar", "city": "Pune", "phone": "98450 12345",
"card": "4111111111111111", "cvv": "123"})
row = store.rows["cust-17"]
print("stored fields:", sorted(row))
print("city :", row["city"])
print("name :", row["name"][:32] + "...")
print("card :", row["card"]["show"], "| token", row["card"]["token"][:8] + "...")
print("app reads phone:", store.read("cust-17", "phone"))
Output (ciphertext and token differ every run):
stored fields: ['card', 'city', 'name', 'phone']
city : Pune
name : 7965605a29e2616eb96d212b5bb69112...
card : XXXX 1111 | token tok_1fa4...
app reads phone: 98450 12345
The CVV was never stored, the card number exists only in the vault, the name and phone are ciphertext in the table, and the app can still read the phone when it needs to.
Practice
- Label every field of a shop
customerstable (name, email, phone, city, card number, CVV, password hash, last login, marketing opt-in) with one of the four levels and a rule. - Add a retention rule that deletes support chats older than 180 days.
- Teach the DLP scanner to find Indian mobile numbers.
- Tokenisation vs encryption: when would you choose each?
Solution 1
| Field | Level | Rule |
|---|---|---|
| name | Confidential | field-level encryption, need-to-know |
| Confidential | encrypt or restrict access; mask in logs | |
| phone | Confidential | field-level encryption; mask on screens |
| city | Internal | employees only |
| card number | Restricted | tokenise; real value only in the vault |
| CVV | Restricted, never store | use for the payment, then discard |
| password hash | Restricted | Argon2id, never logged, never shown |
| last login | Internal | fine for support and security teams |
| marketing opt-in | Internal | needed for consent records |
Solution 2
# Practice 2 solution: a retention rule that deletes old rows
import sqlite3, datetime
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE support_chats (id INTEGER, phone TEXT, created TEXT)")
today = datetime.date(2026, 11, 11)
rows = [(1, "98450 12345", "2025-01-10"), (2, "99000 11111", "2026-06-01"),
(3, "90000 22222", "2026-11-01")]
db.executemany("INSERT INTO support_chats VALUES (?, ?, ?)", rows)
RETENTION_DAYS = 180 # the rule your classification decided
cutoff = (today - datetime.timedelta(days=RETENTION_DAYS)).isoformat()
deleted = db.execute("DELETE FROM support_chats WHERE created < ?", (cutoff,)).rowcount
db.commit()
print("cutoff:", cutoff, "| deleted", deleted, "rows")
print("kept :", db.execute("SELECT id, created FROM support_chats").fetchall())
Output:
cutoff: 2026-05-15 | deleted 1 rows
kept : [(2, '2026-06-01'), (3, '2026-11-01')]
Solution 3
Indian mobile numbers have 10 digits starting with 6–9, optionally after +91. The lookarounds (?<!\d) and (?!\d) stop it matching inside longer numbers.
# Practice 3 solution: the DLP scanner also finds Indian mobile numbers
import re
PHONE = re.compile(r"(?<!\d)(?:\+91[ -]?)?[6-9]\d{4}[ -]?\d{5}(?!\d)")
def dlp_scan(text):
m = PHONE.search(text)
if m:
return f"BLOCKED: phone number ending {re.sub(r'\D', '', m.group())[-4:]}"
return "sent"
for msg in ["Call me on 98450 12345", "Customer: +91-98450-12345",
"Order 12345 67890 shipped", "Invoice 5550012345 attached"]:
print(f"{msg:32}-> {dlp_scan(msg)}")
Output:
Call me on 98450 12345 -> BLOCKED: phone number ending 2345
Customer: +91-98450-12345 -> BLOCKED: phone number ending 2345
Order 12345 67890 shipped -> sent
Invoice 5550012345 attached -> sent
Solution 4
Tokenisation when most of the system only needs a reference to the value (orders that point at a card, analytics that count customers): the token is useless if leaked, and only a small vault holds real values. Encryption when the application itself must read the value back often (showing a customer their own phone number) or when data travels (backups, files, network). Many systems use both: tokens in the main database, encryption inside the vault.
Quick quiz
Which one actually protects the card numbers if the orders table leaks?
A: base64.b64encode(card) B: hashlib.md5(card).hexdigest() C: "tok_" + secrets.token_hex(8), card kept in a vault D: random.seed(time.time()) then XOR
Answer
C. A is encoding (no key). B is a fast, deprecated hash over card numbers, which have a known structure and can be enumerated. D uses a predictable PRNG and a homemade cipher. A random token with the real value in a separate, guarded vault reveals nothing when the orders table leaks.
Interview questions
- What are cryptographic failures? Sensitive data not protected because encryption, hashing, key management or transport security is weak, missing or misused (OWASP A02:2021, A04:2025).
- Encoding vs encryption vs hashing? Encoding changes format and is reversible by anyone; encryption is reversible only with the key; hashing is one-way.
- Where should encryption keys live? In a KMS or HSM, separate from the encrypted data, never in source code or config files in Git.
- Why is
randomwrong for tokens? It's a PRNG: with a known or guessable seed the output can be reproduced. Usesecrets. - Why doesn't hashing protect a 4-digit PIN? The keyspace is 10,000; trying every value takes milliseconds. Add a secret pepper and attempt limits.
- What is data classification and why first? Labelling data by sensitivity so each level gets rules; you can't protect, minimise or monitor what you haven't identified.
- What is data minimisation? Collect, keep and show only what is needed; delete after a retention period.
- Masking vs tokenisation? Masking hides part of a value for display; tokenisation replaces it with a random token, with the real value in a vault.
- Encryption at rest vs field-level encryption? At rest protects stolen disks and backups; field-level protects specific columns even from SQL injection and database admins.
- What does
Cache-Control: no-storedo? Tells every cache, private or shared, not to store the response. - What is DLP? Tools that detect sensitive data leaving the organisation and block, warn or log.
Glossary
| Term | Meaning, with an example |
|---|---|
| Sensitive data | Data that causes harm if exposed: phone numbers with names, card numbers, passwords. |
| Cleartext / plaintext | Readable, unprotected data: Ravi Kumar, 98450 12345. |
| Ciphertext | Encrypted data: 89b809d5133d.... |
| Encryption / decryption | Turning plaintext into ciphertext with a key, and back. |
| Encoding | Changing the format of data, reversible by anyone: Base64. |
| Base64 | An encoding using 64 safe characters; UmF2aSBL... is "Ravi K...". Not encryption. |
| XOR | A bit operation; XOR twice with the same key gives the original back. |
| Cryptographic failure | Sensitive data unprotected because crypto is weak, missing or misused (OWASP A02:2021, A04:2025). |
| OWASP Top 10 | The Open Worldwide Application Security Project's list of the ten biggest web app risk categories. |
| Hardcoded key | A secret written in source code: KEY = "shop2024". |
| Key management system (KMS) | A service that creates, stores and controls use of keys, apart from the data (episode 27). |
| Hash | A fixed-size fingerprint of data that can't be reversed directly: MD5, SHA-256. |
| Deprecated algorithm | One experts say to stop using: MD5, SHA-1, DES, RC4, AES-ECB. |
| Keyspace | The number of possible secrets: 10,000 for a 4-digit PIN. |
| Brute-force attack | Trying every possible secret. |
| Pepper | A secret key mixed into hashing, kept outside the database (e.g. in a KMS). |
| Argon2id | A slow, memory-hard password hashing function (episode 14). |
| PRNG | Pseudo-random number generator: random-looking numbers from a formula and a seed (random). |
| Seed | The starting value of a PRNG; the same seed gives the same numbers. |
| CSPRNG | Cryptographically secure PRNG: unpredictable (secrets, os.urandom). |
| Insufficient randomness | Security values that can be guessed, like a clock-seeded token. |
| Password-reset token | The secret value in a "forgot password" link. |
| Cleartext transmission | Sending sensitive data unencrypted, e.g. over http://. |
| TLS / HTTPS / HSTS | Encryption for data in transit; HSTS makes browsers always use HTTPS (episode 22). |
| Data classification | Labelling data by sensitivity (public, internal, confidential, restricted) with rules per level. |
| Data minimisation | Collecting, keeping and showing only what's needed. |
| Retention period | How long a type of data may be kept before deletion: e.g. 180 days for support chats. |
| Masking | Hiding most of a value for display: XXXX XXXX XXXX 1111. |
| Tokenisation | Replacing a value with a random token, the real value kept in a vault: tok_c8ec.... |
| Token vault | The separate, locked-down store that maps tokens to real values. |
| Encryption at rest | Encrypting stored data: disks, database files, backups. |
| Field-level encryption | Encrypting single sensitive columns in the app, so the database holds only ciphertext. |
| AES-GCM | AES in Galois/Counter Mode: authenticated encryption (hides and detects changes). |
| Nonce | A number used once per encryption with a key; 12 random bytes for AES-GCM. |
| Associated data (AAD) | Non-secret data bound to ciphertext, like a row id; changing it makes decryption fail. |
| InvalidTag | The cryptography library's error when AES-GCM data or associated data was changed. |
| Cache | A saved copy of a response in a browser, proxy or CDN. |
| CDN | Content delivery network: servers around the world that cache and serve content. |
| Cache-Control: no-store | An HTTP header telling every cache not to store the response. |
| Data loss prevention (DLP) | Tools that find sensitive data leaving the organisation and block, warn or log. |
| Regular expression (regex) | A pattern for matching text: \b(?:\d[ -]?){13,19}\b. |
| Luhn check | The check-digit test that card numbers pass; cuts DLP false alarms. |
| False positive | An alarm on something harmless, like a reference number that looks like a card. |
Summary
- Cryptographic failures (OWASP A02:2021, A04:2025): crypto that is missing, weak or misused.
- Encoding is not encryption, and a key in the code is not a secret: keys live in a KMS, apart from the data.
- No deprecated algorithms, mind the keyspace, and make every token with
secrets. - Encrypt in transit (TLS everywhere) and at rest; field-level AES-GCM for the most sensitive columns.
- Classify data, minimise it, mask it on screens and tokenise it where the system only needs a reference.
Cache-Control: no-storefor personal pages; nothing sensitive in URLs or logs; DLP as the last net.
Next episode: insecure design and business-logic flaws.