Guide Cybersecurity · Applied Cryptography

Foundations of Modern
Cryptography in Cybersecurity

A beginner-to-intermediate guide bridging classical cipher theory and modern applied cryptography.

Prepared by A. Yahiaoui 6 Modules Theory · Math · Code
E: (Key, Plaintext) → Ciphertext D: (Key, Ciphertext) → Plaintext such that D(k, E(k, m)) = m for every valid key k and message m
Overview Guide Structure

How This Guide Is Built

LevelBeginner → Intermediate
PrerequisitesBasic programming (Python), basic algebra. No prior cryptography background required.
Format6 modules, each combining theory, math, and working code
Suggested Pace2-3 hours per module, six study sessions, or one intensive week
Learning Outcome

Explain, mathematically derive, implement, and critically evaluate the cryptographic primitives that secure modern systems, from a Caesar shift to an AES-GCM channel.

Map Table of Contents

Six Modules, One Progression

Click any module to jump there. Press M anytime to open the guide map.

01
Module 01 / 06

Foundations & History

Why cryptography exists, and what it actually promises.

M1 Foundations & History · Key Concepts & Definitions

Cryptography, the CIA Triad & Digital Trust

Cryptography is the mathematics of transforming information so only intended parties can access or verify it. It sits inside a broader discipline:

Cryptography

Designing schemes that protect information

Cryptanalysis

Breaking those schemes without authorized access

Cryptology

The umbrella field covering both

The CIA Triad + Non-Repudiation

PropertyQuestion it answersCryptographic mechanism
ConfidentialityCan only the intended reader see this?Encryption (symmetric / asymmetric)
IntegrityHas this data been altered?Hash functions, MACs
AvailabilityCan authorized users reach it when needed?Mostly outside cryptography, redundancy, DDoS defense
Non-repudiationCan the sender deny sending this?Digital signatures
Digital Trust

The emergent property: a user trusts a system not because they inspected its code, but because cryptographic guarantees make dishonesty and tampering computationally infeasible to hide.

M1 Foundations & History · Mathematical / Algorithmic Explanation

Defining an Encryption Scheme

Formally, an encryption scheme is a pair of functions:

E: (Key, Plaintext) → Ciphertext D: (Key, Ciphertext) → Plaintext such that D(k, E(k, m)) = m for every valid key k and message m
Adversarial Definition

Confidentiality is defined adversarially: given ciphertext c = E(k, m), an attacker without k should not recover m, or even distinguish which of two candidate messages produced c, any faster than brute-forcing the key space.

M1 Foundations & History · A Short Timeline

From the Scytale to Post-Quantum

~500 BCESpartan scytale, transposition cipher via a wrapped rod
~50 BCECaesar cipher, shift substitution used in Roman military dispatches
1553Vigenère cipher, first widely adopted polyalphabetic cipher
1917-1945Enigma & rotor machines, mechanical polyalphabetic ciphers, broken at Bletchley Park
1976Diffie-Hellman key exchange, first practical solution to key distribution
1977RSA published; DES adopted as a U.S. federal standard
2001AES replaces DES as the U.S. federal symmetric standard
2015-presentPassword Hashing Competition (Argon2), TLS 1.3, NIST post-quantum standardization
M1 Foundations & History · Concrete Walkthrough

Alice Emails Bob a Signed Contract

StepProperty enforcedHow
1ConfidentialityAlice encrypts the PDF with Bob's public key, only Bob's private key can decrypt it
2Integrity + Non-repudiationAlice hashes the PDF and signs the hash with her private key, any edit changes the hash; only Alice's key produces a valid signature
3Integrity check + AuthenticityBob decrypts, re-hashes, and checks the signature with Alice's public key, a mismatch means tampering, or the wrong sender
4AvailabilityThe mailbox server is load-balanced across regions, architectural, not cryptographic
Pattern

Encrypt for confidentiality, hash for integrity, sign for non-repudiation, this is the backbone of HTTPS, signed software updates, and blockchain transactions alike.

M1 Foundations & History · Real-World Security Warning

Kerckhoffs's Principle

Principle · 1883

