SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 10

Cybersecurity Fundamentals · Lesson 10 of 90 · 14 min

Cryptography foundations

plaintextciphertextcipherkeyencryptiondecryptioneavesdroppingman-in-the-middle (MITM)keyspacebrute forceentropyrandomnessPRNG vs CSPRNGone-time pad

These are the notes for Cybersecurity Fundamentals (defensive), episode 10. Last time, permissions decided who can do what on a computer. But permissions only work inside a running computer: the moment data leaves it, over Wi-Fi or on a stolen disk, anyone who gets hold of it can read it. Today you'll invent cryptography: the science of keeping messages secret and safe even when strangers can see them. You'll meet each idea as the fix for a real-life problem: plaintext, eavesdropping and man-in-the-middle (MITM), encoding vs encryption (and why Base64 is not encryption), cipher, key, ciphertext, decryption, the Caesar cipher, brute force, keyspace, bits, cryptanalysis and frequency analysis, randomness and entropy, PRNG vs CSPRNG and Python's secrets module, the one-time pad with XOR, perfect secrecy and what happens when a pad is reused, Kerckhoffs's principle, hashing, and what cryptography can and cannot protect. Every term is explained the first time it appears, and the Glossary at the end defines them all again.

Riya, Aman and the café are made up. Every code sample runs as-is on your own machine; the outputs below are real (Python 3.13). Two demos use real randomness (the CSPRNG and one-time pad demos), so your values will be different every run.

The problems you'll solve

Problem Idea it teaches
Anyone on the café Wi-Fi can read or change the message Plaintext, eavesdropping, man-in-the-middle (MITM)
"Hide" it with Base64 Encoding is not encryption
Invent a real secret Cipher, algorithm, key, encryption, decryption, ciphertext (Caesar cipher)
The thief tries every key, or counts letters Brute force, keyspace, bits, cryptanalysis, frequency analysis
A huge keyspace, but a guessable key Randomness, entropy, seed, PRNG vs CSPRNG, secrets
The perfect cipher, and reusing it One-time pad, XOR, perfect secrecy, VENONA
Which tool does which job? Kerckhoffs's principle, encoding vs encryption vs hashing, the limits of crypto

Problem 1: anyone can read it

Riya texts Aman over the café Wi-Fi: PIN is 4821. The message in its normal, readable form is called plaintext.

What happens Name Like...
Riya sends a readable message Plaintext A postcard: the words are right there
A stranger on the same Wi-Fi quietly copies every message that passes Eavesdropping Reading the postcard on its way to the letterbox
An attacker sits between Riya and Aman, reads the message, changes 4821 to 1111, and passes it on; neither notices Man-in-the-middle (MITM) Someone rewriting the postcard and posting it on

On a shared network, your messages pass through equipment other people control. So we need to hide the message. The obvious first try?

Problem 2: Base64 is not encryption

"Make it look scrambled!" Base64 is a way of writing any data using only 64 "safe" characters: A-Z, a-z, 0-9, + and / (with = as padding at the end). Riya sends her message as Base64.

Demo 1: "hiding" with Base64

import base64

msg = "PIN is 4821"
hidden = base64.b64encode(msg.encode()).decode()
print("sent:   ", hidden)

# anyone on the Wi-Fi can do this, no secret needed
print("decoded:", base64.b64decode(hidden).decode())

Output:

sent:    UElOIGlzIDQ4MjE=
decoded: PIN is 4821

UElOIGlzIDQ4MjE= looks like gibberish, but the stranger decodes it with one standard function, no secret needed. (.encode() turns text into bytes, which is what b64encode needs; .decode() turns bytes back into text.)

Why it fails: Base64 is encoding, not encryption.

Encoding Encryption
What it does Changes the format of data so systems can carry it (email, URLs) Scrambles data with a secret
Secret needed? None A key
Who can reverse it? Anyone Only someone with the key
Security? None at all Yes, if done right

The fix: we need a real secret. That's encryption.

Problem 3: invent a cipher

Think of a locked box:

A locked box In cryptography Meaning
The letter inside Plaintext The readable message
The lock's design, the same for every box from that company Cipher The method, or algorithm (a precise step-by-step recipe), that scrambles and unscrambles
The key in your pocket, only you and your friend have it Key The secret input to the cipher
The locked box in transit, useless to a thief Ciphertext The scrambled output

