Science of
Secrets
Cryptography is the practice of securing communication in the presence of adversaries. It is the bedrock of digital trust.
The CIA Triad
Confidentiality
Ensuring data is only accessible to authorized parties. (Encryption)
Integrity
Ensuring data has not been modified or corrupted. (Hashing)
Availability
Ensuring authorized users have access to systems. (Redundancy)
Evolution of Ciphers
Before computers, cryptography was a game of substitution and transposition. These methods are no longer secure but form the foundation of modern thinking.
Caesar Cipher
SubstitutionShifts each letter by a fixed number of positions down the alphabet. Shift 3: A → D.
The Math
C = (P + k) mod 26
P = (C - k) mod 26
Where P is plaintext, C is ciphertext, and k is the shift.
Implementation
Iterate through each character, convert to 0-25 (A=0, B=1...), add the shift, and apply modulo 26 to wrap around.
Monoalphabetic
Static MappingUses a fixed random mapping (Permutation) for the entire alphabet. Highly vulnerable to Frequency Analysis.
Vulnerability: Frequency Analysis
In English, 'E' appears ~12.7% of the time. If the most common character in a monoalphabetic ciphertext is 'X', it's highly likely 'X' maps to 'E'. By mapping known language frequencies to the ciphertext, the code can be reverse-engineered without the key.
Vigenère Cipher
PolyalphabeticFlattening frequency analysis by using a keyword to apply different shifts to each letter.
The Math
Ci = (Pi + Ki mod l) mod 26
Where l is the key length. Each letter of the key determines the shift for the corresponding letter of the message.
Implementation
A Caesar cipher with a varying shift. The shift is determined by the position of the key letter in the alphabet (A=0, B=1...).
Playfair Cipher
Bigram substitutionEncrypts pairs of letters (bigrams) using a 5x5 grid.
Bigram Rules
Rail Fence
TranspositionWrites messages in a zigzag pattern and reads them row-by-row.
Transposition Algorithm
Unlike substitution, transposition does not change the characters themselves, only their positions. The rail fence algorithm uses a zigzag pattern:
- Establish N rails (rows).
- Write the message character-by-character in a wave: down through the rails, then up.
- Read off the characters row-by-row to form the ciphertext.
Hiding in Plain Sight
While cryptography scrambles a message to make it unreadable, Steganography hides the existence of the message itself. If an adversary doesn't know a message exists, they won't try to decrypt it.
Steganography vs Cryptography
Cryptography:
"I have a secret, but I'm not telling you what it is."
Steganography:
"I don't even have a secret. This is just a normal cat photo."
Common Carriers
- Images (Pixel data)
- Audio (Background noise)
- Text (Whitespace and invisible chars)
- Network Packets (Header fields)
How it works: LSB (Least Significant Bit)
Images are made of Red, Green, and Blue (RGB) values from 0-255. By changing the last bit (LSB) of each value, we only change the color by 1 unit out of 256—a change invisible to the human eye but readable by a computer.
Generating Randomness
Cryptography relies on unpredictability. Since computers are deterministic, we use Pseudorandom Number Generators (PRNGs) to create sequences that appear random but are actually calculated using mathematical formulas starting from a seed.
Linear Congruential Generator (LCG)
Statistical RandomOne of the oldest PRNGs. Fast, but not cryptographically secure because its parameters can be discovered by observing the output sequence.
Anatomy of LCG
- Seed (X₀): The initialization value. Every sequence starts here.
- Multiplier (a): Controls the "jump" between numbers. Must be chosen carefully to maximize the period.
- Increment (c): A constant added in each step. If c=0, it's called a Multiplicative LCG.
- Modulus (m): The upper bound. Determines the maximum possible unique numbers before the sequence repeats.
How it Works
The generator takes the current value, multiplies it, adds an increment, and then takes the remainder (modulo). The Modulus is like a circular track; once you hit the limit, you wrap back around to the start.
LCG Algorithm Flow
The output Xn+1 becomes the next seed for the iteration.
Blum-Blum Shub (BBS)
CSPRNGA Cryptographically Secure PRNG. Its security relies on the hardness of the Quadratic Residuosity Problem (factoring large numbers).
The BBS Components
- Seed (s): A random starting integer that must be coprime to M.
- Modulus (M): Equal to n = p × q. Finding p and q from M is the "Hard Problem" that secures BBS.
- Least Significant Bit: BBS doesn't output the whole number, but just the remainder when divided by 2 (0 or 1).
Cryptographic Strength
Unlike LCG, which reveals its internal state, BBS extracts only a 1-bit "snapshot" of its state. To predict the next bit, an attacker would have to solve the Quadratic Residuosity Problem, which is currently impossible for large numbers.
BBS Algorithm Flow
Security: Predictability = Factoring M.
Symmetric Key Cryptography
Uses the same key for both encryption and decryption. Fast and efficient, but requires a secure way to share the key.
Hello
Cipher
Examples
AES-256, ChaCha20, DES
Best For
Bulk data encryption, Disk encryption.
Asymmetric Encryption (RSA)
Uses a Pair of Keys: a Public Key for encryption and a Private Key for decryption. It solves the key distribution problem but is significantly slower than symmetric encryption.
(Shared with Everyone)
(Keep Secret)
The RSA Math (Trapdoor)
It is easy to multiply two large prime numbers (P × Q = N). It is extremely hard to find P and Q given only N.
Diffie-Hellman Key Exchange
A method for two parties to establish a shared secret over an insecure channel. Neither party ever sends the final secret; instead, they mix their private keys with public parameters to derive the same result.
The Color Analogy
Diffie-Hellman is like mixing paint. It's easy to mix two colors to get a third, but nearly impossible to separate the original colors from the mixture.
Alice and Bob exchange their public mixtures. By adding their own secret color to the received mixture, they both arrive at the exact same final brown paint, which an eavesdropper cannot recreate without one of the original secret colors.
Elliptic Curve Cryptography (ECC)
The modern standard for public-key cryptography. Unlike RSA which uses large prime factors, ECC uses the algebraic structure of elliptic curves. It provides the same security as RSA but with much smaller key sizes.
Point Addition on a Curve
Security: k = P + P + ... + P (k times)
Security Equivalent Key Sizes
| Security | RSA Key | ECC Key |
|---|---|---|
| 80-bit | 1024 bit | 160 bit |
| 128-bit (Standard) | 3072 bit | 256 bit |
| 256-bit (Ultra) | 15360 bit | 512 bit |
ECC's efficiency makes it ideal for smartphones, IoT devices, and fast web connections.
Why is it secure?
The Elliptic Curve Discrete Logarithm Problem (ECDLP): Given points P and Q, it's easy to calculate Q = kP. However, if you only have P and Q, it's computationally impossible to find 'k'. This is the mathematical "trapdoor" that secures billions of daily transactions.
Man-in-the-Middle (MITM)
A critical vulnerability in public-key exchange. If an attacker (Eve) intercepts the initial exchange, she can impersonate both parties, convincing Alice she's Bob and vice versa.
Alice
Eve
Bob
Click to visualize how Eve intercepts the key exchange and message.
The Solution: Authentication
To prevent MITM, we need Proof of Identity. Alice needs to know the public key she received actually belongs to Bob. This is achieved using Digital Signatures and Certificates issued by trusted Third Parties (Certificate Authorities).
Symmetric Key Distribution (Symmetric Encryption)
In a large network, sharing a unique secret key between every pair of users is impractical (n(n-1)/2 keys). Instead, a trusted Key Distribution Center (KDC) is used. Alice and Bob each share a unique master key with the KDC.
Request: Alice asks for a key to talk to Bob (IDA || IDB || N1).
Response: KDC sends Alice E(K_A, [K_S || Request || E(K_B, [K_S || ID_A])]). Alice extracts the session key K_S and forwards the rest to Bob.
Key Distribution (Asymmetric Encryption)
The modern standard (used in TLS). Instead of a KDC, Alice uses Bob's Public Key to securely deliver a symmetric session key. This combines the speed of Symmetric encryption with the easy key sharing of Asymmetric.
Alice creates a random 256-bit key.
She encrypts it with Bob's RSA/ECC Public Key.
Digital Envelope
Symmetric Key inside Asymmetric Box
One-Way Hashing
A Hash Function maps data of any size to a fixed-size string. It is one-way and deterministic.
SHA-256 Hash Function
Out: 2bd80...f8d
Out: a3e10...9bb
Collision Resistant
Impossible to find two different inputs that produce the same hash.
Avalanche Effect
A tiny change in input (e.g. 'a' to 'A') results in a completely different hash.
Digital Signatures
A digital signature provides Integrity (the data wasn't changed) and Non-repudiation (the sender cannot deny sending it). It's essentially an encrypted hash of the message.
Signing (Alice)
X.509 Digital Certificates
To trust a Public Key, we use a Digital Certificate. It's an electronic document that binds a Public Key to an identity (like a website), signed by a trusted Certificate Authority (CA).
X.509 Certificate
v3 / RFC 5280CN=google.com
DigiCert Global CA G2
The Chain of Trust
Pre-installed in OS
Delegated Trust
google.com
TLS/SSL Handshake
The process that secures HTTP connections (HTTPS) through encryption and authentication.
Firewalls & VPNs
Security isn't just about encryption; it's also about controlling access and protecting data in transit across untrusted networks.
Firewall (Packet Filtering)
Firewalls inspect packets and apply Access Control Lists (ACLs) to block malicious traffic.
Virtual Private Network (VPN)
VPNs use Encapsulation to hide your traffic and Encryption to protect its content.
Post-Quantum Cryptography (PQC)
The Quantum Threat
Universal Quantum Computers running Shor's Algorithm can factor large numbers in seconds, effectively breaking RSA, ECC, and Diffie-Hellman.
Algorithm Death Toll:
- - RSA (Prime Factorization) - Vulnerable
- - ECC (Discrete Log) - Vulnerable
- - AES-256 - Quantum Resistant
The Resistance
NIST is standardizing new algorithms that even quantum computers can't crack. Most are based on complex Lattice Mathematics.
Key Definitions
Plaintext
The original, readable message before encryption.
Ciphertext
The encrypted, unreadable message produced by an algorithm.
Entropy
The randomness or unpredictability of data. High entropy is essential for secure keys.
Salting
Adding random data to a password before hashing to prevent rainbow table attacks.
Steganography
The art of hiding a message within another message or physical object.
Digital Signature
A mathematical scheme for demonstrating the authenticity of digital messages.
Zero-Knowledge Proof
Proving you know something without revealing the information itself.
Forward Secrecy
A property ensuring that compromise of one key does not compromise past keys.