A cryptosystem must stay secure even if everything about it, except the key, is public knowledge. "Security through obscurity" (hiding the algorithm instead of protecting the key) is not a substitute for real cryptographic strength.

History is full of proprietary "secret" algorithms, GSM's A5/1, early RFID and pay-TV ciphers, that were reverse-engineered and broken shortly after deployment.

Best Practice

Every algorithm in this guide is public, peer-reviewed, and standardized, that transparency is a feature, not a risk.

02
Module 02 / 06

Classical Cryptography

Substitution, key space, and the statistical cracks that built modern cryptanalysis.

M2 Classical Cryptography · Key Concepts & Definitions

Four Ciphers, Four Ideas

Classical ciphers no longer protect real data, but they build the intuition, substitution, key space, statistical weakness, that every modern algorithm still has to reckon with.

CipherTypeCore Idea
CaesarMonoalphabetic substitutionShift every letter by a fixed amount k
AffineMonoalphabetic substitutionApply a linear function ax + b to each letter
VigenèrePolyalphabetic substitutionShift each letter by a different amount, cycling through a keyword
HillPolygraphic substitutionEncrypt blocks of letters at once via matrix multiplication

Letters map A=0, B=1, … Z=25; all arithmetic below is mod 26.

M2 Classical Cryptography · Mathematical Explanation (1/2)

Caesar & Affine: Key Space

Caesar Cipher

E(x) = (x + k) mod 26 D(y) = (y - k) mod 26

Key space: 25 usable keys (k=0 is the identity), trivially brute-forceable.

Affine Cipher

E(x) = (a·x + b) mod 26 D(y) = a⁻¹·(y - b) mod 26

a must be coprime with 26 (gcd(a, 26) = 1) or the mapping isn't reversible.

Key space: 12 valid values of a (φ(26) = 12, since 26 = 2 × 13) × 26 values of b = 312 keys.

M2 Classical Cryptography · Mathematical Explanation (2/2)

Vigenère & Hill: Key Space

Vigenère Cipher

For a keyword of length m:

E(x_i) = (x_i + k_(i mod m)) mod 26

Key space: 26^m, exponential in key length, but a repeating key leaks its own length statistically (see cryptanalysis).

Hill Cipher

Plaintext splits into vectors of size n; an n×n key matrix K encrypts by matrix multiplication:

C = K · P mod 26 P = K⁻¹ · C mod 26

K is usable only if invertible mod 26, i.e. gcd(det(K), 26) = 1.

Key space (2×2): |GL(2, Z26)| = 157,248, far larger than Caesar or Affine, but still breakable with linear algebra.

M2 Classical Cryptography · Code Walkthrough (1/2)

Caesar & Affine: Worked by Hand

Caesar: shift k = 3

def caesar_encrypt(plaintext, key): return ''.join( chr((ord(ch) - 65 + key) % 26 + 65) for ch in plaintext.upper() if ch.isalpha() ) print(caesar_encrypt("ATTACKATDAWN", 3))
ATTACKATDAWN → DWWDFNDWGDZQ

Affine: a=5, b=8 (a⁻¹=21)

Letterx5x+8mod 26Cipher
H74317R
E4282C
L116311L
L116311L
O14780A
HELLO → RCLLA
M2 Classical Cryptography · Code Walkthrough (2/2)

Vigenère & Hill: Worked by Hand

Vigenère: key = LEMON

Plaintext: A T T A C K A T D A W N Key: L E M O N L E M O N L E Cipher: L X F O P V E F R N H R

Hill: K = [[3,2],[5,7]]

det(K) = 11, K⁻¹ = [[3,14],[9,5]]. Encrypting HI (H=7, I=8):

C = [[3,2],[5,7]] · [7,8]ᵀ mod 26 = [37,91] mod 26 = [11,13] = L, N
HI → LN

Multiplying [L,N] by K⁻¹ recovers [7,8] = HI.

M2 Classical Cryptography · Basic Cryptanalysis

Frequency Analysis & Its Cousins

English letters are far from uniform:

LetterETAOIN…QZ
Frequency12.7%9.1%8.2%7.5%7.0%6.7%…0.10%0.07%
Caesar

The most frequent ciphertext letter is very likely the encryption of E.

Vigenère