Turning plaintext into ciphertext with the key is encryption. Turning ciphertext back into plaintext with the key is decryption.

Demo 2: the shift (Caesar) cipher

The oldest cipher there is: the shift cipher, also called the Caesar cipher after Julius Caesar. Each letter moves forward in the alphabet by the key. With key 3, a becomes d, b becomes e, and z wraps round to c.

def shift(text, key):
    out = ""
    for ch in text:
        if ch.isalpha():
            out += chr((ord(ch) - 97 + key) % 26 + 97)
        else:
            out += ch
    return out

plain = "meet at the chai stall"
secret = shift(plain, 3)            # encrypt with key 3
print("ciphertext:", secret)
print("decrypted: ", shift(secret, -3))

Output:

ciphertext: phhw dw wkh fkdl vwdoo
decrypted:  meet at the chai stall

How the line works: ord(ch) gives the letter's number (a = 97), - 97 makes a = 0 ... z = 25, + key shifts it, % 26 wraps past z back to a, and chr(... + 97) turns it back into a letter. Shifting by -3 is decryption. (This toy only handles lowercase letters.)

Only someone who knows the key is 3 can decrypt. Or can they?

Problem 4: brute force, keyspace and cryptanalysis

The thief copies the ciphertext phhw dw wkh fkdl vwdoo off the Wi-Fi. He doesn't know the key, so he simply tries every possible key, one after another. That's a brute-force attack: guessing every key until one works. A shift cipher has only 25 useful keys (a shift of 26 gives back the plaintext).

Demo 3: be the thief (brute force)

def shift(text, key):
    return "".join(chr((ord(c) - 97 + key) % 26 + 97)
                   if c.isalpha() else c for c in text)

stolen = "phhw dw wkh fkdl vwdoo"
for key in range(1, 26):            # try EVERY key
    guess = shift(stolen, -key)
    if "the" in guess.split():
        print(f"key {key:2}: {guess}   <-- found it")
        break
    print(f"key {key:2}: {guess}")

Output:

key  1: oggv cv vjg ejck uvcnn
key  2: nffu bu uif dibj tubmm
key  3: meet at the chai stall   <-- found it

Found in three tries. The set of all possible keys is called the keyspace, and this keyspace is tiny.

Demo 4: no guessing at all (frequency analysis)

In English, e is the most common letter. Count the letters in a longer stolen message:

from collections import Counter

stolen = ("wkh vwxghqwv zhqw wr wkh vfkrro wr vhh wkh whdfkhu "
          "dqg wkhq wkhb zhqw krph")
top = Counter(c for c in stolen if c.isalpha()).most_common(3)
print("most common letters:", top)

# 'e' is the most common English letter
key = (ord(top[0][0]) - ord("e")) % 26
print("guessed key:", key)

Output:

most common letters: [('h', 13), ('w', 12), ('k', 8)]
guessed key: 3

The most common letter is h. If h stands for e, the shift is 3: key recovered from patterns alone. Studying ciphertext to break a cipher without the key is cryptanalysis; counting letters is frequency analysis. Lesson: a good cipher must hide patterns like letter counts, not just swap letters.

Keyspace: count the keys

Computers store keys as bits: ones and zeros.

  • keyspace = how many keys are possible.
  • A key of n bits has 2ⁿ possible values.
  • Each extra bit doubles the keyspace, and doubles the thief's work.
  • Caesar: 25 keys. A 4-digit PIN: 10,000.
  • The defence against brute force: make the keyspace far too big to search.

How big is big enough?

Demo 5: how long would brute force take?

Give the thief a monster computer: a trillion guesses per second.

SPEED = 10**12                    # a trillion guesses per second
YEAR = 60 * 60 * 24 * 365

def how_long(secs):
    if secs < 1:     return "instantly"
    if secs < 86400: return f"{secs / 3600:.0f} hours"
    return f"{secs / YEAR:.1e} years"

CASES = [("Caesar", 25), ("4-digit PIN", 10**4),
         ("56-bit DES", 2**56), ("128-bit AES", 2**128)]
for name, keys in CASES:
    t = how_long(keys / SPEED)
    print(f"{name:12} {keys:.1e} keys -> {t}")

Output:

