DEV Community

Cover image for Introduction to Cryptography: Basic Blocks
Dmytro Huz
Dmytro Huz

Posted on

Introduction to Cryptography: Basic Blocks

“We use spells we don't understand, then act surprised when things break.”


🌍 The Magic We Never Question

The next stop in my journey to rebuild the internet from first principles is something powerful, essential, and strangely invisible: security protocols.

TLS (Transport Layer Security) encrypts communication between web browsers and servers, keeping online interactions secure. SSH (Secure Shell) provides secure remote access to servers. VPNs (Virtual Private Networks) create encrypted tunnels over the internet, protecting data from prying eyes.

We use them every day - to log into servers, secure our APIs, encrypt sensitive data. They are the invisible guards that make the modern web possible. Without them, the internet would be like shouting your passwords into a crowded train station.

And behind all of them is one thing: cryptography.

For years, I thought I understood it. I installed certificates. I enforced HTTPS. I even helped debug production TLS issues. I knew the right commands. I thought I knew the concepts.

But I was wrong.


🧠 The “Why?” That Exposes Everything

It hit me while I was building my own web server from scratch. I was deep into HTTP, connection handling, sockets - the guts of the web. And then I reached the point where I wanted to add HTTPS support.

I paused. “Okay,” I thought, “so this is where SSL goes. But... how does it actually work?”

Not the commands. Not the installation steps.

The logic. The math. The trust.

And I realized - I had no idea.

I could say “TLS handshake” or “public key” or “certificate authority,” but if someone asked me why any of this worked, I’d stumble. Just like when a child asks, “Why is the grass green?” and you answer “photosynthesis,” only to collapse at the second “why.”

That’s when I understood: I wasn’t using cryptography. I was just reciting spells.

And so, I made a decision: no more black boxes. I would rebuild my knowledge from the ground up - understand every mechanism - and share that journey openly.


📜 This Series: From Zero to TLS, Step by Step

After searching for the right starting point, I found it: Stanford’s Cryptography I course by Dan Boneh. It’s a rigorous but accessible deep dive into the foundations of modern cryptography - no fluff, no hand‑waving.

This series will follow the course - not just repeating it, but rewriting the insights in my own words, through the lens of a developer rediscovering the fundamentals.

We begin with Week 1: the basics of symmetric encryption, randomness, and probability - the raw materials from which real‑world protocols are built.


Week 1 - What Even Is Cryptography?

🎖️ The General and the Message

Imagine you're a Roman general. Tomorrow’s battle is critical. You can’t risk riding out, but you must send secret orders to another commander.

You use a messenger. But what if he’s intercepted?

The only solution: make your message meaningless to outsiders - and readable only by the intended recipient.

That is the ancient problem cryptography solves:

Make a message readable only by its intended recipient - even if it’s seen by the entire world.


🔐 The Core Model of Symmetric Encryption

Cryptography often starts with symmetric encryption, where the same secret key is used for both encryption and decryption.

Notation:

  • m = message (plaintext)
  • k = key (secret shared between sender and receiver)
  • E(k, m) = c = encryption function (Encryption must be reversible because the intended recipient needs to convert the ciphertext back into the original message. Without reversibility, the encrypted data would be permanently unreadable.)
  • c = ciphertext (unreadable version of the message)
  • D(k, c) = m = decryption function

The encryption and decryption must satisfy:

D(k, E(k, m)) = m

Both sides must share the same key - hence, symmetric.


🌺 Historical Ciphers (and How They Failed)

Examples:

  • Caesar Cipher: shift each letter by ‘n’
  • Substitution Cipher: swap every letter with another
  • Vigenère Cipher: use a keyword to shift letters cyclically

How They Were Broken:

  • Frequency analysis: Exploits letter frequency in language.
  • Known‑plaintext attacks: Using known message portions to reverse‑engineer keys.

These early ciphers lacked true randomness, making them vulnerable.


