Skip to content

Cryptography Fundamentals

Cryptography is the engine behind every “lock” on the internet - HTTPS, SSH, VPNs, signed software. This note builds the mental model from first principles, then gets practical.


TermDefinition
CryptographyThe practice of coding messages to hide them from third parties
EncryptionApplying a cipher to plaintext → ciphertext
DecryptionReversing ciphertext → plaintext using a key
CipherAlgorithm + key; algorithm is the process, key is the unique secret
PlaintextUnencrypted readable data
CiphertextEncrypted unreadable data
CryptanalysisThe study of breaking cryptosystems
SteganographyHiding data inside innocuous-looking data (images, audio) - concealment, not encryption
Kerckhoff’s PrincipleA system should be secure even if everything except the key is public knowledge

One key encrypts and decrypts. Both parties must share the key through a secure channel first.

Plaintext ──[KEY]──→ Ciphertext ──[same KEY]──→ Plaintext
Ciphers
├── Stream ciphers
│ ├── Encrypt one bit/byte at a time
│ ├── Fast - ideal for real-time use (VoIP, VPNs)
│ └── Vulnerable if key stream is reused → use IV (Initialization Vector)
└── Block ciphers
├── Encrypt data in fixed-size blocks (e.g., 128 bits)
├── Same key applied based on the cipher mode
└── More common for data-at-rest and structured data

The mode controls how blocks are chained together - critical to security:

ModeHow it worksRisk
ECB (Electronic Code Book)Each block encrypted independently with the same keyIdentical plaintext blocks → identical ciphertext blocks (pattern leak)
CBC (Cipher Block Chaining)XOR each block with previous ciphertext before encryptingParallelism impossible; IV needed for first block
CTR (Counter)Encrypts a counter value, XORs with plaintext (turns block into stream)Must never reuse counter+key pair
GCM (Galois/Counter Mode)CTR + authentication tag (AEAD)Nonce reuse is catastrophic
AlgorithmKey SizeBlock SizeStatus
DES56-bit (effective)64-bitBroken - brute-forceable since 1998
3DES112/168-bit64-bitDeprecated; slow
AES-128128-bit128-bitSecure; standard
AES-256256-bit128-bitSecure; preferred for sensitive data
ChaCha20256-bitStreamFast on devices without AES hardware
RC440–2048-bitStreamBroken; never use

Asymmetric Encryption (Public-Key Cryptography)

Section titled “Asymmetric Encryption (Public-Key Cryptography)”

Two mathematically linked keys: a public key (share freely) and a private key (never share).

ENCRYPTION DECRYPTION
Plaintext ──[Bob's PUBLIC key]──→ Ciphertext ──[Bob's PRIVATE key]──→ Plaintext
SIGNING VERIFICATION
Message ──[Alice's PRIVATE key]──→ Signature ──[Alice's PUBLIC key]──→ Valid/Invalid
PropertyMechanism
ConfidentialityEncrypt with recipient’s public key; only their private key decrypts
AuthenticitySign with sender’s private key; anyone with public key can verify
Non-repudiationOnly private key holder can produce that signature → can’t deny it
IntegritySignature changes if message is tampered with

RSA (Rivest-Shamir-Adleman)

  • Security relies on the difficulty of factoring the product of two large primes
  • Used for: key exchange, encryption, digital signatures
  • Recommended minimum key size: 2048-bit (4096-bit for long-lived keys)
  • Vulnerabilities: side-channel attacks, weak prime generation, small key sizes

DSA (Digital Signature Algorithm)

  • Designed for signing only (not encryption)
  • Security depends on a random seed value - if the seed is predictable, the private key is recoverable
  • Example: Sony PlayStation 3 (2010) - same nonce used twice → private key extracted

Diffie-Hellman (DH) Key Exchange

  • Allows two parties to establish a shared secret over a public channel without ever transmitting the secret
  • Not for encrypting data - for agreeing on a symmetric key
DH mental model ("colour mixing" analogy):
1. Alice and Bob agree on a public colour: YELLOW
2. Alice picks secret: RED → mixes → ORANGE → sends to Bob
Bob picks secret: BLUE → mixes → GREEN → sends to Alice
3. Alice: GREEN + RED = BROWN (shared secret)
Bob: ORANGE + BLUE = BROWN (same shared secret)
Eavesdropper sees: YELLOW, ORANGE, GREEN - can't reverse to get secrets