Caesar       2.5e+01 keys -> instantly
4-digit PIN  1.0e+04 keys -> instantly
56-bit DES   7.2e+16 keys -> 20 hours
128-bit AES  3.4e+38 keys -> 1.1e+19 years

(1.1e+19 means 1.1 × 10¹⁹.) This is the worst case: trying every key.

  • DES (Data Encryption Standard) was published as a US standard (FIPS 46) in 1977 with a 56-bit effective key. Here it falls in about 20 hours. In fact, in 1998 a machine called Deep Crack (built by the EFF) broke a DES key in 56 hours.
  • AES (Advanced Encryption Standard, FIPS 197, 2001) uses keys of 128, 192 or 256 bits. You'll meet it properly next episode. A 128-bit key: about 1.1 × 10¹⁹ years. Brute force is hopeless.

Problem solved? Not quite.

Problem 5: randomness and entropy

A huge keyspace only helps if the key is picked unpredictably. A developer's app picks a 32-bit key using Python's random module. To get started, random takes a seed: a starting number. The developer uses the year, 2026. The attacker doesn't search the keyspace; he just guesses the seed.

Demo 6: same seed, same key

import random

# the app makes a key from a "random" number...
random.seed(2026)                 # seeded with the year
key = random.getrandbits(32)
print("app's key:     ", key)

# ...the attacker guesses the seed and runs the same code
random.seed(2026)
print("attacker's key:", random.getrandbits(32))

Output:

app's key:      511616025
attacker's key: 511616025

