Cryptography & Security

Science of
Secrets

Cryptography is the practice of securing communication in the presence of adversaries. It is the bedrock of digital trust.

01.1 / Core Principles

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)

01.2 / Timeline

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

Substitution

Shifts each letter by a fixed number of positions down the alphabet. Shift 3: A → D.

KHOOR
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 Mapping

Uses a fixed random mapping (Permutation) for the entire alphabet. Highly vulnerable to Frequency Analysis.

"Common letters like 'E' and 'T' still appear with the same relative frequency, making this trivial to break."
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

Polyalphabetic

Flattening frequency analysis by using a keyword to apply different shifts to each letter.

LXFOPV
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 substitution

Encrypts pairs of letters (bigrams) using a 5x5 grid.

Rules Applied:
  • Rectangle: Swap corners
  • Same Row: Shift Right
  • Same Column: Shift Down
Output:
Bigram Rules
Rectangle: Letters are at corners; swap with other corners in same row.
Same Row: Shift each letter right (wrap around).
Same Column: Shift each letter down (wrap around).

Rail Fence

Transposition

Writes 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:

  1. Establish N rails (rows).
  2. Write the message character-by-character in a wave: down through the rails, then up.
  3. Read off the characters row-by-row to form the ciphertext.
01.3 / Covert Channels

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.

01101000
RGB (Red)
Click to hide inside pixel

> Binary: Original bit: 0

> Visual: No change detected by human retina.

> Logic: Bit replaced successfully.

01.4 / Randomness

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 Random

One of the oldest PRNGs. Fast, but not cryptographically secure because its parameters can be discovered by observing the output sequence.

// LCG 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
Seed (Xn)
× Multiplier (a)
+ Increment (c)
mod Modulus (m)
Xn+1

The output Xn+1 becomes the next seed for the iteration.

Blum-Blum Shub (BBS)

CSPRNG

A Cryptographically Secure PRNG. Its security relies on the hardness of the Quadratic Residuosity Problem (factoring large numbers).

M should be the product of two large primes p,q where p,q ≡ 3 (mod 4).

// BBS Bitstream (Xₙ mod 2)
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
Seed (xn)
Square (x2)
mod M (p × q)
xn+1
Output Bit: xn+1 mod 2

Security: Predictability = Factoring M.

02.1 / Encryption

Symmetric Key Cryptography

Uses the same key for both encryption and decryption. Fast and efficient, but requires a secure way to share the key.

Plain

Hello

Secret Key
X&j9

Cipher

Examples

AES-256, ChaCha20, DES

Best For

Bulk data encryption, Disk encryption.

02.2 / Public Key

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.

Public Key

(Shared with Everyone)

Private Key

(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.

02.3 / Key Exchange

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
Public: Common Paint
Alice: Secret Red
Bob: Secret Blue

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.

Interactive DH Simulator (Toy Parameters)

Alice
// Keep this secret!
Public Result (A)
--
gᵃ mod p
// Public Parameters
Prime (p): 23
Base (g): 5

These values are shared openly. The security relies on the difficulty of finding 'a' from 'A'.

Bob
// Keep this secret too!
Public Result (B)
--
gᵇ mod p
The Derived Secret

Alice takes Bob's B and her own a. Bob takes Alice's A and his own b. They both calculate:

Alice: Bᵃ mod p = Shared Secret
Bob: Aᵇ mod p = Shared Secret
Established Secret
--
02.4 / State of the Art

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.

02.5 / Attacks

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
Waiting...
?
Eve
Bob
Waiting...

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).

02.6 / Key Management

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.

Alice
KDC
Bob
A

Request: Alice asks for a key to talk to Bob (IDA || IDB || N1).

B

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.

02.7 / Hybrid Systems

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.

AES
1. Generate Session Key

Alice creates a random 256-bit key.

2. Wrap in "Envelope"

She encrypts it with Bob's RSA/ECC Public Key.

Digital Envelope

Symmetric Key inside Asymmetric Box

03.1 / Fingerprints

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

In (text): "Alice"
Out: 2bd80...f8d
In (video): 4GB Binary
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.

03.2 / Authenticity

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)
Message: "Hi Bob"
↓ Hashing ↓
Hash: 7a2b...
↓ + Alice's Private Key ↓
Digital Signature
03.3 / Digital Identity

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 5280

CN=google.com

DigiCert Global CA G2

Not Before: 2024 Not After: 2025
04:A3:E1:92:B4:C9:E2:C7... (256-bit Elliptic Curve)
CA Signed

The Chain of Trust

Root CA

Pre-installed in OS

Intermediate CA

Delegated Trust

End Entity

google.com

04.1 / Protocols

TLS/SSL Handshake

The process that secures HTTP connections (HTTPS) through encryption and authentication.

Client-Server Communication
ClientHello
Server
Client
ServerHello
Key Exchange
Finished
04.2 / Perimeter Security

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)

TCP 80 (HTTP) Allow
TCP 23 (Telnet) Deny
UDP 53 (DNS) Allow

Firewalls inspect packets and apply Access Control Lists (ACLs) to block malicious traffic.

Virtual Private Network (VPN)

Client
Encrypted Tunnel
Office

VPNs use Encapsulation to hide your traffic and Encryption to protect its content.

05.1 / Future Tech

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.

ML-KEM (Kyber)
ML-DSA (Dilithium)
Glossary

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.

06 / Knowledge Check

Final Assessment