🧮 Probability: The Foundation of Secrecy

🎲 Probability Distributions

If we have a set U (e.g., 2‑bit strings {00, 01, 10, 11}), a probability distribution P assigns likelihood to each item.

Examples:

  • Uniform distribution: Each outcome equally likely (P(x) = 1/4).
  • Point distribution: One outcome certain (P(10) = 1, others 0).

📦 Events

In cryptography, we’re often interested in how likely it is for certain outcomes - like a key being guessed - to happen. These are called events.

An event is a collection of possible outcomes. Rolling a die, outcomes are {1,2,3,4,5,6}.

  • Event A (even numbers): {2,4,6}, Pr[A] = 0.5.

⚠️ Union Bound

Estimates the probability that at least one of several rare events happens (A, B, or both):

Pr[A ∪ B] ≤ Pr[A] + Pr[B]

The union (∪) means “A or B (or both).” The sum on the right may double‑count the overlap, so it is always an upper bound - handy when you just need a worst‑case figure.

Example

  • Event A: an attacker correctly guesses a 128‑bit AES key on the first try ⇒ Pr[A] = 2^{-128}.
  • Event B: the same attacker forges a 128‑bit MAC tag by blind luck ⇒ Pr[B] = 2^{-128}.

The chance the attacker succeeds in either attack is at most:

Pr[A ∪ B] ≤ 2^{-128} + 2^{-128} = 2^{-127}

Still astronomically small - but twice the single‑attack probability. The union bound lets us combine multiple risks into one clear, conservative number.


🔣 Variables vs. Random Variables

A variable holds a known, fixed value (e.g., x = 5).

A random variable captures outcomes from random processes:

  • Coin flips (X: number of heads).
  • Die rolls (Y: even = 1, odd = 0).

They measure randomness mathematically.


🔄 Uniform Random Variables and Randomized Algorithms

A uniform random variable: every outcome equally probable (e.g., random 8‑bit key).

  • Deterministic algorithm (y ← A(m)): same input yields same output.
  • Randomized algorithm (y ← A(m; r)): randomness r gives unpredictable outcomes.

In cryptography, randomized algorithms prevent predictability and pattern recognition.


🔐 Random Variables in Cryptography

Randomness in cryptography prevents attackers from easily predicting encrypted outcomes. Without randomness, encryption outputs would be predictable, allowing attackers to exploit patterns and ultimately compromise the security of the encryption.

Examples:

  • Key Generation (K): 128‑bit keys have equal probabilities (1 in 2^128).
  • Ciphertext (C) Distribution: If encryption varies outputs for same inputs, it prevents leaks.
  • Attacker Guess (X): Probability attacker correctly guesses plaintext (e.g., how often a hacker’s random guess matches your password).

Random variables quantify cryptographic security.


🧩 Independence

Events A and B are independent if knowing that one occurs tells you nothing about the chance of the other. Formally, the probability of both happening together (the intersection A ∧ B) equals the product of their individual probabilities:

Pr[A ∧ B] = Pr[A] × Pr[B]

Example
Fair coins – Flip two independent fair coins.

  • Event A: first coin is heads ⇒ Pr[A] = ½.
  • Event B: second coin is heads ⇒ Pr[B] = ½.

Because the flips are independent, the chance of both being heads is:

Pr[A ∧ B] = ½ × ½ = ¼ - exactly the real‑world probability of “HH.”

Why it matters in crypto
If a ciphertext leaks information about its plaintext, the events “ciphertext = C” and “plaintext = P” become dependent. A secure cipher keeps them independent so that:

Pr[plaintext = P | ciphertext = C] = Pr[plaintext = P],

meaning the ciphertext reveals nothing beyond what an attacker already knew.


✨ The Magic of XOR in Cryptography

XOR (exclusive OR) is a basic bitwise operation that’s at the heart of modern symmetric encryption. It’s simple, powerful, and - most importantly - reversible.

How XOR Works