Same number, both times. random is a PRNG (pseudo-random number generator): a formula that produces numbers that look random, but the same seed always gives the same sequence. (Python's core generator is the Mersenne Twister.) Python's own documentation says: "The pseudo-random generators of this module should not be used for security purposes", and tells you to use the secrets module instead.

The fix: a CSPRNG (cryptographically secure pseudo-random number generator). It's seeded by the operating system from unpredictable events, like hardware noise and timing, and even seeing its outputs doesn't help you predict the next one. In Python, that's the secrets module (or os.urandom, which returns random bytes from the operating system).

Demo 7: real keys, and entropy

import secrets, math

print("key 1:", secrets.token_hex(16))   # 16 bytes = 128 bits
print("key 2:", secrets.token_hex(16))

# entropy = log2(number of equally likely choices)
for name, choices in [("coin flip", 2), ("4-digit PIN", 10**4),
                      ("128-bit key", 2**128)]:
    print(f"{name:12} {math.log2(choices):6.1f} bits")

Output (one run; the two keys are different every run):

key 1: d405a9cddfc5e0ec714eba61409f3e05
key 2: c7c3ec4bd15f9419c1e9400b2acaa638
coin flip       1.0 bits
4-digit PIN    13.3 bits
128-bit key   128.0 bits

token_hex(16) gives 16 random bytes written as 32 hex (base-16, digits 0-9a-f) characters. Below the keys is entropy: a measure of unpredictability, in bits. It's log₂ of the number of equally likely choices. A coin flip is 1 bit, a 4-digit PIN about 13.3 bits, and a properly random 128-bit key the full 128.

Randomness, the right way

PRNG (random) CSPRNG (secrets, os.urandom)
Predictable from the seed? Yes, same seed → same numbers No
Good for Games, simulations, tests where repeatable is fine Keys, password-reset tokens, one-time codes
Use for secrets? Never Always

Randomness, in security, means nobody can predict the next value, not even someone who saw the previous ones. A key is only as strong as its randomness: a 128-bit key picked from a guessable seed has the entropy of the seed, not 128 bits.

Problem 6: the perfect cipher, and reusing it

Is there a cipher that can never be broken, not even with infinite computing power? Yes: the one-time pad. Imagine two spies with identical notebooks full of truly random pages:

A spy's notebook One-time pad Rule
A pad of random pages, two copies, one each Random key As long as the message, truly random
Combine page + message, letter by letter XOR Bit by bit, reversible
Burn the page after use Use once Reuse breaks it

XOR ("exclusive or", written ^ in Python) combines two bits: if they're different the result is 1; if they're the same, 0.

a b a XOR b
0 0 0
0 1 1
1 0 1
1 1 0

XOR with the same key twice gives back the original (m ^ k ^ k == m), so the same step encrypts and decrypts. The idea goes back to Vernam (1917). In 1949, Claude Shannon ("Communication Theory of Secrecy Systems") proved that it gives perfect secrecy: the ciphertext tells the attacker nothing at all about the message. But only if the key is uniformly (truly) random, as long as the message, and never reused.

Demo 8: a one-time pad

import secrets

def xor(a, b):
    return bytes(x ^ y for x, y in zip(a, b))

msg = b"ATTACK AT DAWN"
pad = secrets.token_bytes(len(msg))   # random, full length
ct = xor(msg, pad)
print("ciphertext:", ct.hex())
print("decrypted: ", xor(ct, pad).decode())

Output (one run; the ciphertext is different every run because the pad is new each time):

ciphertext: 5772e1d30916dad94024c89f12be
decrypted:  ATTACK AT DAWN

b"..." is a bytes literal; zip(a, b) pairs up the bytes; x ^ y XORs each pair. Every possible 14-letter message is equally likely to give that ciphertext, so brute force is useless: trying every pad just gives you every possible message.

So why doesn't everyone use it? The key must be as long as all the data you'll ever send, delivered in secret beforehand, and never reused. And people get lazy and reuse it.

Demo 9: a reused pad

def xor(a, b):
    return bytes(x ^ y for x, y in zip(a, b))

pad = bytes.fromhex("8f3a91c2d45e07b6a1c93e5f20d4")   # used TWICE
c1 = xor(b"ATTACK AT DAWN", pad)
c2 = xor(b"RETREAT AT TEN", pad)

# the eavesdropper has only c1 and c2, and guesses message 1
leak = xor(c1, c2)                      # the pad cancels out!
print(xor(leak, b"ATTACK AT DAWN").decode())

Output:

RETREAT AT TEN

Why: c1 ^ c2 = (m1 ^ pad) ^ (m2 ^ pad) = m1 ^ m2, because pad ^ pad is all zeros. The pad cancels out, leaving the two messages mixed together. One correct guess about message 1, and out pops message 2. No key needed. Real Soviet spy messages were read this way in the VENONA project, because pad material had been reused.

Kerckhoffs's principle, revisited

Remember Kerckhoffs's principle from episode 3? A system should stay secure even if the enemy knows everything about it, except the key.

  • Assume the enemy knows the cipher; only the key must stay secret.
  • A key is small and easy to change if it leaks; a method built into a million devices is not.
  • Good ciphers are published, attacked by experts for years, and trusted only if they survive.
  • Hiding the method and hoping nobody figures it out is security through obscurity, and it isn't enough. Our Caesar shift fell to a tiny keyspace and visible patterns.
  • Never invent your own cipher for real data.

Encoding vs encryption vs hashing

One more tool, which people mix up with the other two: hashing. A hash function turns any input into a fixed-size fingerprint, and there's no way back. SHA-256 is a widely used hash function that produces a 256-bit fingerprint (64 hex characters).

Demo 10: encoding vs hashing

import hashlib, base64

enc = base64.b64encode(b"meet at 5").decode()
print("encoded:", enc, "-> decodes back:", base64.b64decode(enc))

# hashing: a fixed-size fingerprint, no key, no way back
print("hash 5: ", hashlib.sha256(b"meet at 5").hexdigest()[:32])
print("hash 6: ", hashlib.sha256(b"meet at 6").hexdigest()[:32])

Output:

encoded: bWVldCBhdCA1 -> decodes back: b'meet at 5'
hash 5:  1e43efa5146417549ecb0964dc57fb46
hash 6:  243f6b70d0d096a11e0f25c1bf7eef59

([:32] shows just the first 32 of the 64 hex characters, to fit the screen.) Encoding: reversible by anyone. Hashing: change one character and the fingerprint looks completely different. You can check a hash (hash the input again and compare), but you can't run it backwards to get the message. Episode 13 is all about hashes.

Encoding (Base64) Encryption Hashing (SHA-256)
Key? None Yes None
Reversible? By anyone Only with the key No (one-way)
Job Carry data safely through systems (email, URLs) Keep data secret Make a fingerprint you can check
Security? None Confidentiality Detect changes / compare

Three tools, three different jobs. Know which one you need.

What cryptography can, and can't, protect

Crypto CAN protect (used correctly) Crypto CANNOT protect
Secrecy on the network A stolen or weakly chosen key
Secrecy of a stolen disk Malware (malicious software) already on your phone, which sees the message before encryption
Detect changed data, which stops a MITM editing messages (MACs, episode 12) You, tricked by phishing (fake messages that trick you into giving away secrets)
Prove who sent something (signatures, episode 16) Metadata: data about the data, like who talked to whom, when, and how much
Buggy code that uses crypto wrongly

Crypto guards data; it doesn't protect the endpoints (the devices at each end, like Riya's and Aman's phones) or the people using them.

The whole chain

Step Problem You invented
1 Anyone on the Wi-Fi reads it Plaintext, eavesdropping, MITM
2 Base64 decoded in one line Encoding is not encryption
3 A secret shift Cipher, key, ciphertext, encryption, decryption
4 The thief tries every key, counts letters Brute force, keyspace, cryptanalysis
5 A guessable seed Randomness, entropy, PRNG vs CSPRNG (secrets)
6 Perfect, but keys as long as the data One-time pad, XOR, never reuse a pad
7 A secret method isn't enough Kerckhoffs's principle; encoding vs encryption vs hashing
? A short key (like 128 bits) that's safe to reuse for gigabytes? Next episode: symmetric encryption (AES, ChaCha20)

Common mistakes (and what they print)

Mistake What you see Why it's wrong Fix
Hiding a password/PIN with base64.b64encode decoded: PIN is 4821 Encoding has no key Encrypt with a vetted library (or hash passwords, episode 14)
random.seed(2026); random.getrandbits(32) for a key attacker's key: 511616025 PRNG output is repeatable secrets.token_hex(16) / secrets.token_bytes(16)
Same pad for two messages RETREAT AT TEN XOR cancels the pad Never reuse a key stream
Your own secret cipher key 3: meet at the chai stall <-- found it Tiny keyspace, visible patterns Use AES / ChaCha20
base64.b64encode("PIN is 4821") (a string, not bytes) TypeError: a bytes-like object is required, not 'str' Base64 works on bytes .encode() first
base64.b64decode("UElOIGlzIDQ4MjE") (missing =) binascii.Error: Incorrect padding Base64 text must be a multiple of 4 characters Keep the = padding
hashlib.sha256("meet at 5") TypeError: Strings must be encoded before hashing Hashes work on bytes hashlib.sha256(b"meet at 5") or .encode()
XOR with a pad shorter than the message b'@VW' (a 14-byte message, a 3-byte pad) zip silently stops at the shorter one Pad length must equal message length

Mini project: a crypto red-flag checker

A small defensive tool for your own code and config: (1) is a stored "secret" merely Base64 of readable text? (2) does a key-generation file use the random module or hide secrets with Base64?

import base64, binascii, re

def merely_base64(s):
    """Return the decoded text if s is just Base64 of readable text."""
    try:
        raw = base64.b64decode(s, validate=True)
        text = raw.decode()
    except (binascii.Error, UnicodeDecodeError):
        return None
    return text if text.isprintable() else None

WEAK = [(r"random\.seed\(",       "PRNG seeded with a guessable value"),
        (r"random\.(getrandbits|randint|random|choice)\(",
                                 "random module used (not a CSPRNG)"),
        (r"b64encode\(.*(pass|pin|key|secret)",
                                 "secret 'hidden' with Base64 (encoding, no key)")]

def scan_code(lines):
    for n, line in enumerate(lines, 1):
        for pattern, why in WEAK:
            if re.search(pattern, line, re.IGNORECASE):
                print(f"  line {n}: {why}\n          {line.strip()}")

# 1. strings found in a made-up app's config
for s in ["UElOIGlzIDQ4MjE=", "5772e1d30916dad94024c89f12be", "bWVldCBhdCA1"]:
    text = merely_base64(s)
    verdict = f"just Base64 -> {text!r}" if text else "not readable Base64"
    print(f"{s:30} {verdict}")

# 2. a made-up key-generation file
code = '''import random, base64, secrets
random.seed(2026)
key = random.getrandbits(32)
token = secrets.token_hex(16)
saved = base64.b64encode(password.encode())'''.splitlines()
print("weak spots in keygen.py:")
scan_code(code)

Output:

UElOIGlzIDQ4MjE=               just Base64 -> 'PIN is 4821'
5772e1d30916dad94024c89f12be   not readable Base64
bWVldCBhdCA1                   just Base64 -> 'meet at 5'
weak spots in keygen.py:
  line 2: PRNG seeded with a guessable value
          random.seed(2026)
  line 3: random module used (not a CSPRNG)
          key = random.getrandbits(32)
  line 5: secret 'hidden' with Base64 (encoding, no key)
          saved = base64.b64encode(password.encode())

Notice line 4 (secrets.token_hex(16)) is not flagged: that's the right way. And the hex ciphertext from Demo 8 happens to use only valid Base64 characters, but decodes to unreadable bytes, so it isn't flagged as "just Base64". To check a real project you own, read its files with open(...).read().splitlines() and pass them to scan_code. This is a simple pattern check, so treat its hits as "look here", not proof.

Practice

1. Homework: brute force vhfxulwb. It was made with a lowercase shift cipher. Find the key and the word.

Solution
def shift(text, key):
    return "".join(chr((ord(c) - 97 + key) % 26 + 97)
                   if c.isalpha() else c for c in text)

stolen = "vhfxulwb"
for key in range(1, 26):
    print(f"key {key:2}: {shift(stolen, -key)}")

Output:

key  1: ugewtkva
key  2: tfdvsjuz
key  3: security
key  4: rdbtqhsx
key  5: qcaspgrw
key  6: pbzrofqv
key  7: oayqnepu
key  8: nzxpmdot
key  9: mywolcns
key 10: lxvnkbmr
key 11: kwumjalq
key 12: jvtlizkp
key 13: iuskhyjo
key 14: htrjgxin
key 15: gsqifwhm
key 16: frphevgl
key 17: eqogdufk
key 18: dpnfctej
key 19: comebsdi
key 20: bnldarch
key 21: amkczqbg
key 22: zljbypaf
key 23: ykiaxoze
key 24: xjhzwnyd
key 25: wigyvmxc

Key 3: security. Only one line out of 25 is a real word: a 25-key keyspace gives no protection.

2. Homework: entropy of a 6-digit one-time code (OTP). How many bits? Compare with a 4-digit PIN.

Solution
import math
print(f"6-digit OTP: {math.log2(10**6):.1f} bits")
print(f"4-digit PIN: {math.log2(10**4):.1f} bits")

Output:

6-digit OTP: 19.9 bits
4-digit PIN: 13.3 bits

10⁶ equally likely codes → log₂(10⁶) ≈ 19.9 bits, if the code is picked by a CSPRNG. That's small, which is why such codes must expire quickly and allow only a few tries.

3. Homework: fix seed.py with secrets. Rewrite Demo 6 so the attacker can't regenerate the key.

Solution
import secrets

# the app makes a key from the operating system's CSPRNG
key = secrets.randbits(32)
print("app's key:     ", key)

# the attacker has no seed to guess; running the same code gives a new number
print("attacker's try:", secrets.randbits(32))

Output (one run; different every run):

app's key:      3725752258
attacker's try: 1517615236

No seed, so nothing to guess. For a real key, use a full 128 bits: secrets.token_bytes(16) or secrets.token_hex(16).

4. A "128-bit" key from a year. An app runs random.seed(year) and then random.getrandbits(128). Show that the real entropy is tiny.

Solution
import random, math
random.seed(2026)
key = random.getrandbits(128)          # looks like a 128-bit key...
for seed in range(2000, 2100):         # ...but the seed was a year
    random.seed(seed)
    if random.getrandbits(128) == key:
        print("seed found:", seed)
        break
print(f"real entropy: about {math.log2(100):.1f} bits, not 128")

Output:

seed found: 2026
real entropy: about 6.6 bits, not 128

The key has the entropy of the seed (about 100 possible years), not of its length.

5. XOR twice. Without running it, what does xor(xor(b"HI", b"\x13\x37"), b"\x13\x37") print? Why?

Solution
def xor(a, b):
    return bytes(x ^ y for x, y in zip(a, b))

print(xor(xor(b"HI", b"\x13\x37"), b"\x13\x37"))

Output:

b'HI'

m ^ k ^ k = m ^ 0 = m: XOR with the same key twice undoes itself, which is why one function both encrypts and decrypts a one-time pad, and why a reused pad cancels out.

6. Which tool? (a) Send a photo inside an email that only carries text. (b) Keep a diary file secret if the laptop is stolen. (c) Check that a downloaded file wasn't changed.

Solution

(a) Encoding (Base64): a format change, no secrecy. (b) Encryption with a key. (c) Hashing: compare the file's SHA-256 fingerprint with the expected one.

7. Homework: one thing crypto can't fix. Name one and say why.

Solution

Any of: malware on the phone (it reads the message before encryption); phishing (you hand over the key or password yourself); a stolen or weak key; metadata (who talked to whom, when, how much is still visible); buggy code that uses crypto wrongly.

Quick quiz

Which one is real encryption, where only the key holder can get the data back?

# A. base64.b64encode(data)
#
# B. hashlib.sha256(data).hexdigest()
#
# C. data XOR a pad from secrets,
#    used once, as long as the data
#
# D. data XOR a pad from random.seed(1)

A. Base64 B. SHA-256 hash C. One-time pad from secrets D. Pad from random.seed(1)

Answer

C. Base64 has no key. A hash can't be reversed at all, so it isn't encryption. A pad from random.seed(1) can be regenerated by anyone. A random, single-use pad from secrets, as long as the data, is a true one-time pad, and it's perfect if never reused.

Interview questions

  1. What's the difference between encoding, encryption and hashing? Encoding changes format and anyone can reverse it (no key). Encryption scrambles with a key and only the key holder can reverse it. Hashing makes a fixed-size, one-way fingerprint with no key.
  2. Is Base64 encryption? No. It's encoding: base64.b64decode reverses it with no secret. It provides zero confidentiality.
  3. What is keyspace, and why does key length matter? The number of possible keys; an n-bit key has 2ⁿ. Each extra bit doubles brute-force work, so 128-bit keys are out of reach of brute force while 56-bit DES is not.
  4. What's the difference between a PRNG and a CSPRNG? A PRNG (Python's random, Mersenne Twister) is fast and repeatable from its seed, so it's predictable. A CSPRNG (secrets, os.urandom) is seeded by the OS from unpredictable events and its outputs don't help predict the next ones. Use a CSPRNG for keys, tokens and one-time codes.
  5. What is entropy in this context? Unpredictability measured in bits: log₂ of the number of equally likely choices. A key has the entropy of how it was generated, not of its length.
  6. Why is the one-time pad perfectly secure, and why isn't it used everywhere? With a truly random key as long as the message, used once, the ciphertext reveals nothing about the message (Shannon's perfect secrecy). But the key must be as long as all the data, shared secretly in advance, and never reused.
  7. What happens if a one-time pad is reused? XORing the two ciphertexts cancels the pad and leaves m1 XOR m2; guessing part of one message reveals the other (as in VENONA).
  8. What is Kerckhoffs's principle? A system should stay secure even if everything about it except the key is public. So use published, well-studied ciphers, and don't rely on security through obscurity or a home-made cipher.