Kasiski examination (repeated ciphertext segments infer key length) + the Index of Coincidence turns it back into several monoalphabetic ciphers.

Hill

Entirely linear, a known-plaintext attack (just n pairs for an n×n key) solves for K directly via linear algebra.

M2 Classical Cryptography · Real-World Security Warning

Don't Roll Your Own Crypto

A modern laptop brute-forces a Caesar cipher in microseconds and recovers a reasonable-length Vigenère key in milliseconds using frequency statistics. These ciphers matter today purely as pedagogy, small enough to compute by hand, which makes "key space," "reversible transformation," and "statistical weakness" tangible before meeting AES or RSA.

The Recurring Lesson

A "custom" or "obfuscated" cipher invented for a product, XOR loops, home-rolled substitution, bit-rotation "encryption", is functionally a Caesar cipher with extra steps, and breaks just as fast. Don't roll your own crypto.

03
Module 03 / 06

Cryptographic Paradigms & Modern Ciphers

Symmetric speed meets asymmetric trust, and the standards that run the internet.

M3 Cryptographic Paradigms · Key Concepts & Definitions

Symmetric vs. Asymmetric

SymmetricAsymmetric
KeysOne shared secret keyA mathematically linked public/private pair
SpeedFast, suited to bulk data~100-1000× slower, suited to small data
Core problem solvedConfidentialityConfidentiality and key distribution
Key distributionn users need n(n−1)/2 pairwise secret keysEach user publishes one public key; no shared secret required
ExamplesAES, ChaCha20RSA, ECC, Diffie-Hellman
Hybrid Cryptosystems

Combine both: use asymmetric crypto once to establish a shared secret, then switch to fast symmetric crypto for the actual data. This is exactly what TLS does, an ECDHE/RSA handshake negotiates a one-time AES session key, and the rest of the HTTPS connection runs on that AES key.

M3 Cryptographic Paradigms · Mathematical Explanation (1/2)

AES: Block Size & Modes of Operation

Block Size

Fixed 128 bits (16 bytes), regardless of key size

Key Sizes

128 / 192 / 256 bits → 10 / 12 / 14 rounds of substitution-permutation

Mode of Operation

A block cipher scrambles one 16-byte block; a mode chains many blocks together

CBCGCM
MechanismEach plaintext block XORed with the previous ciphertext block before encryptionCounter-mode encryption combined with a GHASH authentication tag
NeedsA random IV, plus PKCS#7 padding to fill the last blockA unique nonce (96-bit standard); no padding
IntegrityNone built in, ciphertext can be tampered with silentlyBuilt in, decryption fails loudly if even one bit changes
Known riskPadding-oracle attacks (e.g. POODLE)Catastrophic key/tag recovery if a nonce is ever reused
VerdictLegacy; needs a separate MAC (Encrypt-then-MAC)Modern default, TLS 1.3, most VPNs
M3 Cryptographic Paradigms · Mathematical Explanation (2/2)

RSA: Key Generation

Security rests on integer factorization: multiplying two large primes is fast, but factoring their product back into those primes is computationally infeasible at sufficient size (2048+ bits in practice).