XOR takes two bits as input and outputs 1 if they are different, 0 if they are the same.

Bit 1 Bit 2 Bit 1 ⊕ Bit 2
0 0 0
0 1 1
1 0 1
1 1 0
Why XOR Is Perfect for Encryption
  • Reversibility: If you XOR a bit with a key, you can recover the original by XOR’ing again with the same key.

    • Example: If your plaintext bit is P and your key bit is K:
    • Encryption: C = P ⊕ K 1101 ⊕ 0110 = 1011
    • Decryption: P = C ⊕ K 1011 ⊕ 0110 = 1101
  • This works for entire strings, not just single bits - just apply XOR to each bit in the string.

XOR: The Ideal Encryption Building Block

  • No Information Lost: XOR is a one-to-one transformation if the key is kept secret.
  • No Bias Introduced: If the key is random, the result looks random, regardless of the original message.
  • Simplicity: XOR is easy to compute, both in hardware and software, and forms the basis for more complex encryption schemes.

🚫 Why Not Use Other Bitwise Operations for Encryption?

The core reason we use XOR and not OR/AND is reversibility: you must be able to get the original message back using the key and the ciphertext.

Let’s prove it step by step:

1. XOR Is Reversible

If you encrypt with XOR, you can always decrypt:

  • Encrypt: C = P ⊕ K
  • Decrypt: P = C ⊕ K

Proof:

Let’s expand the decryption:

C ⊕ K = (P ⊕ K) ⊕ K

But XOR is associative and commutative, and K ⊕ K = 0:

  • (P ⊕ K) ⊕ K = P ⊕ (K ⊕ K) = P ⊕ 0 = P
  • You always recover the original P.

2. OR and AND Are Not Reversible

Example with OR

Suppose you use OR for encryption:

  • Encrypt: C = P OR K

Let’s try to recover P from C and K.

Case:

Let’s say K = 1.

  • For any P (0 or 1): P OR 1 = 1

So C = 1, but you can’t tell if P was 0 or 1.

Another way:

P K P OR K Can you recover P from C and K?
0 0 0 Yes (P=0)
0 1 1 No (could be P=0 or 1)
1 0 1 Yes (P=1)
1 1 1 No (could be P=0 or 1)

Example with AND

Suppose you use AND for encryption:

  • Encrypt: C = P AND K

Case:

Let’s say K = 0.

  • For any P: P AND 0 = 0

So C = 0, but you can’t tell if P was 0 or 1.

P K P AND K Can you recover P from C and K?
0 0 0 No (could be P=0 or 1)
0 1 0 Yes (P=0)
1 0 0 No (could be P=0 or 1)
1 1 1 Yes (P=1)

Conclusion:

OR and AND “lose information” - many different P and K can give you the same C, so you cannot get the original message back.

XOR is the only common bitwise operation that is always reversible with knowledge of the key.


💪 Summary: Building Blocks Learned

  • Symmetric encryption starts with a shared secret key.
  • Probability and events help us measure risk and security.
  • Random variables and independence turn randomness into something we can analyze.
  • XOR is the backbone of secure, reversible encryption at the bit level.
  • Why not OR/AND? They’re not reversible - encryption must always be reversible!

We’re building from the fundamentals upward, laying the groundwork for real cryptographic security.

Cryptography isn’t magic-it’s math, logic, and trust.

Let’s keep uncovering its secrets, one layer at a time.


P.S.
This post is an experiment in format: I packed a lot of material and rewrote it from a developer‑first perspective. ChatGPT helped with proofreading and structure, but the voice and mistakes are mine. I’d love your feedback on clarity, depth, and length -everything will feed into the next articles in the series.

Thanks for reading, and stay tuned-more posts are coming soon!

Top comments (1)

Collapse
 
nevodavid profile image
Nevo David

Man, I’ve lost count of how many times I thought I got this but had no clue what was happening under the hood - reading this hits home in the best way.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.