Glossary

Term Meaning in plain words Example
Cybersecurity Protecting computers, networks and data from attack and misuse This course
Cryptography The science of keeping messages secret and safe even when strangers can see them Encrypting a chat message
Plaintext The message in its normal, readable form PIN is 4821
Ciphertext The scrambled output of a cipher phhw dw wkh fkdl vwdoo
Cipher The method that scrambles and unscrambles messages The Caesar shift, AES
Algorithm A precise step-by-step recipe a computer can follow "Move each letter forward by the key"
Key The secret input to a cipher; only the people talking have it Shift 3; a 128-bit random value
Encryption Turning plaintext into ciphertext with a key shift(plain, 3)
Decryption Turning ciphertext back into plaintext with the key shift(secret, -3)
Eavesdropping Secretly copying messages as they pass A stranger on the café Wi-Fi
Man-in-the-middle (MITM) An attacker between two people who reads and changes messages 4821 changed to 1111
Encoding Changing data's format so systems can carry it; no secret, anyone reverses it Base64, URL encoding
Base64 An encoding that writes any data with 64 safe characters (A-Z a-z 0-9 + /) UElOIGlzIDQ4MjE=
Caesar / shift cipher Move each letter a fixed number of places in the alphabet Key 3: a → d
Brute force Trying every possible key until one works Trying shifts 1 to 25
Keyspace The set (and number) of all possible keys 25 for Caesar, 2¹²⁸ for a 128-bit key
Bit A single 0 or 1; keys are measured in bits A 56-bit DES key
Cryptanalysis Studying ciphertext to break a cipher without the key Recovering key 3 from letter counts
Frequency analysis Breaking a cipher by counting which symbols appear most h is most common, so h = e
DES Data Encryption Standard: a US standard from 1977 (FIPS 46) with a 56-bit key; now brute-forceable Deep Crack broke a key in 56 hours (1998)
AES Advanced Encryption Standard (FIPS 197, 2001), keys of 128/192/256 bits; covered next episode AES-128
Randomness Values nobody can predict, even after seeing earlier ones Output of secrets
Entropy Unpredictability measured in bits: log₂(number of equally likely choices) Coin flip 1 bit, 4-digit PIN 13.3 bits
Seed The starting number a PRNG begins from; same seed, same sequence random.seed(2026)
PRNG Pseudo-random number generator: a formula whose output looks random but is predictable from the seed Python's random (Mersenne Twister)
CSPRNG Cryptographically secure PRNG, seeded by the OS from unpredictable events; outputs can't be predicted secrets, os.urandom
secrets module Python's module for security-grade random values secrets.token_hex(16)
os.urandom Python function returning random bytes from the operating system's CSPRNG os.urandom(16)
Hex Base-16 writing of bytes using 0-9a-f; 2 characters per byte d405a9cd...
One-time pad XOR the message with a truly random key as long as the message, used once Demo 8
XOR "Exclusive or": 1 if two bits differ, 0 if they match; doing it twice undoes it m ^ k ^ k == m
Perfect secrecy The ciphertext tells the attacker nothing about the message (Shannon, 1949) A correctly used one-time pad
VENONA The project that read Soviet spy messages because pad material had been reused Demo 9's idea
Kerckhoffs's principle A system should stay secure even if the enemy knows everything except the key Publish the cipher, guard the key
Security through obscurity Relying on the method being secret instead of on the key A home-made cipher
Hashing / hash function Turning any input into a fixed-size, one-way fingerprint, with no key hashlib.sha256(data)
SHA-256 A widely used hash function with a 256-bit (64 hex character) output 1e43efa5... for meet at 5
Metadata Data about the data: who talked to whom, when, how much Encryption doesn't hide it
Endpoint A device at either end of a conversation Riya's phone
Malware Malicious software running on a device Spyware that reads messages before encryption
Phishing Fake messages that trick people into giving away secrets A fake "verify your PIN" text

