Writing
Cryptography: Trust in a World Without Trust
From plain bytes to a trusted message: encryption, tags, key exchange, signatures, and certificates, shown through one chat message.
This blog explains how cryptography works by following one small message: “hi”, sent from Alice to Bob in a chat application. On its way, the message passes through machines that neither of them owns, and every one of those machines can read it or change it. Everything in the blog grows out of this single problem.
The blog is a chain of problems, not a list of algorithms. Each step starts with a simple solution, shows how an attacker breaks it, and moves on to the idea that fixes the break. A fixed mapping gives the same output for the same message, so a nonce is added. A key used for two messages exposes both, so every message gets its own keystream. Encrypted data can be changed without anyone noticing, so an authentication tag is added. A key exchange can be intercepted, so signatures and certificates are added. The last question is whose key is whose.
Three goals are used to judge every step: confidentiality (only Alice and Bob can read the message), integrity (the message arrives exactly as it was sent), and authenticity (the other side is really who it claims to be).
Some examples use small numbers, so that every step can be checked by hand. Other examples show the actual output of standard algorithms (AES, X25519, Ed25519, HMAC). That output contains random values, so it looks different every time the code is run.
Contents
Part 1: Hiding the message
- A Message Through Untrusted Machines
- A Scrambling That Cannot Be Undone Is Useless
- The Same Message Must Not Look the Same Twice
- The Simplest Way to Mix: XOR
- What Happens When the Key Is Used Twice
- One Key, Many Messages
Part 2: Protecting the message
Part 3: Agreeing on a key and knowing who is there
- The Key Problem
- Building a Key in Public
- The Stranger in the Middle
- Proving Who Sent a Value
- Whose Key Is It?
Wrap-up
A Message Through Untrusted Machines
This blog uses an example that has two people, Alice and Bob, communicating with each other over a websocket connection.
Alice types “hi” and presses send. Her browser turns the text into bytes and sends them over a WebSocket. A WebSocket is just a long-lived connection between her browser and the server, and the data travels over the internet in small pieces called packets.
Those packets do not fly directly from Alice to the server. They pass through a chain of machines, each one receiving the bytes and passing them on:
Alice's browser → Wi-Fi router → her ISP → many internet routers → the server → ... → Bob's browser
Every machine in that chain handles the bytes, so every machine could copy them, read them, or change them. Alice does not own those machines, and she cannot choose who is on the path.
With a plain ws:// connection, nothing is hidden. This is the frame that carries “hi” toward Bob, as someone watching the network would see it:
81 02 68 69
The first byte (81) says “this is a text message”, and the second (02) says “two bytes follow”. The last two are our bytes:
68 = h
69 = i
No effort, no secret, and no password is needed to read it. Anyone on the path just looks at the bytes. This is the root problem that cryptography exists to solve: the data has to travel through places nobody trusts, and the sender cannot control who is there.
Let’s pretend cryptography does not exist yet. How would this transfer happen in a secure way?
The first step could be turning “hi” into an unreadable payload. For example, a mapping table and a function could turn “hi” into something like 4246, a completely random number.
That was one of the oldest ideas in cryptography. People used mapping tables to hide messages for thousands of years, and the idea is the same as the one above.
| The idea | Cryptography’s word |
|---|---|
| “hi” | plaintext, the readable message |
| 4246 | ciphertext, the scrambled result |
| Turning “hi” into 4246 | encryption |
| Bob using the table to get “hi” back | decryption |
| The mapping table and function | the cipher |
The problem with this approach is that the same input always gives the same output. If Alice sends “hi” three times, a stranger sees 4246, 4246, 4246. They cannot read it, but they can see that the same thing was said three times. And if they ever learn what one 4246 means, they know it forever. For centuries, letter-for-letter ciphers were broken exactly this way: by counting how often each symbol appears, since some letters are far more common than others. This method, called frequency analysis, was described as early as the ninth century.
A Scrambling That Cannot Be Undone Is Useless
A natural next idea is to apply several math operations to the number. For example, “hi” is turned into 42, and then 42 mod 5 is calculated, which gives 2. But 2 is also the result for 7, 12, 17, and many more numbers. When Bob receives a 2, there is no way to know which number was meant.
This small failure shows a basic rule: encryption must be reversible. Every ciphertext must come from exactly one plaintext. Otherwise, the message is lost for Bob as well, not only for the stranger. Operations that destroy information on purpose do exist, and they are very useful, but they have a different job. They are called hash functions, and they appear later in the story.
The Same Message Must Not Look the Same Twice
Back to the weakness of the mapping table: “hi” always becomes 4246. One way to fix this is to add an extra input to the process, for example a random string such as “asdjasdasmdask”, and to scramble the message based on it.
In fact, two different kinds of extra input are hidden in this idea:
| Key | Nonce | |
|---|---|---|
| Is it secret? | Yes | No, it is sent along in the open |
| How often is it new? | Rarely, one key serves many messages | For every single message |
| What is it for? | Only the key holder can unscramble | The same message looks different each time |
The key is the real secret. Without it, the message cannot be unscrambled. The nonce (short for “number used once”) is a fresh value created for every message. It is mixed with the key, so that “hi” sent three times gives three different results. A stranger who sees all three cannot even tell that the same message was repeated.
One rule comes with this: a nonce must never repeat under the same key. The reason is shown later in the story.
The Simplest Way to Mix: XOR
Which operation mixes two values together and can always be undone? The simplest one is XOR (written ⊕). It compares two bits and gives 1 when they are different:
0 ⊕ 0 = 0
0 ⊕ 1 = 1
1 ⊕ 0 = 1
1 ⊕ 1 = 0
It has one very useful property: using XOR with the same value twice cancels out, so (a ⊕ k) ⊕ k = a. The same operation therefore encrypts and decrypts.
Here is “hi” encrypted byte by byte, with the two-byte key 3A C1 as an example. The key is one value made of two bytes, so each letter is combined with its own key byte: 3A for the first letter and C1 for the second.
plaintext h 01101000 (0x68)
key byte 1 00111010 (0x3A)
ciphertext 01010010 (0x52)
plaintext i 01101001 (0x69)
key byte 2 11000001 (0xC1)
ciphertext 10101000 (0xA8)
The ciphertext is 52 A8. When Bob applies the same key again, the original comes back:
01010010 ⊕ 00111010 = 01101000 (0x68, h)
10101000 ⊕ 11000001 = 01101001 (0x69, i)
On the network, the frame toward Bob now looks like this:
81 02 52 A8
The two bytes no longer spell “hi”. Someone watching the network sees only numbers that mean nothing without the key.
What Happens When the Key Is Used Twice
After “hi”, Alice sends a second message, “ok”, with the same key 3A C1. Its ciphertext is 55 AA. A stranger on the path now holds two ciphertexts, and still has no key:
c1 = 52 A8
c2 = 55 AA
Each ciphertext is a plaintext mixed with the key, so c1 = p1 ⊕ k and c2 = p2 ⊕ k. When the two ciphertexts are combined, the key cancels out, because any value XOR-ed with itself gives zero:
c1 ⊕ c2 = (p1 ⊕ k) ⊕ (p2 ⊕ k) = p1 ⊕ p2
The key is never needed for this step. Byte by byte, the stranger computes:
52 ⊕ 55 = 07
A8 ⊕ AA = 02
The result, 07 02, is not readable, but it is the two plaintexts blended together. Now the stranger only needs to guess. Chat traffic is full of predictable starts: greetings, protocol headers, and fixed text. If the first message is guessed to be “hi” (68 69), the key itself falls out:
k = p1 ⊕ c1
k = 68 69 ⊕ 52 A8 = 3A C1
The whole key is recovered, and from that moment every message under this key can be read, the old ones and the future ones:
55 ⊕ 3A = 6F = o
AA ⊕ C1 = 6B = k
The same result is reached by a second road: the blend 07 02 XOR-ed with the guess 68 69 gives 6F 6B, which is “ok”.
So reusing a key is not a small leak. One correct guess can give away everything. A second weakness was already visible before any computation: the stranger could see that both messages are two bytes long. Encryption like this hides the content, but not the length.
One Key, Many Messages
A key must not be reused, but a chat has thousands of messages. A fresh key for every message is impossible, because every key would have to be delivered to Bob first. The nonce solves this problem.
Instead of being used directly, the key and the nonce are fed into a function that produces a long, random-looking stream of bytes, called a keystream. The keystream is mixed with the message by XOR, exactly as before. A block cipher is the right tool for this job. AES, the standard block cipher of the world, takes a key and a 16-byte block, and gives back 16 bytes that look completely random. In counter mode (CTR), the block “nonce + counter” is encrypted under the key, and the result is used as the keystream.
Here are “hi” and “ok” again, encrypted with real AES-CTR (with a demo key, and the nonces 1, 2, and 3):
message 1 "hi" nonce 1 -> 2A 05
message 2 "hi" nonce 2 -> 88 7A
message 3 "ok" nonce 3 -> DD 3B
Two things happened here. First, the same message “hi” gives two different ciphertexts, so a stranger cannot even see that a message was repeated. The weakness of the mapping table is gone.
Second, the attack from the previous section stops working. If the stranger guesses that message 1 was “hi”, the keystream of message 1 is revealed:
2A 05 ⊕ 68 69 = 42 6C
But this keystream belongs to nonce 1 only. Applied to message 3, it gives:
DD 3B ⊕ 42 6C = 9F 57
This is meaningless, and not “ok”. The keystream of one message says nothing about the keystream of another, and AES is designed so that the key cannot be found from such pairs. Bob has the key and receives nonce 3 together with the message, so he simply creates the same keystream and decrypts “ok”.
Two rules go with this design. The nonce is not secret: it is sent next to the ciphertext. But it must never repeat under the same key, because then two messages share one keystream, and the attack from the previous section works again. A simple counter or a long random value both do the job.
Hidden Is Not the Same as Safe
Encryption hides a message, but it does not stop the message from being changed. A stranger on the path can still modify bytes in transit, and the XOR design has a special weakness here. Decryption is plaintext = ciphertext ⊕ keystream, so changing one bit of the ciphertext changes exactly the same bit of the plaintext.
For example, the stranger changes the last byte of the first message from 2A 05 to 2A 04. The change itself is 05 ⊕ 04 = 01, and the same change is applied to the plaintext when Bob decrypts:
69 ⊕ 01 = 68 (i becomes h)
Bob reads “hh”. No error appears, and nothing looks wrong.
With a correct guess about the original message, the stranger can do much more. To turn “hi” into “no”, the difference between the two plaintexts is computed, and it is applied to the ciphertext:
68 69 ⊕ 6E 6F = 06 06
2A 05 ⊕ 06 06 = 2C 03
Bob decrypts 2C 03 with the real keystream 42 6C and reads:
2C ⊕ 42 = 6E = n
03 ⊕ 6C = 6F = o
The key was never needed. In a real chat, messages have a predictable structure, and the stranger knows where the important bytes are. For example, the digit “1” is 0x31 and the digit “9” is 0x39, so flipping a single bit turns an amount of 100 into 900.
This is the difference between two of the three goals. Confidentiality holds, because the stranger still cannot read anything. But integrity is broken, because the message was changed and nobody noticed.
Noticing a Change
Bob needs a way to check that a message was not modified. A natural idea is a fingerprint: a short value that is computed from the message and sent along with it. A hash function does exactly this. Any input, large or small, is turned into an output of fixed size. A tiny change in the input gives a completely different output, and the process cannot be run backwards. For example, the first 8 bytes of two fingerprints are:
sha256("hi") = 8f434346648f6b96...
sha256("no") = 9390298f3fb0c5b1...
But a fingerprint alone proves nothing. A stranger who changes “hi” to “no” simply computes the new fingerprint, and Bob’s check passes. Everything that is computed without a secret can be recomputed by the stranger.
The solution is to mix the shared secret into the fingerprint. The result is called a message authentication code (MAC), and its standard form is HMAC. Alice computes a tag from the key and the message, and sends it along. Bob computes the tag again and compares. Only a holder of the key can produce a valid tag:
HMAC(key, "hi") = a1777c58721788b7...
"no" with the old tag -> rejected
"no" with a plain SHA-256 fingerprint -> rejected
Two rules go with this. The tag should cover the nonce and the ciphertext, and Bob should check it before decrypting anything. Also, a MAC has a limit: it cannot stop replay. A stranger can record a valid message and send it again later, and the tag will still be correct.
In practice, encryption and the tag are combined into one step, called authenticated encryption. The most common choice is AES-GCM. With the same demo key, “hi” becomes 18 bytes: 2 bytes of ciphertext and a 16-byte tag.
"hi" -> d2bc 7295d8c47678ec3bdbb6a5b96e38bdf7
(2 bytes ciphertext + 16 bytes tag)
one bit flipped -> rejected, nothing is decrypted
The nonce rule applies here too, and it is even stricter: in GCM, a repeated nonce leaks the same blend as before and also breaks the authentication.
The Key Problem
Bob needs the key to decrypt and to check the tags. How does it reach him without the strangers on the path seeing it?
The server could generate the key and push it through the open channel, but then everyone who watches the channel can copy it, and the server itself can read every message. The key must be built by Alice and Bob themselves, and the stranger sees every message they exchange. For this reason, only public values can be sent, and still the same secret must be reached on both sides.
Building a Key in Public
This is possible with an operation that has two properties: the order of the steps does not matter, and the operation cannot be run backwards. Paint shows the idea. Yellow is public. Alice mixes in a private red, and Bob mixes in a private blue. The two mixtures are swapped, and each person adds their own private color to the mixture received. Both end up with yellow + red + blue, but the stranger, who saw only the two mixtures, cannot un-mix them.
In numbers, the mixing is exponentiation with a remainder: g^a mod p. A remainder cannot be undone, which is the same property that made mod useless for encryption and makes it perfect here. With the public values p = 23 and g = 5:
Alice's private number a = 3 A = 5^3 mod 23 = 10 (sent to Bob)
Bob's private number b = 4 B = 5^4 mod 23 = 4 (sent to Alice)
Alice computes B^a mod 23 = 4^3 mod 23 = 18
Bob computes A^b mod 23 = 10^4 mod 23 = 18
The same value is reached on both sides, because (g^a)^b = (g^b)^a. The stranger sees 23, 5, 10, and 4, but never 18, because the private numbers do not travel.
With numbers this small, the stranger can still find a private number by trying exponents one by one: 5^1 = 5, 5^2 = 2, 5^3 = 10. The third try finds a = 3, and then 4^3 mod 23 = 18 gives the key. Only 22 private numbers are possible, so the exchange falls at once. Finding a private number from the public values is called the discrete logarithm problem, and it is the same brute-force problem as before: security comes from making the search astronomically large.
Real exchanges use numbers hundreds of digits long, or the elliptic curve version called X25519, where private and public values are only 32 bytes. For X25519, the best known attacks need about 2^126 steps. Here is a real exchange, followed by key derivation and the encryption of “hi” (the values change on every run):
Alice public value: 62964184e42e5123... (32 bytes)
Bob public value: b324d0ff8aa45efd... (32 bytes)
shared secrets equal: True (32 bytes)
derived keys equal: True (32 bytes)
Alice sends: da3a63ee2974... (18 bytes: "hi" + tag)
Bob reads: "hi"
The shared secret is not used as the key directly. It goes through a key derivation function (HKDF), which turns it into a clean, uniform key and can also produce separate keys for separate purposes.
The Stranger in the Middle
So far, the stranger only watched. If the stranger also acts, a different picture appears. Suppose the stranger chooses a private number k = 6 and computes M = 5^6 mod 23 = 8. When Alice sends A = 10 toward Bob, it is intercepted, and Bob receives M = 8 instead. The same is done with B = 4, and Alice also receives M = 8:
Alice computes M^a mod 23 = 8^3 mod 23 = 6 (a key shared with the stranger)
Bob computes M^b mod 23 = 8^4 mod 23 = 2 (a key shared with the stranger)
The stranger computes:
A^k mod 23 = 10^6 mod 23 = 6 (the same key as Alice)
B^k mod 23 = 4^6 mod 23 = 2 (the same key as Bob)
Nothing breaks, and no error appears. Alice and Bob do not share a key with each other. Each of them shares a key with the stranger, who now holds both. Every message can be decrypted with one key, read or changed, and encrypted again with the other, and the tags are valid on both sides. The stranger never needed a private number of Alice or Bob, only their own k. This is called a man-in-the-middle attack.
The math was never broken. What is missing is an answer to a simple question: does A really belong to Alice, and B to Bob? Nothing in the exchange can say. This is the third goal, authenticity: knowing who is on the other side.
Proving Who Sent a Value
The stranger’s trick works because nothing proves where a public value comes from. A MAC could prove it, but a MAC needs a shared secret, and Alice and Bob share nothing yet. What is needed is a proof that anyone can check, but only one person can create. This is a digital signature.
Bob owns a pair of keys: a private signing key, which never leaves his device, and a public verification key, which everyone may know. Bob signs his exchange value with the signing key, and Alice checks the signature with the verification key. A real example with Ed25519:
Bob's verification key: 891fc9571ae514bf... (32 bytes)
signature on B: 1016be4d82e5b8ca... (64 bytes)
Alice checks B with Bob's signature -> valid
Alice checks the stranger's M with that signature -> rejected
Alice checks M signed by the stranger's own key -> rejected
The last line deserves attention. The stranger can sign too, with their own key, and the signature is valid, but only for the stranger’s key and not for Bob’s. So the question moves one step further. It is no longer “who signed this value?” but “does this verification key really belong to Bob?”
Whose Key Is It?
The stranger can also hand Alice a fake verification key. How can Alice know that a verification key really belongs to Bob?
One answer is a trusted third party. Alice does not have to know Bob’s key. Instead, someone she already trusts signs a statement that links Bob’s name to Bob’s key. Such a statement is called a certificate, and the signer is a certificate authority (CA). Alice needs to know only one key beforehand, the key of the CA, and with it she can check every certificate the CA has signed. A toy example follows (real certificates use a more complex format, but the idea is the same):
certificate = "bob:" + Bob's verification key, signed by the CA
Alice checks Bob's certificate with the CA key -> valid
Alice checks Bob's signature on B with the key inside it -> valid
Alice checks the stranger's fake certificate with the CA key -> rejected
The stranger can create a certificate for their own key, but it can only be signed with the stranger’s own signing key, and Alice’s check against the CA key fails.
The chain of trust has to start somewhere. The key of the CA cannot arrive through the channel under attack, so it is delivered together with the software: browsers and operating systems ship with a list of CA keys that they trust. This system is called PKI. It is how the padlock in a browser works. A website presents a certificate, the browser checks it against its list, and only then is the key exchange trusted.
Trust is moved here, not removed. If a CA is hacked or dishonest, false certificates appear. In 2011, a CA called DigiNotar was hacked, and fraudulent certificates were issued for well-known websites.
Closing
The message “hi” started as plain bytes on an open path, where anyone could read it and anyone could change it. Every step since then answered one failure of the step before. A cipher hid the content, a nonce stopped equal messages from looking equal, and a key that is never reused stopped one mistake from exposing everything. A tag, either a MAC or AES-GCM, made changes visible. A key exchange built the shared key in public, and signatures and certificates tied that key to the right person.
Measured against the three goals, the result is this: confidentiality comes from encryption, integrity from the tag, and authenticity from signatures and certificates. None of the three works alone. Encryption without a tag can be modified, a tag without a trustworthy key proves nothing, and a key exchange without authentication is open to the stranger in the middle.
One point remains from the end of the story. Cryptography does not remove trust. It reduces the trust to something small and specific: a private key that stays private, and the key of a certificate authority that is known beforehand. With these two in place, Alice can send “hi”, and Bob receives it exactly as it was sent, readable only to him.