Computer Network 📂 Information Security · 1 of 2 54 min read

Cryptography Basics

Master the mathematics of digital secrets — from AES-256 symmetric encryption and RSA/ECC asymmetric keys to hybrid encryption powering every HTTPS connection. Features four animated diagrams (side-by-side comparison, AES pipeline, RSA public/private key exchange, TLS hybrid handshake), block cipher modes (ECB Penguin), digital signatures, SHA-256 hashing, real incidents (Heartbleed, SHAttered, Apple vs FBI), and the coming post-quantum transition.

Section 01

Cryptography — The Mathematics of Secrets

The Padlock and the Postbox
Imagine you want to send a valuable diamond by post to a friend across the world. You cannot trust the postal service — anyone along the way could open the box.

Approach 1 — Symmetric: You and your friend meet in person years ago and exchange two copies of the same key. You put the diamond in a locked box using your key and post it. Your friend opens it with the identical key. Fast, simple, secure — but you had to meet in person first.

Approach 2 — Asymmetric: Your friend keeps a padlock — the kind that clicks shut without a key — and sends the open padlock to you. You place the diamond in a box, snap the padlock shut, and mail it. Only your friend has the key to open the padlock. You never needed to meet — the whole world could see the open padlock travel to you, and it would not matter.

That is the entire idea. Symmetric = shared secret key. Asymmetric = a public padlock and a private key. Modern security uses both together.

Cryptography is the science of protecting information so that only the intended parties can read it. Every HTTPS connection, every WhatsApp message, every bank transaction, every SSH login, and every Bitcoin transfer relies on cryptographic primitives. Without cryptography, there would be no e-commerce, no online banking, no private messaging, and no secure remote work.

📌
The Four Goals of Cryptography — CIAN

Confidentiality — only authorised parties can read the data. Achieved by encryption.

Integrity — the data has not been altered in transit. Achieved by hash functions and MACs.

Authentication — the sender is who they claim to be. Achieved by digital signatures and MACs.

Non-repudiation — the sender cannot later deny sending the message. Achieved by asymmetric digital signatures.