Summary

  • Data that leaves the computer travels as plaintext unless protected; anyone can eavesdrop, and a man-in-the-middle can change it.
  • Encoding (Base64) is not encryption: no key, anyone reverses it.
  • A cipher is the public method; the key is the secret. Encryption turns plaintext into ciphertext; decryption reverses it.
  • Tiny keyspaces fall to brute force, and visible patterns fall to cryptanalysis (frequency analysis). Each extra key bit doubles the work; 128 bits is out of reach, 56-bit DES is not.
  • A key is only as strong as its randomness: never make keys with random (a PRNG); use a CSPRNG (secrets, os.urandom). Entropy = log₂(choices).
  • The one-time pad gives perfect secrecy, but only with a truly random key as long as the message, used once; reuse leaks messages (VENONA).
  • Kerckhoffs's principle: trust published ciphers, keep keys secret, never invent your own cipher.
  • Encoding = format, encryption = secrecy with a key, hashing = one-way fingerprint.
  • Crypto protects data, not stolen keys, malware on endpoints, phishing victims, metadata, or buggy code.

Next episode: symmetric encryption: AES and ChaCha20, block and stream ciphers, ECB's penguin problem, CBC, CTR, IVs and nonces.

Sources: Python documentation, random module (security warning, secrets, Mersenne Twister); C. E. Shannon, "Communication Theory of Secrecy Systems", Bell System Technical Journal, 1949 (perfect secrecy, one-time pad, Vernam 1917, VENONA), via course notes at bnaskrecki.faculty.wmi.amu.edu.pl, chapter 13; Wikipedia, "Data Encryption Standard" (FIPS 46, 1977, 56-bit key, EFF Deep Crack 1998) and "Advanced Encryption Standard" (FIPS 197, 2001). Fetched 29 Oct 2026. Code outputs from Python 3.13 runs.