1. Choose two large primes p, q 2. n = p * q (the modulus, public) 3. phi(n) = (p-1)(q-1) (Euler's totient, kept secret) 4. Choose e, coprime with phi(n) (commonly 65537) 5. d = e^-1 mod phi(n) (the private exponent) Public key: (n, e) Private key: (n, d)
Dual Role

The same pair swaps roles for signing: encrypt with the public key / decrypt with the private key gives confidentiality; sign with the private key / verify with the public key gives authenticity, the math is symmetric even though the use case isn't.

M3 Cryptographic Paradigms · Code Walkthrough (1/2)

RSA: A Small Worked Example

Textbook-sized primes, never use numbers this small in practice.

p, q = 61, 53 n = p * q # 3233 phi = (p - 1) * (q - 1) # 3120 e = 17 # gcd(17, 3120) == 1 d = pow(e, -1, phi) # 2753 (modular inverse of e) m = 65 c = pow(m, e, n) # encrypt: c = m^e mod n -> 2790 recovered = pow(c, d, n) # decrypt: m = c^d mod n -> 65 print(c, recovered) # 2790 65
M3 Cryptographic Paradigms · Code Walkthrough (2/2)

AES-GCM: Authenticated Encryption

from cryptography.hazmat.primitives.ciphers.aead import AESGCM import os key = AESGCM.generate_key(bit_length=256) aesgcm = AESGCM(key) nonce = os.urandom(12) # MUST be unique per encryption ciphertext = aesgcm.encrypt(nonce, b"Transfer $500 to account #4471", associated_data=b"txn-header-v1") plaintext = aesgcm.decrypt(nonce, ciphertext, associated_data=b"txn-header-v1") # Flipping a single bit in ciphertext or associated_data raises InvalidTag. # GCM detects tampering that CBC alone would silently accept.
M3 Cryptographic Paradigms · Real-World Security Warning

Modes, Nonces & Key Sizes

Never Use ECB

Identical plaintext blocks produce identical ciphertext blocks, leaking structure, the classic demonstration encrypts a bitmap in ECB and the picture is still recognizable in the ciphertext.

Never Reuse a Nonce

With GCM or CTR mode, reuse exposes the XOR of two plaintexts and can fully recover the authentication key, turning "authenticated" encryption into no encryption at all.

RSA Key Size Matters

1024-bit RSA is considered breakable by well-resourced attackers; 2048-bit is today's minimum, 3072/4096-bit for long-term protection.

Prefer Authenticated Modes

GCM, ChaCha20-Poly1305 over CBC for new designs, integrity shouldn't be an afterthought bolted on separately.

04
Module 04 / 06

Hashing, Salting & Password Security

Why hashing a password wrong is worse than not hashing it at all.

M4 Hashing & Password Security · Key Concepts & Definitions

What Is a Cryptographic Hash Function?

A cryptographic hash function maps arbitrary-length input to a fixed-length digest, with three defining properties:

PropertyMeaning
Pre-image resistance (one-way)Given H(x), you cannot feasibly recover x
Collision resistanceYou cannot feasibly find two different inputs that hash to the same output
Avalanche effectFlipping one input bit changes roughly half the output bits
M4 Hashing & Password Security · Mathematical / Algorithmic Explanation

SHA-256 vs. Key Derivation Functions

H : {0,1}* → {0,1}ⁿ, SHA-256 maps any input to a 256-bit digest. It is deterministic and fast, running at multiple GB/s on commodity hardware. That speed is exactly why it's the wrong tool for passwords.

Key Derivation Functions (KDFs), bcrypt, scrypt, Argon2, are deliberately the opposite: slow, and often memory-hard, with a tunable work factor.

SHA-256bcryptArgon2
Designed forIntegrity, checksums, signaturesPasswordsPasswords (2015 PHC winner)
SpeedBillions of hashes/sec on a GPUDeliberately slow, tunable cost factorDeliberately slow & memory-hard
Resists GPU/ASIC crackingNoSomewhatYes, memory cost is expensive to parallelize in silicon
M4 Hashing & Password Security · Code Walkthrough

Insecure vs. Secure Password Hashing

import hashlib, bcrypt password = "P@ssw0rd123" # INSECURE, fast, unsalted, identical output every time insecure = hashlib.sha256(password.encode()).hexdigest() # SECURE, bcrypt generates a random salt automatically hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(rounds=12)) bcrypt.checkpw(password.encode('utf-8'), hashed) # True bcrypt.checkpw(b"wrongpassword", hashed) # False
CallSHA-256 (insecure)bcrypt (secure)
Run 1231ecc7d178d...$2b$12$I/HxMXewCi...
Run 2231ecc7d178d... (identical)$2b$12$SmVWESPZWX... (different)
M4 Hashing & Password Security · Real-World Security Warning

Rainbow Tables, Salts & Work Factors

Rainbow Tables

Precomputed chains mapping billions of candidate passwords to their hashes. Against unsalted SHA-256, a database breach is instantly a breach of every common password, the attacker looks the hash up instead of computing it.

Salting Defeats This

A random, unique salt per user means the attacker needs a separate multi-terabyte table per user, which is computationally pointless. Salts aren't secret, their only job is making precomputation useless.

Work Factors Must Rise

A bcrypt cost factor "safe" in 2015 is weaker every year as hardware improves. Never store passwords in plaintext, and never rely on a fast general-purpose hash (MD5, SHA-1, bare SHA-256) alone for passwords.

05
Module 05 / 06

Token-Based Authentication & JWTs

A signed claim isn't a secret, and forgetting that breaks authentication.

M5 JWTs · Key Concepts & Definitions

Anatomy of a JSON Web Token

A JWT is a compact, URL-safe string with three base64url-encoded parts joined by dots:

HeaderPayloadSignature
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0Iiwicm9sZSI6ImFkbWluIiwiZXhwIjoxNzM1Njg5NjAwfQ.YTbPZkdWYl86Jcp-vaDFpCOFTNTiHa6YLEh4a3Qwy6M
PartContentsDecoded example
HeaderAlgorithm + token type{"alg":"HS256","typ":"JWT"}
PayloadClaims, data about the subject{"sub":"1234","role":"admin","exp":1735689600}
SignatureProof header+payload weren't alteredHMAC-SHA256(base64(header)+"."+base64(payload), secret)
Critical Point

The payload is only encoded, not encrypted. Anyone can base64-decode a JWT and read its claims, never put secrets in the payload.

M5 JWTs · Mathematical / Algorithmic Explanation

HS256 vs. RS256

signature = Sign(secretOrPrivateKey, base64url(header) + "." + base64url(payload)) verify: recompute the signature the same way and compare
HS256 (HMAC)RS256 (RSA)
Key typeOne symmetric secretAsymmetric key pair
Who can signAnyone holding the shared secretOnly the private key holder
Who can verifyAnyone holding the same shared secretAnyone with the public key
Risk if a key leaksEvery verifier can also forge tokensPublic key leaking is fine, only signing capability matters
M5 JWTs · Code Walkthrough

Decoding Without Verifying

Exactly what makes tampering dangerous if an application forgets to check the signature:

import base64, json def decode_jwt_part(part): padded = part + '=' * (-len(part) % 4) return json.loads(base64.urlsafe_b64decode(padded)) token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0Iiwicm9sZSI6ImFkbWluIiwiZXhwIjoxNzM1Njg5NjAwfQ.YTbPZkdWYl86Jcp-vaDFpCOFTNTiHa6YLEh4a3Qwy6M" header, payload, signature = token.split('.') print(decode_jwt_part(header)) # {'alg': 'HS256', 'typ': 'JWT'} print(decode_jwt_part(payload)) # {'sub': '1234', 'role': 'admin', 'exp': 1735689600} # No secret was needed to read this, only to forge a NEW valid signature.
M5 JWTs · Real-World Security Warning

alg: none & Algorithm Confusion

alg: none

The JWT spec defines an "unsecured" mode where alg is set to none and the signature is omitted. Early libraries trusted the alg field taken from the token itself, an attacker could rewrite the header to {"alg":"none"}, strip the signature, and edit the payload freely (e.g. "role":"admin"). Modern libraries hard-code the expected algorithm server-side, but this bug class still resurfaces in custom implementations.

Algorithm Confusion

If a server accepts both HS256 and RS256 and reuses the same key material for both, an attacker who obtains the RSA public key, public by design, can use it as the HMAC secret to sign a forged HS256 token.

Secret Brute-Forcing

A short or common HS256 secret can be cracked offline from a single captured token; once cracked, the attacker forges tokens indefinitely. Use a long, random, high-entropy secret (32+ bytes), or move to asymmetric signing.

06
Module 06 / 06

Entropy, Randomness & CSPRNGs

When "random" isn't: the entropy assumption every key generator depends on.

M6 Entropy & CSPRNGs · Key Concepts & Definitions

PRNG vs. TRNG vs. CSPRNG

PRNG

A deterministic algorithm that expands a seed into a long sequence that looks random

TRNG

A hardware source of randomness from physical entropy, thermal noise, clock jitter, radioactive decay

CSPRNG

A PRNG built so observing past outputs gives no computational advantage in predicting future ones

A generator can pass every statistical randomness test and still be completely insecure, statistical randomness and unpredictability-given-the-algorithm are different properties.

M6 Entropy & CSPRNGs · Mathematical / Algorithmic Explanation

Why the Mersenne Twister Isn't Safe

Python's built-in random module uses the Mersenne Twister (MT19937), excellent for simulations, unsafe for security, because its entire internal state is 624 32-bit words, and observing 624 consecutive outputs is enough to reconstruct that state exactly, after which every future (and past) output becomes predictable.

CSPRNG

Breaks that link by design: even given the full output history, computing the next output should be as hard as breaking the underlying cryptographic primitive. Operating systems expose this directly, /dev/urandom on Linux, BCryptGenRandom on Windows, and Python's secrets / os.urandom wrap them.

M6 Entropy & CSPRNGs · Code Walkthrough

A "Random" Token That Wasn't

import random, secrets # A PRNG seeded from something an attacker can guess or observe random.seed(1337) session_token = random.getrandbits(128) # The attacker reproduces the same seed -> reproduces the SAME output random.seed(1337) predicted_token = random.getrandbits(128) print("Match:", session_token == predicted_token) # True # The fix: an OS-backed CSPRNG, never seeded, never predictable print("CSPRNG token:", secrets.token_hex(16))
Match: True

The "random" token was never random once the seed was known. That single mechanism, a generator seeded from guessable material, is exactly what the case study below turned into a real, multi-million-dollar loss.

M6 Entropy & CSPRNGs · Case Study (1/3)

The Pseudo-Random Trap: Inside the Coldcard Firmware Flaw

In late July 2026, Coinkite (maker of the Coldcard Bitcoin hardware wallet) disclosed a firmware bug present since March 2021.

While integrating a new cryptographic library, an incorrect conditional check, testing whether a macro existed rather than whether it was enabled, caused affected firmware to silently fall through to a software PRNG (Yasmarang, bundled with the device's MicroPython runtime) instead of the device's dedicated STM32 hardware TRNG during seed generation.

Root Cause

Yasmarang was seeded only from the chip's unique ID and boot-time timer registers, with no further entropy collected afterward, both constrained, partially predictable values, not the "128 bits of physical noise" the wallet's design assumed.

M6 Entropy & CSPRNGs · Case Study (2/3)

Intended vs. Actual: and the Fallout

IntendedActual (affected firmware)
Entropy sourceSTM32 hardware TRNGYasmarang PRNG (software)
Seed strength128 bits~40 bits (Mk3) / ~72 bits (Mk4/Mk5/Q)
Search space~3.4 × 10³⁸~10¹², within reach of brute force

Because Yasmarang is deterministic and its seed material is constrained, an attacker able to narrow down a device's UID and boot-timer state could reproduce candidate seed streams entirely offline, then check each candidate by deriving its Bitcoin addresses and comparing them against the public blockchain.

Impact

The flaw went undetected for roughly five years. Once disclosed, on-chain researchers tracked rapid sweeps by more than a dozen independent attackers, draining well over a thousand BTC, tens of millions of dollars, within days; loss estimates were still being revised upward through early August 2026.

M6 Entropy & CSPRNGs · Case Study (3/3)

The Lesson for Security Engineers

Response

A firmware patch alone does not repair an already-weak key. Every seed generated on vulnerable firmware had to be treated as compromised and regenerated from scratch on fixed firmware, with funds migrated to a new wallet.

Who Was Safe

Users who had mixed in their own dice-roll entropy during setup, or used a strong, unique BIP-39 passphrase, were not at risk, independent entropy sources the flawed code path never touched.

Lesson

One silently substituted entropy source turned a hardware wallet, the gold standard for key isolation, into a device producing brute-forceable keys, for five years, undetected by the vendor's own review process. Never trust randomness by assumption. If a system's security depends on "this call returns cryptographically secure random bytes," that call needs to be tested and verified at the point of use.

End of Guide

Every module builds toward the same operational habit.

Before trusting a cryptographic primitive, know its key space, its failure mode, and what happens when its randomness assumption breaks. That habit, not memorized formulas, is what separates "the app has encryption" from an app that is actually hard to attack.

01 Foundations02 Classical03 Paradigms04 Hashing05 JWTs06 Entropy
01 / 42