<!--email_off-->---
title: "XOR in Cryptography: The Reagent That Cancels Itself Out"
source: https://iaastha.com/insights/concepts/xor-in-cryptography/
type: Concept
date_published: 2026-11-21
date_modified: 2026-11-21
author: Animesh Pratap
description: "XOR is a reagent that cancels itself out: pour it once and your data becomes unreadable, pour it again and it is gone. That one property makes encryption possible, causes two classic mistakes (key reuse and tampering), and fixes a third (timing)."
publisher: iAastha Research &amp; Consulting
---

# XOR in Cryptography: The Reagent That Cancels Itself Out

Picture a chemistry lab. On the top shelf sits a small red bottle labelled **K**.

Pour it into any clear solution and the solution turns murky. Nobody can tell what was in there. Pour the *same* bottle in a second time and something odd happens: the murk vanishes, and the original solution is back, exactly as it was. Not roughly. Exactly.

No real chemical behaves like this, which is a shame, because it would make a fantastic party trick. But there is an operation in your computer that does, and it sits inside nearly every cipher that protects your data today. It is called XOR.

**TL;DR: XOR is a reagent that cancels itself out. Pour it once and your data becomes unreadable; pour it again and it is gone. That one property makes encryption possible. It also causes two classic mistakes, and fixes a third.**

## The reagent that cancels itself

XOR works on bits, the 0s and 1s, two at a time. It asks one question: *are you two different?* If yes, the answer is 1. If no, 0.

That sounds dull until you notice what it means. Pour a bit of reagent into a bit of solution and it flips, or doesn’t. Pour the same bit of reagent in again, and it flips back. Every time. Two identical pours always cancel.

FIG·01 — FIRST POUR FLIPS THE BITS, SECOND POUR FLIPS THEM BACK

In code, the whole lab fits in one small function. I have called it `pour`, because that is exactly what it does:

```
import secrets

def pour(solution: bytes, reagent: bytes) -> bytes:
"""XOR, drop by drop. Pour the same reagent twice and it vanishes."""
if len(solution) != len(reagent):
raise ValueError("the reagent must match the solution, drop for drop")
return bytes(s ^ r for s, r in zip(solution, reagent))

solution = b"PAY 100 TO ALICE"
reagent = secrets.token_bytes(len(solution)) # random, as long as the message, used once

cloudy = pour(solution, reagent) # first pour: unreadable
clear = pour(cloudy, reagent) # second pour: the reagent is gone
assert clear == solution
print(cloudy.hex())
print(clear)
```

Run it and the first print is gibberish, a fresh batch of it every time. The second is your message, home safe. Encryption and decryption are the same move: pour, then pour again.

## The bottle every cipher keeps on the bench

Here is the part that made cryptographers fall in love. If the reagent is truly random, as long as the message, and used only once, the murky solution tells you *nothing*. Not “very little”. Nothing. This is called the **one-time pad**, and it is mathematically proven to be unbreakable.

The catch is the size of the bottle. To encrypt a 4 GB backup you first need a fresh 4 GB of reagent, delivered secretly to the other side, then poured down the drain forever. Most labs cannot run on that budget.

So modern ciphers like AES-GCM and ChaCha20 cheat, politely. They start from a small key and mix up a long stream of random-looking reagent from it, called a keystream. Then they pour. Underneath the impressive names, “encrypted with AES-GCM” means: XORed with something extremely hard to guess.

FIG·02 — ONE SMALL KEY, MIXED INTO A LONG KEYSTREAM

Which means every way of misusing XOR comes along for the ride too. Here are three mistakes that happen in real apps: two that XOR causes, and one that XOR cures.

To keep it concrete, we will follow one app through all three. You are building a payments app. A shop’s phone sends instructions like `PAY 100 TO ALICE` to the bank’s server, encrypted. The phone sits on café Wi-Fi, and so does Mallory. Mallory can see every message, record it, and change it before it reaches the bank. She cannot break the cipher. She will not need to.

## Mistake 1: one bottle, two beakers

**The mistake:** your app encrypts two messages with the same key *and* the same nonce. A nonce is a number the cipher mixes in so every message gets fresh reagent; it must be used once. A common way to get this wrong is a nonce counter that starts at 0 again every time the app restarts.

In the lab, that is pouring the same bottle K into two beakers. Monday’s message is `PAY 100 TO ALICE`. Tuesday’s is `PAY 900 TO MALLO`. Both go out murky, and Mallory records both.

She cannot read either one. So she XORs the two murky messages together, and the reagent meets itself and cancels. Here it is with 4 bits instead of 16 bytes:

- Reagent K = `1010`, Monday A = `0110`, Tuesday B = `1001`