📶 Core Cryptography Vocabulary
Plaintext
The original readable message before encryption. Also called "cleartext."
Ciphertext
The scrambled unreadable output after encryption. Should look statistically random to anyone without the key.
Key
The secret parameter that controls the encryption/decryption transformation. Same algorithm + different key = different ciphertext.
Cipher
The algorithm itself (AES, RSA, ChaCha20). Public knowledge — security must not depend on hiding the algorithm (Kerckhoffs's principle).
Cryptanalysis
The art of breaking ciphers — finding weaknesses that let an attacker recover plaintext or key without permission.
Key Space
The set of all possible keys. AES-256 has 2256 ≈ 1077 keys — more than atoms in the observable universe.

Section 02

🏭 Animated: Symmetric vs Asymmetric — Side by Side

The animation below shows the fundamental difference between the two encryption families. Watch how each scheme handles a message from Alice to Bob — where the keys come from, how they are exchanged, and what happens if an eavesdropper (Eve) tries to intercept the traffic.

▶ Symmetric (Shared Key) vs Asymmetric (Public/Private Key)
Click Play to compare both approaches

💡 Notice the critical difference: symmetric encryption requires a secure channel to exchange the key beforehand — the chicken-and-egg problem. Asymmetric encryption solves this — Bob's public key can travel via any insecure channel (email, SMS, billboard). Only Bob's private key can decrypt.


Section 03

Symmetric Encryption — One Key for Both Sides

Symmetric encryption uses the same key to encrypt and decrypt. It is fast — modern CPUs have hardware-accelerated instructions (AES-NI) that encrypt gigabytes per second. It is compact — a 256-bit key is only 32 bytes. And it is mathematically simple compared to asymmetric schemes. But it has one fatal weakness: how do the two parties agree on the key in the first place?

🔑
AES — Advanced Encryption Standard
NIST FIPS 197 · 2001 · Block cipher
The dominant symmetric cipher on Earth. Standardised by NIST in 2001 (originally called Rijndael, designed by two Belgian cryptographers Daemen and Rijmen). Block size: 128 bits. Key sizes: 128, 192, or 256 bits. Used by every HTTPS connection, every disk encryption, every VPN. Hardware-accelerated on all modern CPUs (AES-NI).
✓ NSA approved for TOP SECRET · ✓ Hardware accelerated · ✓ No known practical attacks
🔨
ChaCha20 — Stream Cipher Alternative
Designed by Bernstein · 2008 · Stream
A stream cipher used where AES hardware acceleration is unavailable — primarily on mobile ARM CPUs. Used by TLS 1.3 (as ChaCha20-Poly1305), Google Chrome, WireGuard VPN, and Signal Protocol. Simpler than AES, resistant to timing attacks, and faster in software. 256-bit key, 96-bit nonce.
✓ Software-fast · ✓ Timing-attack resistant · ✓ Simple implementation
🚩
DES / 3DES — Historic and Deprecated
1977 · Block cipher · BROKEN
DES (Data Encryption Standard) had a 56-bit key — brute-forced in 1998 in under 24 hours by the EFF's "Deep Crack" machine costing $250K. 3DES applied DES three times for 168-bit effective security but was slow and finally deprecated by NIST in 2023. Do not use for any new system. Still found in legacy banking, ATM PIN encryption, and some SIM cards.
✗ 56-bit DES: brute-forced in hours · ✗ 3DES deprecated 2023 · ✗ Legacy only

Block Cipher Modes — How to Encrypt More Than One Block

A block cipher like AES only encrypts one fixed block (128 bits = 16 bytes) at a time. To encrypt a longer message you need a mode of operation. The mode choice is as important as the cipher itself — using the wrong mode can catastrophically weaken otherwise strong encryption.

ModeFull NamePropertyUse Today
ECBElectronic Code BookIdentical blocks → identical ciphertext (leaks patterns)Never — insecure
CBCCipher Block ChainingChains blocks; needs IV; vulnerable to padding-oracle attacksLegacy — being phased out
CTRCounter ModeTurns block cipher into stream cipher; parallelisableWidely used
GCMGalois/Counter ModeCTR + authentication tag; AEADModern standard (TLS 1.2/1.3)
CCMCounter with CBC-MACAuthenticated encryption; used in WPA2, IPsecWidely used
XTSXEX-based Tweaked CodebookSector-level disk encryptionBitLocker, LUKS, FileVault
⚠️
The ECB Penguin — Why Mode Matters

In 2004, cryptographer Bart Preneel encrypted the Linux mascot Tux the Penguin image using AES in ECB mode. The result was famous: the outline of the penguin was still clearly visible in the ciphertext, because identical blocks of pixels (the white background, the black body) all encrypted to identical ciphertext blocks. This is why ECB mode leaks structural information — even a strong cipher becomes useless. This image is now the canonical example in every cryptography course of why "just use AES" is not enough — the mode of operation matters equally.

🏭 Animated: AES Encryption Step-by-Step

▶ Symmetric Encryption Pipeline — Alice Sends "MEET AT NOON" to Bob
Ready

💡 The exact same key (K) is used by Alice for encryption and Bob for decryption. The ciphertext (X!Kz#Q9NmB@r) reveals nothing about the plaintext — statistically random. If Eve intercepts the ciphertext without the key, she gets nothing useful.


Section 04

Asymmetric Encryption — The Public/Private Key Revolution

Asymmetric encryption (also called public-key cryptography) was invented in 1976 by Whitfield Diffie and Martin Hellman — arguably the most important idea in the history of communication security. It solved a problem that had seemed unsolvable for thousands of years: how do you agree on a shared secret with someone you have never met, over an insecure channel?

The key insight: use two mathematically linked keys. What one encrypts, only the other can decrypt. Publish one (public key) so anyone can send you encrypted messages. Keep the other secret (private key) so only you can read them.

🔑 Public Key (openly shared)
PropertyBehaviour
SharedFreely with everyone
Used forEncrypting messages to you
Verifying your signatures
Size2048–4096 bits (RSA)
256 bits (Ed25519)
DistributionEmail, website, keyservers, X.509 certificate
If compromisedNo damage — was public anyway
AnalogyOpen padlock — anyone can lock things with it
🔐 Private Key (never shared)
PropertyBehaviour
SharedNEVER — this is the crown jewel
Used forDecrypting messages sent to you
Signing outgoing messages
SizeSame key length as public key
StorageEncrypted on disk with a passphrase
HSM, YubiKey, or secure enclave
If compromisedTotal breach — attacker impersonates you
AnalogyThe only key to your padlock
🔑
RSA — Rivest, Shamir, Adleman
1977 · Based on integer factorisation
The classic asymmetric cipher. Security rests on the difficulty of factoring the product of two large prime numbers. Typical key size today: 2048 or 4096 bits. Used for SSH keys, TLS certificates, PGP email, and code signing. Being gradually replaced by elliptic curve schemes because RSA keys must be huge (3072-bit RSA ≈ 128-bit AES security).
✓ Battle-tested 45+ years · ✓ Wide support
✗ Slow · ✗ Huge keys · ✗ Quantum-vulnerable
⚙️
ECC — Elliptic Curve Cryptography
1985 · Based on ECDLP problem
Uses the mathematics of points on elliptic curves. A 256-bit ECC key gives the same security as a 3072-bit RSA key — much faster and smaller. Curves in use: NIST P-256, secp256k1 (Bitcoin), Curve25519 (Signal, WireGuard). ECDSA is the digital signature algorithm; ECDH is the key exchange. Modern TLS 1.3 defaults to ECC.
✓ Small keys · ✓ Fast · ✓ Mobile-friendly
✗ Curve choice matters · ✗ Quantum-vulnerable
🔁
Diffie-Hellman Key Exchange
1976 · Establishes shared secret
Not an encryption scheme — a key agreement scheme. Two parties independently compute the same shared secret over an insecure channel without ever transmitting it. The number crossing the wire looks random. Used in every TLS handshake, WireGuard, IPsec, and Signal Protocol. Modern variant: ECDH (Elliptic Curve DH) using Curve25519.
✓ No shared secret ever transmitted · ✓ Forward secrecy

🏭 Animated: RSA in Action — Alice Sends Bob an Encrypted Message

▶ Asymmetric Encryption Pipeline — With and Without Bob's Private Key
Ready

💡 Notice: Bob's public key travels openly — Eve sees it, but it does not help her decrypt. Only Bob's private key (which never leaves Bob's machine) can decrypt what was encrypted with the public key. This is the mathematical asymmetry that makes public-key cryptography possible.


Section 05

Hybrid Encryption — The Best of Both Worlds

Asymmetric encryption is slow — around 1,000× slower than AES. You would never encrypt a 4 GB video with RSA. But asymmetric encryption solves key exchange perfectly. So every modern secure protocol uses hybrid encryption: asymmetric to exchange a fresh symmetric key, then symmetric for the actual data. This is how TLS, PGP, Signal, and WhatsApp all work under the hood.

▶ Hybrid Encryption — How TLS/HTTPS Actually Works
Ready

💡 Every HTTPS connection you make does exactly this: asymmetric for a few hundred bytes to exchange a session key, then AES-GCM (symmetric) for the actual page data. This gives you the security of asymmetric key exchange with the speed of symmetric encryption.


Section 06

Digital Signatures & Hash Functions

Encryption keeps messages secret. But how do you prove a message came from you? And how do you detect if it was modified? For these, cryptography uses hash functions and digital signatures.

📈
Hash Functions — Fingerprints for Data
A cryptographic hash is a one-way function that takes any input (a byte, a gigabyte, or Wikipedia) and produces a fixed-length output — a "fingerprint." Small change in input → completely different fingerprint (avalanche effect). Impossible to reverse: you cannot recover the input from the hash.

Modern hashes: SHA-256 (Bitcoin, TLS, Git), SHA-3 (successor standard), BLAKE3 (fast).
Broken/deprecated: MD5 (collisions since 2004), SHA-1 (broken by Google's SHAttered attack, 2017).
SHA-256 · SHA-3 · One-way · Fixed 256-bit output · Fingerprints
✍️
Digital Signatures — Sign with Private, Verify with Public
A digital signature is asymmetric encryption in reverse: you encrypt a message's hash with your private key — producing a signature. Anyone with your public key can decrypt it and check the hash matches — proving you signed it (only you have the private key) and the message was not modified.

Algorithms: RSA-PSS, ECDSA (Bitcoin, TLS), Ed25519 (SSH, Signal — modern favourite).
Provides all three: authentication + integrity + non-repudiation.
ECDSA · Ed25519 · Sign(privK) → Verify(pubK) · Non-repudiation
🔒
MACs — Message Authentication Codes
A MAC is a hash combined with a shared symmetric key. Anyone with the key can verify the message came from someone who also has the key AND was not modified — but cannot prove which of the two parties sent it (no non-repudiation). Fast — used inside every AES-GCM and ChaCha20-Poly1305 packet.

Algorithms: HMAC-SHA256 (JWT, API auth), Poly1305 (paired with ChaCha20 in TLS 1.3).
Provides: authentication + integrity, but no non-repudiation.
HMAC-SHA256 · Poly1305 · Shared key · Symmetric authentication
SHA-256 EXAMPLES — THE AVALANCHE EFFECT
Input: "Hello, world!" SHA-256: 315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3 Input: "Hello, world!" ← added trailing dot: "Hello, world!." SHA-256: 08b1ff2d1354d4f77b6bebb2ebc4c25b3ec7cf70bff9e00f57ec98a4b0be1e12 └── Completely different — one bit changed, entire hash changes. Input: The entire text of Wikipedia (~50 GB) SHA-256: a19f8...c3e42 ← still exactly 64 hex characters (256 bits) Fixed output size regardless of input size.

Section 07

Where You Use Cryptography Every Day

🌐
HTTPS / TLS 1.3
Every web page you load
Uses ECDHE (asymmetric key exchange) + AES-GCM or ChaCha20-Poly1305 (symmetric encryption) + ECDSA/RSA (server authentication via certificate). Textbook hybrid encryption.
📱
WhatsApp & Signal
End-to-end encrypted messaging
Signal Protocol: X3DH (asymmetric) for initial key agreement + Double Ratchet + AES-256 (symmetric) for each message. Even the servers cannot read your messages. Used by 3 billion people.
💰
Bitcoin & Blockchain
ECDSA + SHA-256
Every Bitcoin address is derived from an ECDSA public key on the secp256k1 curve. Every transaction is signed by your private key. Every block header is a SHA-256 hash chain. Cryptography IS Bitcoin.
🔑
SSH — Secure Shell
Server login without passwords
You generate an Ed25519 or RSA key pair. Your public key sits on the server in ~/.ssh/authorized_keys. Server sends a challenge; you sign it with your private key; server verifies. No password ever transmitted.
💾
Full-Disk Encryption
BitLocker, FileVault, LUKS
Your laptop's disk is encrypted with AES-XTS-256. The disk-encryption key is unlocked at boot by your password or TPM chip. If your laptop is stolen, the data is unreadable without the password.
🔔
Payment Cards (EMV)
Chip-and-PIN
Every chip card contains a small computer that stores an RSA private key. When you tap or insert, the terminal challenges the chip to prove its identity by signing a transaction — cryptography prevents card cloning.

Section 08

Real-World Cryptography Incidents

💥
2014 — Heartbleed: The Bug That Read Server Memory
CVE-2014-0160 — a two-year-old bug in OpenSSL's TLS heartbeat extension let attackers read up to 64 KB of server memory per malformed request, repeatedly. The stolen memory often contained private keys, session tokens, and passwords. Affected over 500,000 HTTPS servers including Yahoo, Imgur, and OKCupid. Even though the cryptography (AES, RSA) was mathematically sound, an implementation bug in the crypto library leaked the private keys. Demonstrates that the strongest algorithm is only as secure as its implementation. Source: Cloudflare blog "Answering the critical question: Can you get private SSL keys using Heartbleed?"; The Guardian, April 2014.
CVE-2014-0160 · OpenSSL · Private key leak · 500K servers · 2014
🔥
2017 — SHAttered: SHA-1 Officially Broken
Google and CWI Amsterdam published the first practical SHA-1 collision — two different PDF documents with the same SHA-1 hash, generated using 6,500 CPU-years of compute. This confirmed what cryptographers had warned about since 2005. Git, subversion, TLS certificates, and countless legacy systems relied on SHA-1. All major browsers had already deprecated SHA-1 TLS certificates by 2017. Every developer now uses SHA-256 or SHA-3. Source: Google Security Blog "Announcing the first SHA1 collision," February 2017; shattered.io.
SHA-1 collision · Google research · Hash function broken · 2017
📲
2016 — Apple vs FBI: The San Bernardino iPhone
The FBI demanded Apple create a backdoor to unlock an iPhone 5C recovered from a terrorism suspect. The phone used AES-256 encryption tied to a passcode, with 10 failed attempts erasing the key. Apple refused publicly, arguing that a backdoor would weaken security for all iPhone users. The FBI eventually paid a third party (rumoured to be Cellebrite) around $900,000 for a zero-day exploit. The case set the modern political precedent for the "going dark" debate — strong crypto vs law enforcement access. Source: The New York Times "FBI Paid More Than $1 Million to Hack San Bernardino iPhone," April 2016.
Apple vs FBI · AES-256 · Going dark debate · Encryption backdoor · 2016

Section 09

The Quantum Threat & Post-Quantum Cryptography

Every public-key algorithm we use today — RSA, ECDSA, Diffie-Hellman, ECDH — will be broken by a sufficiently large quantum computer running Shor's algorithm. It is not a question of if, but when. Symmetric algorithms (AES) are only weakened by Grover's algorithm — AES-256 becomes effectively 128-bit secure against quantum attackers, still safe. But every asymmetric key ever used will eventually be crackable if intercepted and stored.

⚠️
"Harvest Now, Decrypt Later" — The Silent Threat

Intelligence agencies and adversaries are believed to be already collecting encrypted traffic and storing it — waiting for practical quantum computers to be built. Anything you transmit today under RSA or ECDH could be decrypted in 10–20 years. This is why the migration to post-quantum cryptography (PQC) has begun urgently. In August 2024, NIST published the first PQC standards: ML-KEM (Kyber — key encapsulation) and ML-DSA (Dilithium — signatures). Cloudflare, Google, and Apple have already deployed hybrid classical + post-quantum key exchange in production TLS.

Algorithm TypeQuantum Vulnerable?Fix
AES-128 (symmetric)Weakened (Grover — 64-bit effective)Use AES-256
AES-256 (symmetric)Safe (128-bit effective — still secure)No change needed
SHA-256 (hash)Safe (128-bit collision resistance)No change needed
RSA-2048 / RSA-4096Completely broken by Shor's algorithmMigrate to ML-KEM (Kyber) + ML-DSA
ECDSA / ECDH (P-256, Ed25519)Completely broken by Shor's algorithmMigrate to ML-DSA (Dilithium)
Diffie-HellmanCompletely broken by Shor's algorithmMigrate to ML-KEM (Kyber)

Section 10

Golden Rules — Cryptography in Practice

📌 Non-Negotiable Rules for Every Developer & Engineer
1
Never invent your own cryptography. Every serious cryptographic algorithm is peer-reviewed for years by dozens of cryptanalysts before deployment. "It looks strong to me" is not a security argument. Use battle-tested libraries: libsodium, OpenSSL, or your language's standard cryptography module. Rolling your own AES or writing a "clever" custom cipher is how catastrophic breaches happen.
2
Use AES-256-GCM or ChaCha20-Poly1305 for symmetric encryption — never ECB. GCM and Poly1305 provide authenticated encryption — they detect tampering. Plain AES-CBC without a MAC is vulnerable to padding-oracle attacks. ECB mode leaks patterns (the ECB Penguin). If you find yourself typing AES.MODE_ECB, stop. Use AEAD ciphers only.
3
Prefer Ed25519 for signatures and X25519 for key exchange. Modern elliptic curve algorithms designed by Daniel Bernstein. Small keys (32 bytes), fast, and immune to many classical implementation pitfalls (e.g. no bad random nonces breaking your key like ECDSA has). Used by SSH, Signal, WireGuard, and TLS 1.3. Fall back to ECDSA/RSA only when interoperability requires it.
4
Never reuse keys across purposes. A key used for encryption should never also sign. A key used for TLS should never be used for SSH. A separate key per purpose limits the damage of any single key compromise. This is called "key separation" and is a fundamental design principle in every serious cryptographic system.
5
Generate keys with a cryptographically secure RNG — never Math.random(). Use /dev/urandom, getrandom(), or crypto.randomBytes(). A predictable random source destroys any encryption scheme built on top of it. In 2013, Bitcoin wallets on Android lost funds because of a broken RNG in the SecureRandom class that reused values across apps — allowing attackers to derive private keys.
6
Store private keys in hardware where possible. A YubiKey, HSM, TPM, or Apple Secure Enclave keeps private keys inside tamper-resistant hardware — the key never leaves. Signing happens inside the chip. Even if the host OS is fully compromised, the attacker cannot exfiltrate the key. For high-value keys (signing production releases, CA keys, cryptocurrency cold storage), this is not optional.
7
Plan for the post-quantum transition today. NIST has standardised ML-KEM (Kyber) and ML-DSA (Dilithium). Cloudflare, Google, and Apple have deployed hybrid classical + PQC key exchange in production. If your systems will still be operating in 2030+, or if you handle data with a long confidentiality lifetime (medical, legal, national security), you should already be inventorying every use of RSA and ECC and planning migration.
🎓
The Complete Picture

Cryptography makes the digital world possible. Without it, there is no online banking, no private messaging, no e-commerce, no blockchain, and no remote work.

Symmetric encryption (AES, ChaCha20) is fast and compact — perfect for bulk data — but requires two parties to share a key in advance. Asymmetric encryption (RSA, ECC, Diffie-Hellman) is slow and key-heavy — but solves the key-exchange problem so completely that we can communicate securely with strangers over an insecure Internet.

Hybrid encryption combines them: asymmetric for the handshake, symmetric for the bulk. This is how TLS, SSH, WhatsApp, and Signal work. Add hash functions (SHA-256) for integrity and digital signatures (Ed25519, ECDSA) for authentication, and you have the full toolkit of modern secure communication.

From the RSA key on your SSH key ring to the AES engine in your CPU, from every HTTPS padlock to every Bitcoin transaction — cryptography is the mathematical foundation of digital trust. Understand it well: it is your first, last, and best line of defence in a networked world.