A beginner-to-intermediate guide bridging classical cipher theory and modern applied cryptography.
| Level | Beginner → Intermediate |
| Prerequisites | Basic programming (Python), basic algebra. No prior cryptography background required. |
| Format | 6 modules, each combining theory, math, and working code |
| Suggested Pace | 2-3 hours per module, six study sessions, or one intensive week |
Explain, mathematically derive, implement, and critically evaluate the cryptographic primitives that secure modern systems, from a Caesar shift to an AES-GCM channel.
Click any module to jump there. Press M anytime to open the guide map.
Why cryptography exists, and what it actually promises.
Cryptography is the mathematics of transforming information so only intended parties can access or verify it. It sits inside a broader discipline:
Designing schemes that protect information
Breaking those schemes without authorized access
The umbrella field covering both
| Property | Question it answers | Cryptographic mechanism |
|---|---|---|
| Confidentiality | Can only the intended reader see this? | Encryption (symmetric / asymmetric) |
| Integrity | Has this data been altered? | Hash functions, MACs |
| Availability | Can authorized users reach it when needed? | Mostly outside cryptography, redundancy, DDoS defense |
| Non-repudiation | Can the sender deny sending this? | Digital signatures |
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.
Formally, an encryption scheme is a pair of functions:
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.
| Step | Property enforced | How |
|---|---|---|
| 1 | Confidentiality | Alice encrypts the PDF with Bob's public key, only Bob's private key can decrypt it |
| 2 | Integrity + Non-repudiation | Alice hashes the PDF and signs the hash with her private key, any edit changes the hash; only Alice's key produces a valid signature |
| 3 | Integrity check + Authenticity | Bob decrypts, re-hashes, and checks the signature with Alice's public key, a mismatch means tampering, or the wrong sender |
| 4 | Availability | The mailbox server is load-balanced across regions, architectural, not cryptographic |
Encrypt for confidentiality, hash for integrity, sign for non-repudiation, this is the backbone of HTTPS, signed software updates, and blockchain transactions alike.
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.
Every algorithm in this guide is public, peer-reviewed, and standardized, that transparency is a feature, not a risk.
Substitution, key space, and the statistical cracks that built modern cryptanalysis.
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.
| Cipher | Type | Core Idea |
|---|---|---|
| Caesar | Monoalphabetic substitution | Shift every letter by a fixed amount k |
| Affine | Monoalphabetic substitution | Apply a linear function ax + b to each letter |
| Vigenère | Polyalphabetic substitution | Shift each letter by a different amount, cycling through a keyword |
| Hill | Polygraphic substitution | Encrypt blocks of letters at once via matrix multiplication |
Letters map A=0, B=1, … Z=25; all arithmetic below is mod 26.
Key space: 25 usable keys (k=0 is the identity), trivially brute-forceable.
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.
For a keyword of length m:
Key space: 26^m, exponential in key length, but a repeating key leaks its own length statistically (see cryptanalysis).
Plaintext splits into vectors of size n; an n×n key matrix K encrypts by matrix multiplication:
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.
| Letter | x | 5x+8 | mod 26 | Cipher |
|---|---|---|---|---|
| H | 7 | 43 | 17 | R |
| E | 4 | 28 | 2 | C |
| L | 11 | 63 | 11 | L |
| L | 11 | 63 | 11 | L |
| O | 14 | 78 | 0 | A |
det(K) = 11, K⁻¹ = [[3,14],[9,5]]. Encrypting HI (H=7, I=8):
Multiplying [L,N] by K⁻¹ recovers [7,8] = HI.
English letters are far from uniform:
| Letter | E | T | A | O | I | N | … | Q | Z |
|---|---|---|---|---|---|---|---|---|---|
| Frequency | 12.7% | 9.1% | 8.2% | 7.5% | 7.0% | 6.7% | … | 0.10% | 0.07% |
The most frequent ciphertext letter is very likely the encryption of E.
Kasiski examination (repeated ciphertext segments infer key length) + the Index of Coincidence turns it back into several monoalphabetic ciphers.
Entirely linear, a known-plaintext attack (just n pairs for an n×n key) solves for K directly via linear algebra.
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.
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.
Symmetric speed meets asymmetric trust, and the standards that run the internet.
| Symmetric | Asymmetric | |
|---|---|---|
| Keys | One shared secret key | A mathematically linked public/private pair |
| Speed | Fast, suited to bulk data | ~100-1000× slower, suited to small data |
| Core problem solved | Confidentiality | Confidentiality and key distribution |
| Key distribution | n users need n(n−1)/2 pairwise secret keys | Each user publishes one public key; no shared secret required |
| Examples | AES, ChaCha20 | RSA, ECC, Diffie-Hellman |
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.
Fixed 128 bits (16 bytes), regardless of key size
128 / 192 / 256 bits → 10 / 12 / 14 rounds of substitution-permutation
A block cipher scrambles one 16-byte block; a mode chains many blocks together
| CBC | GCM | |
|---|---|---|
| Mechanism | Each plaintext block XORed with the previous ciphertext block before encryption | Counter-mode encryption combined with a GHASH authentication tag |
| Needs | A random IV, plus PKCS#7 padding to fill the last block | A unique nonce (96-bit standard); no padding |
| Integrity | None built in, ciphertext can be tampered with silently | Built in, decryption fails loudly if even one bit changes |
| Known risk | Padding-oracle attacks (e.g. POODLE) | Catastrophic key/tag recovery if a nonce is ever reused |
| Verdict | Legacy; needs a separate MAC (Encrypt-then-MAC) | Modern default, TLS 1.3, most VPNs |
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).
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.
Textbook-sized primes, never use numbers this small in practice.
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.
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.
1024-bit RSA is considered breakable by well-resourced attackers; 2048-bit is today's minimum, 3072/4096-bit for long-term protection.
GCM, ChaCha20-Poly1305 over CBC for new designs, integrity shouldn't be an afterthought bolted on separately.
Why hashing a password wrong is worse than not hashing it at all.
A cryptographic hash function maps arbitrary-length input to a fixed-length digest, with three defining properties:
| Property | Meaning |
|---|---|
| Pre-image resistance (one-way) | Given H(x), you cannot feasibly recover x |
| Collision resistance | You cannot feasibly find two different inputs that hash to the same output |
| Avalanche effect | Flipping one input bit changes roughly half the output bits |
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-256 | bcrypt | Argon2 | |
|---|---|---|---|
| Designed for | Integrity, checksums, signatures | Passwords | Passwords (2015 PHC winner) |
| Speed | Billions of hashes/sec on a GPU | Deliberately slow, tunable cost factor | Deliberately slow & memory-hard |
| Resists GPU/ASIC cracking | No | Somewhat | Yes, memory cost is expensive to parallelize in silicon |
| Call | SHA-256 (insecure) | bcrypt (secure) |
|---|---|---|
| Run 1 | 231ecc7d178d... | $2b$12$I/HxMXewCi... |
| Run 2 | 231ecc7d178d... (identical) | $2b$12$SmVWESPZWX... (different) |
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.
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.
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.
A signed claim isn't a secret, and forgetting that breaks authentication.
A JWT is a compact, URL-safe string with three base64url-encoded parts joined by dots:
| Part | Contents | Decoded example |
|---|---|---|
| Header | Algorithm + token type | {"alg":"HS256","typ":"JWT"} |
| Payload | Claims, data about the subject | {"sub":"1234","role":"admin","exp":1735689600} |
| Signature | Proof header+payload weren't altered | HMAC-SHA256(base64(header)+"."+base64(payload), secret) |
The payload is only encoded, not encrypted. Anyone can base64-decode a JWT and read its claims, never put secrets in the payload.
| HS256 (HMAC) | RS256 (RSA) | |
|---|---|---|
| Key type | One symmetric secret | Asymmetric key pair |
| Who can sign | Anyone holding the shared secret | Only the private key holder |
| Who can verify | Anyone holding the same shared secret | Anyone with the public key |
| Risk if a key leaks | Every verifier can also forge tokens | Public key leaking is fine, only signing capability matters |
Exactly what makes tampering dangerous if an application forgets to check the signature:
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.
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.
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.
When "random" isn't: the entropy assumption every key generator depends on.
A deterministic algorithm that expands a seed into a long sequence that looks random
A hardware source of randomness from physical entropy, thermal noise, clock jitter, radioactive decay
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.
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.
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.
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.
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.
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.
| Intended | Actual (affected firmware) | |
|---|---|---|
| Entropy source | STM32 hardware TRNG | Yasmarang PRNG (software) |
| Seed strength | 128 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.
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.
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.
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.
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.
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.