Elliptic Curve Cryptography (ECC)

  • Uses algebraic structure of elliptic curves over finite fields
  • Same security as RSA with much smaller keys: ECC-256 ≈ RSA-3072 in strength
  • Variants: ECDH (key exchange), ECDSA (signing)
  • Used in: TLS 1.3, SSH, Bitcoin, modern code signing
AlgorithmKey Size for ~128-bit security
RSA3072-bit
DH3072-bit
ECC256-bit
AES128-bit

The hybrid model (how TLS actually works):

1. Asymmetric crypto (ECDH) → agree on a shared session key
2. Symmetric crypto (AES-GCM) → encrypt all data with that session key

Asymmetric is used only for key exchange (slow but safe); symmetric handles the data (fast).


A hash function maps arbitrary-length input to a fixed-size output (digest). It is one-way - you cannot reverse a hash to get the original input.

"password123" ──[SHA-256]──→ ef92b778bafe771... (64 hex chars = 256 bits)
"password124" ──[SHA-256]──→ 0b14d501a5944a7... (completely different)

Required Properties of a Cryptographic Hash

Section titled “Required Properties of a Cryptographic Hash”
PropertyMeaning
DeterministicSame input always produces same output
Fast to computeEfficient forward direction
Pre-image resistantCan’t reverse hash → original input
Second pre-image resistantCan’t find different input with same hash
Collision resistantComputationally infeasible to find two inputs that hash to same value
Avalanche effectTiny input change → wildly different output
AlgorithmDigest SizeStatus
MD5128-bitBroken - collisions trivially generated
SHA-1160-bitBroken - collision demonstrated in 2017 (SHAttered)
SHA-256256-bitSecure - current standard
SHA-3 (Keccak)256/512-bitSecure - different design from SHA-2, diversifies risk
BLAKE3256-bitSecure + very fast - emerging choice
Terminal window
# Compute SHA-256 of a file
sha256sum /path/to/file.iso
# Compute MD5 (only for checksums, NOT for security)
md5sum /path/to/file
# Verify downloaded file integrity
echo "expected_hash filename" | sha256sum --check

Password storage - never store plaintext passwords:

User sets password: "hunter2"
System stores: sha256("hunter2" + salt) = 3d70e47...
At login: hash entered password + same salt → compare

File integrity - verify a download hasn’t been tampered with:

Terminal window
# Download file + check against published SHA-256
curl -O https://example.com/ubuntu.iso
echo "published_hash ubuntu.iso" | sha256sum -c

Git object storage - every commit, tree, and blob is identified by its SHA-1 (→ SHA-256 in progress) hash.


Without salts, two users with the same password get the same hash → one lookup table (rainbow table) cracks everyone.

Without salt:
user1: sha256("password") = 5e884898...
user2: sha256("password") = 5e884898... ← identical! one table cracks both
With salt (random per user):
user1: sha256("password" + "a7f3x2") = 9b2c4e1... ← unique
user2: sha256("password" + "k9m1p8") = 4d7a3c2... ← unique

Use a deliberately slow KDF (Key Derivation Function), not a raw hash:

KDFWhy it’s used
bcryptBuilt-in salt, tunable cost factor
scryptMemory-hard (resists GPU/ASIC attacks)
Argon2id2015 Password Hashing Competition winner; recommended default
PBKDF2Widely supported; weaker than Argon2 but FIPS-approved
Terminal window
# Generate an Argon2id hash (Linux, requires argon2 package)
echo -n "mypassword" | argon2 "random_salt" -id -t 3 -m 16 -p 4

A MAC uses a shared secret key to produce a tag that proves:

  1. The message came from someone with the key (authenticity)
  2. The message was not modified (integrity)
Sender: MAC = HMAC(key, message) → sends (message + MAC)
Receiver: recompute MAC using same key + received message
if computed MAC == received MAC → authentic and intact
TypeAlgorithmMechanism
HMACHMAC-SHA256, HMAC-SHA3-256Hash function + secret key (most common)
CMACAES-CMACBlock cipher (AES) in CBC mode as MAC
GMACPart of AES-GCMGCM authentication tag (integrated with encryption)
PropertyHashMACDigital Signature
Requires keyNoYes (shared)Yes (private key)
Provides integrityYesYesYes
Provides authenticityNoYes (to key holders)Yes (to anyone)
Non-repudiationNoNoYes
ExampleSHA-256HMAC-SHA256RSA-SHA256, ECDSA