- What Mallory records: A ⊕ K = `1100` and B ⊕ K = `0011`

- She XORs them: `1100` ⊕ `0011` = `1111`, which is exactly A ⊕ B (`0110` ⊕ `1001`). K is gone.

Now she only needs one message. Every payment from your app looks like `PAY`, an amount, `TO`, a name, so guessing is easy. Say she guesses Monday’s right: `PAY 100 TO ALICE`. She XORs that into A ⊕ B and Tuesday’s message falls out, in full. From now on, every message she can guess unlocks one she can’t.

FIG·03 — SAME REAGENT, TWO BEAKERS: MIX THEM AND K CANCELS OUT

In code, with `pour()` standing in for the cipher:

```
beaker_a = pour(b"PAY 100 TO ALICE", reagent)
beaker_b = pour(b"PAY 900 TO MALLO", reagent) # same bottle, second beaker

mixed = pour(beaker_a, beaker_b) # the reagent meets itself and vanishes
print(pour(mixed, b"PAY 100 TO ALICE")) # guess one, read the other: b'PAY 900 TO MALLO'
```

**The fix:** never let a key and nonce pair repeat. Use a fresh random nonce for every message, or a counter that is saved so it never goes back to 0, and let a well-tested library handle it.

This is not a classroom exercise. In 2016, a scan of the internet [found 184 HTTPS servers repeating nonces](https://eprint.iacr.org/2016/475), including financial institutions and a credit card company. Same mistake, much nicer lab coats.

## Mistake 2: a stranger’s drop

**The mistake:** your app encrypts the message but never checks whether anyone changed it on the way. Encryption on its own, like AES in counter (CTR) mode, only hides the message. It does not notice if someone changes it.

Your fixed app now sends `PAY 100 TO ALICE`, murky and with a fresh nonce. Mallory still cannot read it. But she knows your app’s format: the amount always sits at characters 5 to 7. So she does not read. She adds a drop.

Here is the loophole. The bank decrypts by pouring K again. K leaves, as always, but her drop does not: flipping a bit in the murky message flips the same bit in the clear one. To turn the `1` into a `9`, she XORs that one character with `1` ⊕ `9`, which is exactly the difference between the two. She never touches the key:

```
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

key, nonce = os.urandom(32), os.urandom(16)
aes_ctr = Cipher(algorithms.AES(key), modes.CTR(nonce))

def encrypt(data: bytes) -> bytes:
enc = aes_ctr.encryptor()
return enc.update(data) + enc.finalize()

def decrypt(data: bytes) -> bytes:
dec = aes_ctr.decryptor()
return dec.update(data) + dec.finalize()

ct = bytearray(encrypt(b"PAY 100 TO ALICE"))
ct[4] ^= ord("1") ^ ord("9") # attacker flips bits; never sees the key
print(decrypt(bytes(ct))) # b'PAY 900 TO ALICE', and no error
```

FIG·04 — THE REAGENT LEAVES, THE STRANGER’S DROP STAYS

The bank sees `PAY 900 TO ALICE`, a clean, valid instruction, and pays it. No error, no alarm. Encryption hides what a message says. It never promised nobody touched it. Those are two different jobs, like a lock and a tamper seal, and your app only fitted the lock.

**The fix:** seal the beaker. Authenticated encryption, such as AES-GCM or ChaCha20-Poly1305, adds a tag: a short checksum only the key holder can make. The bank checks the tag before it decrypts anything. Try the same drop and the seal breaks loudly:

```
import os
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

aead = AESGCM(AESGCM.generate_key(bit_length=256))
nonce = os.urandom(12) # 96 bits; never reuse with this key
ct = bytearray(aead.encrypt(nonce, b"PAY 100 TO ALICE", b"invoice-42"))

ct[4] ^= ord("1") ^ ord("9") # the same bit flip as before
try:
aead.decrypt(nonce, bytes(ct), b"invoice-42")
except InvalidTag:
print("rejected: ciphertext was modified")
```

The `b"invoice-42"` part is a label glued to the outside of the beaker: checked, but not encrypted. It ties this ciphertext to the record it belongs to, so nobody can swap beakers between orders.

## Mistake 3: the impatient inspector

Last one, and this one is not XOR’s fault. XOR is the cure. It is sneaky because the code looks fine.

**The mistake:** the bank’s server checks a secret with `==`. Say each request from the shop carries a signature, a secret code that proves it came from the shop, and the server does `if received == expected:`. Comparing with `==` works like an impatient inspector: it checks drop by drop and shouts “reject” at the first wrong one.

Here is the loophole. Mallory sends fake requests with made-up signatures and times each rejection. A guess with a wrong first byte is rejected instantly. A guess with the right first byte takes a tiny bit longer, because the inspector checked one more drop. So she tries all 256 values for byte 1 and keeps the slowest. Then byte 2, then byte 3. Each answer is only a few nanoseconds slower, so she repeats every guess thousands of times and averages. Byte by byte, she rebuilds the whole signature without ever knowing the secret, and the server accepts her fake request.

FIG·05 — STOPPING EARLY LEAKS HOW MANY DROPS WERE RIGHT

**The fix:** make the inspector check every drop, every time. XOR every pair of bytes, keep a running note of any difference, and only look at the note at the very end. Now a wrong first byte and a wrong last byte take the same time, and the stopwatch learns nothing:

```
import hmac

def xor_equal(a: bytes, b: bytes) -> bool:
# Shows the idea only: Python itself gives no timing guarantee.
if len(a) != len(b):
return False
diff = 0
for x, y in zip(a, b):
diff |= x ^ y # any differing bit sticks; no early exit
return diff == 0

def signature_ok(expected: bytes, received: bytes) -> bool:
return hmac.compare_digest(expected, received) # use this in real code

print(xor_equal(b"abc", b"abc"), xor_equal(b"abc", b"abd"), signature_ok(b"abc", b"abc"))
```

The loop shows the idea; Python itself makes no timing promises. In real code, call `hmac.compare_digest`, which exists for exactly this. Every serious language ships an equivalent.

## Lab rules

- Never brew your own reagent. Use AES-GCM or ChaCha20-Poly1305 from a maintained library, and never ship homemade “XOR encryption”.

- One bottle, one beaker. Never reuse a nonce with the same key. A random 12-byte nonce for AES-GCM is fine; a counter is fine if you can prove it never repeats, even across restarts.

- Seal every beaker. If you are not using authenticated encryption, you are not done.

- A broken seal is an incident, not a glitch. Log it, alert on it, and never fall back to an unsealed path.

- Send the impatient inspector home. Compare secrets with a constant-time function.

- Keep a test that adds one stranger’s drop to a ciphertext and expects it to be rejected.

## In the interview

### What does XOR do, and why can the same operation both encrypt and decrypt?

A strong answer: XOR outputs 1 where two bits differ and 0 where they match. Anything XORed with itself is 0, and anything XORed with 0 is unchanged, so (A ⊕ K) ⊕ K = A. The second pour cancels the first. Bonus points for saying it is cheap and has no carries between bits.

### Why is the one-time pad unbreakable, and why don’t we use it everywhere?

A strong answer: with a truly random key as long as the message and used once, every possible message of that length could have produced this same ciphertext, each with its own key, so the ciphertext gives nothing away. This has been proven mathematically. We don’t use it because you need as much secret key as data, delivered securely and never reused. Real ciphers grow a keystream from a short key instead.

### AES-GCM is secure. So what goes wrong if you reuse a nonce?

A strong answer: the same key and nonce produce the same keystream, so XORing the two ciphertexts cancels it and leaves the two messages XORed together, Mistake 1. With GCM it also weakens the seal, so an attacker can start forging messages. The fix: a fresh random 96-bit nonce per message, or a counter that provably never repeats.

XOR is the most obedient chemical in the lab. It does exactly what you pour it for, every single time. Which is why, in cryptography, the disasters never come from XOR itself. They come from pouring it twice, or forgetting to seal the beaker.

## References

- Claude Shannon, [Communication Theory of Secrecy Systems](https://archive.org/details/bstj28-4-656) (1949): the proof that a one-time pad gives nothing away.

- Gilbert Vernam, [US patent 1,310,719](https://patents.google.com/patent/US1310719A) (1919): the first cipher built on XOR, for teleprinters.

- [The Venona project](https://en.wikipedia.org/wiki/Venona_project): reused one-time pad pages let US codebreakers read Soviet messages for decades, Mistake 1 in the 1940s.

- Böck, Zauner, Devlin, Somorovsky and Jovanovic, [Nonce-Disrespecting Adversaries](https://eprint.iacr.org/2016/475) (2016): the scan that found 184 HTTPS servers reusing nonces.

- Python docs, [hmac.compare_digest](https://docs.python.org/3/library/hmac.html#hmac.compare_digest): the constant-time comparison from Mistake 3.

Animesh Pratap

---
Cite as: "XOR in Cryptography: The Reagent That Cancels Itself Out" — iAastha Research &amp; Consulting, https://iaastha.com/insights/concepts/xor-in-cryptography/
Site index for AI: https://iaastha.com/llms.txt
<!--/email_off-->